diff --git a/README.md b/README.md index 38208957..dc5ec024 100644 --- a/README.md +++ b/README.md @@ -138,7 +138,7 @@ The Gateway routes requests through the Provider Registry. Account Sync refreshe | Routing | Model discovery, Provider pinning, sticky sessions, quota/concurrency guards, and bounded failover | | Sessions | Stored responses, compact, prompt-cache affinity, and optional reasoning replay | | Media | Image generation/editing, video jobs, local archiving, and URL/Base64/SSE output | -| Egress | HTTP/SOCKS/Resin, subscriptions, probes, proxy pools, allocation, fallback, and FlareSolverr | +| Egress | HTTP/SOCKS/Resin and Trojan/VLESS/Shadowsocks/VMess tunnels, subscriptions, probes, proxy pools, allocation, fallback, and FlareSolverr | | Operations | Dashboard, model routes, client keys, audits, runtime settings, and media libraries | ### Provider boundaries @@ -147,9 +147,9 @@ The Gateway routes requests through the Provider Registry. Account Sync refreshe | :-- | :-- | :-- | :-- | | Grok Build | OAuth / Device OAuth | Discovered per account | Responses, Chat, Messages, compact, stored responses, paid-account video | | Grok Web | SSO | Built-in, filtered by tier | Responses, Chat, Messages, stored responses, images, image editing, video | -| Grok Console | SSO | Built-in | Stateless Responses, Chat, Messages, images, image editing, video | +| Grok Console | SSO | Built-in | Stateless Responses, Chat, Messages, images, image editing, video, TTS, STT, Realtime | -Each Provider keeps its own credentials, quota, health, cooldown, concurrency, and model capabilities. Failover stays within the selected Provider. +Each Provider keeps its own credentials, quota, health, cooldown, concurrency, and model capabilities. Account retries stay within one route; when one public model ID intentionally aggregates multiple routes, the gateway may select another schedulable route without mixing Provider state. ## Quick start @@ -258,13 +258,13 @@ Web uses a built-in catalog filtered by account tier; higher tiers inherit lower | `grok-chat-expert` | Conversation | Super | Chat Completions, Responses, Messages | | `grok-chat-heavy` | Conversation | Heavy | Chat Completions, Responses, Messages | | `grok-imagine-image-lite` | Image | Basic | Images Generations | -| `grok-imagine-image-quality-lite` | Image | Super | Images Generations | +| `grok-imagine-image-quality-lite` | Image | Basic | Images Generations | | `grok-imagine-image-edit` | Image Edit | Super | Images Edits | | `grok-imagine-video` | Video | Super | Videos | ### Grok Console -Console uses the catalog built into the current release. Conversation forwarding is stateless, while image and video models use the standard xAI resource APIs. +Console uses the catalog built into the current release. Conversation forwarding is stateless, while image, video, and voice use the standard xAI resource APIs. | Model | Type | Gateway surfaces | | :-- | :-- | :-- | @@ -276,7 +276,11 @@ Console uses the catalog built into the current release. Conversation forwarding | `grok-build-0.1` | Conversation | Chat Completions, Responses, Messages | | `grok-imagine-image` | Image, Image Edit | Images Generations, Images Edits | | `grok-imagine-image-quality` | Image, Image Edit | Images Generations, Images Edits | +| `grok-imagine-image-2.0` | Image, Image Edit | Images Generations, Images Edits | | `grok-imagine-video` | Video | Videos | +| `grok-imagine-video-1.5` | Video | Video generation, including Free Console accounts | +| `grok-voice-latest`, `grok-voice-think-fast-2.0`, `grok-voice-think-fast-1.0` | Voice | TTS and Realtime WebSocket proxy | +| `grok-stt` | Voice | STT and OpenAI-compatible audio transcriptions | Generation and editing capabilities for the same Console image model are grouped into one logical model row; no separate `-edit` model copy is required. @@ -309,10 +313,15 @@ Authorization: Bearer g2a_xxx_xxx | `POST` | `/v1/messages` | Anthropic Messages JSON/SSE | | `POST` | `/v1/images/generations`, `/v1/images/edits` | Generate or edit images | | `POST`, `GET` | `/v1/videos/*` | Create and inspect video jobs | +| `POST` | `/v1/tts`, `/v1/audio/speech`, `/v1/audio/tasks` | Synthesize speech | +| `POST` | `/v1/stt`, `/v1/audio/transcriptions` | Transcribe audio | +| `GET` | `/v1/stt`, `/v1/realtime` | Proxy voice WebSocket sessions | | `GET` | `/v1/media/images/{asset_id}`, `/v1/media/videos/{asset_id}` | Read archived media | Stored responses and compact depend on the selected Provider. The signed-in admin console provides live examples at `/docs`; Swagger is available only when `server.swaggerEnabled: true`. +`/v1/audio/transcriptions` supports `json` (default), `verbose_json`, and `text`. Video edit/extension routes must resolve to Console `grok-imagine-video`; custom public model names remain supported. Monetary billing is applied only when the gateway can reliably measure the official pricing unit: TTS is reserved and settled from its input character count, while REST and streaming STT are settled from the actual audio duration returned by a successful response. Because STT duration is known only after completion, concurrent requests may briefly take a billing-limited key beyond its spend limit. Realtime, video edits/extensions, and custom routes without a recognized official price are currently audited as unpriced; they remain callable and do not consume the spend limit. + Client keys support model allowlists and optional RPM, concurrency, spend, and expiry limits. ```bash @@ -330,7 +339,8 @@ curl http://127.0.0.1:8000/v1/responses \ Egress nodes are scoped to Build, Web, Console, or Web assets. The admin console supports: -- HTTP, HTTPS, SOCKS4/4A, SOCKS5/5H, and Resin +- HTTP, HTTPS, SOCKS4/4A, SOCKS5/5H, Resin, Trojan, VLESS, Shadowsocks, and VMess +- TCP, WebSocket, and TLS tunnel transports; unsupported variants are rejected during import - Subscription and text/Base64 import - Batch probes, filtering, deletion, assignment, and balancing - Fallback per scope: none, direct, or a fixed node @@ -338,6 +348,8 @@ Egress nodes are scoped to Build, Web, Console, or Web assets. The admin console - Immediate recovery probes after fixed-proxy transport failures, with per-node coalescing and bounded waiting for fast retry - Optional [Egress Quality Guard](./tools/egress-quality-guard/README.md) for active per-node model probes, guarded quarantine, and recovery; enable it with the built-in `quality-guard` Compose profile +Hysteria and TUIC are not supported yet. FlareSolverr accepts only HTTP/SOCKS proxy URLs, so automatic clearance refresh cannot use a tunnel share URL directly. + To enable the guard, add a `qualityGuard` section to `config.yaml`, then start the profile. The main service creates and reuses a non-exportable system probe identity automatically: diff --git a/README.zh-CN.md b/README.zh-CN.md index 38aff70d..7aded223 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -139,7 +139,7 @@ flowchart LR | 路由 | 模型发现、Provider 限定、会话粘滞、额度/并发门禁和有界切换 | | 会话 | stored response、compact、Prompt Cache 亲和与可选 reasoning replay | | 媒体 | 图片生成与编辑、视频任务、本地归档及 URL/Base64/SSE 输出 | -| 出口 | HTTP/SOCKS/Resin、订阅、探测、代理池、调配、回退与 FlareSolverr | +| 出口 | HTTP/SOCKS/Resin 与 Trojan/VLESS/Shadowsocks/VMess 隧道、订阅、探测、代理池、调配、回退与 FlareSolverr | | 运维 | Dashboard、模型路由、客户端密钥、审计、运行设置和媒体库 | ### Provider 边界 @@ -148,9 +148,9 @@ flowchart LR | :-- | :-- | :-- | :-- | | Grok Build | OAuth / 设备授权 | 按账号动态发现 | Responses、Chat、Messages、compact、stored response、付费账号视频 | | Grok Web | SSO | 内置并按等级过滤 | Responses、Chat、Messages、stored response、图片、图片编辑、视频 | -| Grok Console | SSO | 内置 | 无状态 Responses、Chat、Messages、图片、图片编辑、视频 | +| Grok Console | SSO | 内置 | 无状态 Responses、Chat、Messages、图片、图片编辑、视频、TTS、STT、Realtime | -三个 Provider 独立维护凭据、额度、健康、冷却、并发与模型能力。故障切换不会跨 Provider 混用账号状态。 +三个 Provider 独立维护凭据、额度、健康、冷却、并发与模型能力。单条路由的账号重试始终留在当前 Provider;当同一对外模型名主动聚合了多条路由时,网关可选择另一条可调度路由,但不会跨 Provider 混用账号状态。 ## 快速部署 @@ -259,13 +259,13 @@ Web 使用内置目录并按账号等级过滤;更高等级继承低等级模 | `grok-chat-expert` | 对话 | Super | Chat Completions、Responses、Messages | | `grok-chat-heavy` | 对话 | Heavy | Chat Completions、Responses、Messages | | `grok-imagine-image-lite` | 图像 | Basic | Images Generations | -| `grok-imagine-image-quality-lite` | 图像 | Super | Images Generations | +| `grok-imagine-image-quality-lite` | 图像 | Basic | Images Generations | | `grok-imagine-image-edit` | 图像编辑 | Super | Images Edits | | `grok-imagine-video` | 视频 | Super | Videos | ### Grok Console -Console 使用当前版本内置目录。对话为无状态转发;图片和视频使用 xAI 标准资源接口。 +Console 使用当前版本内置目录。对话为无状态转发;图片、视频和语音使用 xAI 标准资源接口。 | 模型 | 类型 | 网关接口能力 | | :-- | :-- | :-- | @@ -277,7 +277,11 @@ Console 使用当前版本内置目录。对话为无状态转发;图片和视 | `grok-build-0.1` | 对话 | Chat Completions、Responses、Messages | | `grok-imagine-image` | 图像、图像编辑 | Images Generations、Images Edits | | `grok-imagine-image-quality` | 图像、图像编辑 | Images Generations、Images Edits | +| `grok-imagine-image-2.0` | 图像、图像编辑 | Images Generations、Images Edits | | `grok-imagine-video` | 视频 | Videos | +| `grok-imagine-video-1.5` | 视频 | 视频生成,包括 Free Console 账号 | +| `grok-voice-latest`、`grok-voice-think-fast-2.0`、`grok-voice-think-fast-1.0` | 语音 | TTS 和 Realtime WebSocket 代理 | +| `grok-stt` | 语音 | STT 和 OpenAI 兼容的音频转录 | 同一个 Console 图片模型的生成与编辑能力会聚合展示为一条逻辑模型,不需要创建 `-edit` 模型副本。 @@ -310,10 +314,15 @@ Authorization: Bearer g2a_xxx_xxx | `POST` | `/v1/messages` | Anthropic Messages JSON/SSE | | `POST` | `/v1/images/generations`、`/v1/images/edits` | 生成或编辑图片 | | `POST`、`GET` | `/v1/videos/*` | 创建和查询视频任务 | +| `POST` | `/v1/tts`、`/v1/audio/speech`、`/v1/audio/tasks` | 语音合成 | +| `POST` | `/v1/stt`、`/v1/audio/transcriptions` | 音频转录 | +| `GET` | `/v1/stt`、`/v1/realtime` | 代理语音 WebSocket 会话 | | `GET` | `/v1/media/images/{asset_id}`、`/v1/media/videos/{asset_id}` | 读取归档媒体 | stored response 和 compact 取决于最终 Provider。登录管理端后可在 `/docs` 查看当前模型与调用示例;仅在 `server.swaggerEnabled: true` 时提供 Swagger。 +`/v1/audio/transcriptions` 支持 `json`(默认)、`verbose_json` 和 `text`。视频编辑与延长按实际路由校验 Console `grok-imagine-video`,对外模型名仍可自定义。金额计费以网关能够可靠测量的官方计价单位为准:TTS 按输入字符数预留并结算,REST 与流式 STT 按成功响应返回的实际音频时长结算。STT 时长只能在请求完成后获得,因此并发中的请求可能使有限额 Key 短暂超过金额上限。Realtime、视频编辑与延长,以及未收录官方定价的自定义路由当前记录为“未计费”,保持可调用且不消耗金额额度。 + 客户端密钥支持模型白名单,以及可选的 RPM、并发、用量和截止日期限制。 ```bash @@ -331,7 +340,8 @@ curl http://127.0.0.1:8000/v1/responses \ 出口节点按 Build、Web、Console 或 Web 资源隔离。管理端支持: -- HTTP、HTTPS、SOCKS4/4A、SOCKS5/5H 与 Resin +- HTTP、HTTPS、SOCKS4/4A、SOCKS5/5H、Resin、Trojan、VLESS、Shadowsocks 与 VMess +- 隧道协议支持 TCP、WebSocket 和 TLS,未实现的传输形态会在导入时拒绝 - 订阅和文本/Base64 导入 - 批量探测、筛选、删除、分配与均衡 - 按作用域配置无回退、直连或固定节点 @@ -339,6 +349,8 @@ curl http://127.0.0.1:8000/v1/responses \ - 固定代理传输失败后立即复测;同节点复测自动合并,后续绑定请求限时等待并在恢复后快速重试 - 可选的[出口质量守护程序](./tools/egress-quality-guard/README.zh-CN.md),支持逐节点模型探测、防误杀隔离和自动恢复;通过内置的 `quality-guard` Compose profile 按需启用 +Hysteria 与 TUIC 暂未支持。FlareSolverr 仅接受 HTTP/SOCKS 代理地址,因此自动刷新 Clearance 暂不能直接使用隧道分享链接。 + 首次启用时只需在 `config.yaml` 中增加 `qualityGuard` 并启动 profile。主程序会自动创建并稳定复用不可导出的系统探测身份: ```yaml diff --git a/backend/docs/docs.go b/backend/docs/docs.go index 0585d1ee..bcae057f 100644 --- a/backend/docs/docs.go +++ b/backend/docs/docs.go @@ -497,6 +497,102 @@ const docTemplate = `{ } } }, + "/v1/videos/edits": { + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Videos" + ], + "summary": "创建异步视频编辑任务", + "parameters": [ + { + "description": "请求", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/httpserver.SwaggerVideoGenerationRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "400": { + "description": "Bad Request", + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + }, + "/v1/videos/extensions": { + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Videos" + ], + "summary": "创建异步视频延长任务", + "parameters": [ + { + "description": "请求", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/httpserver.SwaggerVideoGenerationRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "400": { + "description": "Bad Request", + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + }, "/v1/videos/generations": { "post": { "security": [ @@ -754,6 +850,15 @@ const docTemplate = `{ } } }, + "httpserver.SwaggerVideoAudioInput": { + "type": "object", + "properties": { + "voice_id": { + "type": "string", + "example": "eve" + } + } + }, "httpserver.SwaggerVideoGenerationRequest": { "type": "object", "properties": { @@ -765,6 +870,9 @@ const docTemplate = `{ "type": "integer", "example": 8 }, + "image": { + "$ref": "#/definitions/httpserver.SwaggerVideoMediaInput" + }, "model": { "type": "string", "example": "grok-imagine-video" @@ -773,9 +881,37 @@ const docTemplate = `{ "type": "string", "example": "A cinematic tracking shot in the rain" }, + "reference_audios": { + "type": "array", + "items": { + "$ref": "#/definitions/httpserver.SwaggerVideoAudioInput" + } + }, + "reference_images": { + "type": "array", + "items": { + "$ref": "#/definitions/httpserver.SwaggerVideoMediaInput" + } + }, "resolution": { "type": "string", "example": "720p" + }, + "video": { + "$ref": "#/definitions/httpserver.SwaggerVideoMediaInput" + } + } + }, + "httpserver.SwaggerVideoMediaInput": { + "type": "object", + "properties": { + "file_id": { + "type": "string", + "example": "file_123" + }, + "url": { + "type": "string", + "example": "https://example.com/input.png" } } } diff --git a/backend/docs/swagger.json b/backend/docs/swagger.json index 4124d5ec..1db79f33 100644 --- a/backend/docs/swagger.json +++ b/backend/docs/swagger.json @@ -490,6 +490,102 @@ } } }, + "/v1/videos/edits": { + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Videos" + ], + "summary": "创建异步视频编辑任务", + "parameters": [ + { + "description": "请求", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/httpserver.SwaggerVideoGenerationRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "400": { + "description": "Bad Request", + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + }, + "/v1/videos/extensions": { + "post": { + "security": [ + { + "BearerAuth": [] + } + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Videos" + ], + "summary": "创建异步视频延长任务", + "parameters": [ + { + "description": "请求", + "name": "request", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/httpserver.SwaggerVideoGenerationRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "400": { + "description": "Bad Request", + "schema": { + "type": "object", + "additionalProperties": true + } + } + } + } + }, "/v1/videos/generations": { "post": { "security": [ @@ -747,6 +843,15 @@ } } }, + "httpserver.SwaggerVideoAudioInput": { + "type": "object", + "properties": { + "voice_id": { + "type": "string", + "example": "eve" + } + } + }, "httpserver.SwaggerVideoGenerationRequest": { "type": "object", "properties": { @@ -758,6 +863,9 @@ "type": "integer", "example": 8 }, + "image": { + "$ref": "#/definitions/httpserver.SwaggerVideoMediaInput" + }, "model": { "type": "string", "example": "grok-imagine-video" @@ -766,9 +874,37 @@ "type": "string", "example": "A cinematic tracking shot in the rain" }, + "reference_audios": { + "type": "array", + "items": { + "$ref": "#/definitions/httpserver.SwaggerVideoAudioInput" + } + }, + "reference_images": { + "type": "array", + "items": { + "$ref": "#/definitions/httpserver.SwaggerVideoMediaInput" + } + }, "resolution": { "type": "string", "example": "720p" + }, + "video": { + "$ref": "#/definitions/httpserver.SwaggerVideoMediaInput" + } + } + }, + "httpserver.SwaggerVideoMediaInput": { + "type": "object", + "properties": { + "file_id": { + "type": "string", + "example": "file_123" + }, + "url": { + "type": "string", + "example": "https://example.com/input.png" } } } diff --git a/backend/docs/swagger.yaml b/backend/docs/swagger.yaml index c0a724b4..4aa5f8a4 100644 --- a/backend/docs/swagger.yaml +++ b/backend/docs/swagger.yaml @@ -118,6 +118,12 @@ definitions: example: false type: boolean type: object + httpserver.SwaggerVideoAudioInput: + properties: + voice_id: + example: eve + type: string + type: object httpserver.SwaggerVideoGenerationRequest: properties: aspect_ratio: @@ -126,15 +132,36 @@ definitions: duration: example: 8 type: integer + image: + $ref: '#/definitions/httpserver.SwaggerVideoMediaInput' model: example: grok-imagine-video type: string prompt: example: A cinematic tracking shot in the rain type: string + reference_audios: + items: + $ref: '#/definitions/httpserver.SwaggerVideoAudioInput' + type: array + reference_images: + items: + $ref: '#/definitions/httpserver.SwaggerVideoMediaInput' + type: array resolution: example: 720p type: string + video: + $ref: '#/definitions/httpserver.SwaggerVideoMediaInput' + type: object + httpserver.SwaggerVideoMediaInput: + properties: + file_id: + example: file_123 + type: string + url: + example: https://example.com/input.png + type: string type: object info: contact: {} @@ -475,6 +502,66 @@ paths: summary: 查询异步视频任务 tags: - Videos + /v1/videos/edits: + post: + consumes: + - application/json + parameters: + - description: 请求 + in: body + name: request + required: true + schema: + $ref: '#/definitions/httpserver.SwaggerVideoGenerationRequest' + produces: + - application/json + responses: + "200": + description: OK + schema: + additionalProperties: + type: string + type: object + "400": + description: Bad Request + schema: + additionalProperties: true + type: object + security: + - BearerAuth: [] + summary: 创建异步视频编辑任务 + tags: + - Videos + /v1/videos/extensions: + post: + consumes: + - application/json + parameters: + - description: 请求 + in: body + name: request + required: true + schema: + $ref: '#/definitions/httpserver.SwaggerVideoGenerationRequest' + produces: + - application/json + responses: + "200": + description: OK + schema: + additionalProperties: + type: string + type: object + "400": + description: Bad Request + schema: + additionalProperties: true + type: object + security: + - BearerAuth: [] + summary: 创建异步视频延长任务 + tags: + - Videos /v1/videos/generations: post: consumes: diff --git a/backend/go.mod b/backend/go.mod index 7cdc90a9..ea822164 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -3,15 +3,19 @@ module github.com/chenyme/grok2api/backend go 1.26 require ( + github.com/Asutorufa/yuhaiin v0.3.8 github.com/bdandy/go-socks4 v1.2.3 github.com/bogdanfinn/fhttp v0.6.8 github.com/bogdanfinn/tls-client v1.15.1 github.com/bogdanfinn/websocket v1.5.5-barnius + github.com/coder/websocket v1.8.14 github.com/gin-gonic/gin v1.12.0 github.com/glebarez/sqlite v1.11.0 github.com/golang-jwt/jwt/v5 v5.3.1 github.com/google/uuid v1.6.0 + github.com/gorilla/websocket v1.5.3 github.com/redis/go-redis/v9 v9.21.0 + github.com/shadowsocks/go-shadowsocks2 v0.1.5 github.com/swaggo/files v1.0.1 github.com/swaggo/gin-swagger v1.6.1 github.com/swaggo/swag v1.16.6 @@ -30,6 +34,7 @@ require ( github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect github.com/andybalholm/brotli v1.2.0 // indirect github.com/bdandy/go-errors v1.2.2 // indirect + github.com/beorn7/perks v1.0.1 // indirect github.com/bogdanfinn/quic-go-utls v1.0.9-utls // indirect github.com/bogdanfinn/utls v1.7.7-barnius // indirect github.com/bytedance/gopkg v0.1.3 // indirect @@ -65,21 +70,30 @@ require ( github.com/mattn/go-isatty v0.0.20 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect + github.com/prometheus/client_golang v1.20.5 // indirect + github.com/prometheus/client_model v0.6.1 // indirect + github.com/prometheus/common v0.55.0 // indirect + github.com/prometheus/procfs v0.15.1 // indirect github.com/quic-go/qpack v0.6.0 // indirect github.com/quic-go/quic-go v0.59.0 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3 // indirect github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.3.1 // indirect go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect go.uber.org/atomic v1.11.0 // indirect golang.org/x/arch v0.22.0 // indirect + golang.org/x/exp v0.0.0-20241204233417-43b7b7cde48d // indirect golang.org/x/mod v0.37.0 // indirect golang.org/x/sys v0.47.0 // indirect golang.org/x/text v0.40.0 // indirect + golang.org/x/time v0.9.0 // indirect golang.org/x/tools v0.47.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect + gvisor.dev/gvisor v0.0.0-20241220022509-4690b2e35d70 // indirect modernc.org/libc v1.22.5 // indirect modernc.org/mathutil v1.5.0 // indirect modernc.org/memory v1.5.0 // indirect diff --git a/backend/go.sum b/backend/go.sum index e91d31b7..c4c442f6 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -1,3 +1,5 @@ +github.com/Asutorufa/yuhaiin v0.3.8 h1:HrEqvXNVYUviL2+Zu01AxRJiPayZa7lZvoYQlvgMkgc= +github.com/Asutorufa/yuhaiin v0.3.8/go.mod h1:fLEwJOwgPumPQvGgJNJn392c63GyAaP4QCkZTj6LRyo= github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= @@ -10,6 +12,8 @@ github.com/bdandy/go-errors v1.2.2 h1:WdFv/oukjTJCLa79UfkGmwX7ZxONAihKu4V0mLIs11 github.com/bdandy/go-errors v1.2.2/go.mod h1:NkYHl4Fey9oRRdbB1CoC6e84tuqQHiqrOcZpqFEkBxM= github.com/bdandy/go-socks4 v1.2.3 h1:Q6Y2heY1GRjCtHbmlKfnwrKVU/k81LS8mRGLRlmDlic= github.com/bdandy/go-socks4 v1.2.3/go.mod h1:98kiVFgpdogR8aIGLWLvjDVZ8XcKPsSI/ypGrO+bqHI= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bogdanfinn/fhttp v0.6.8 h1:LiQyHOY3i0QoxxNB7nq27/nGNNbtPj0fuBPozhR7Ws4= github.com/bogdanfinn/fhttp v0.6.8/go.mod h1:A+EKDzMx2hb4IUbMx4TlkoHnaJEiLl8r/1Ss1Y+5e5M= github.com/bogdanfinn/quic-go-utls v1.0.9-utls h1:tV6eDEiRbRCcepALSzxR94JUVD3N3ACIiRLgyc2Ep8s= @@ -34,6 +38,8 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UF github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= +github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g= +github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= @@ -79,10 +85,12 @@ github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArs github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ= -github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo= +github.com/google/pprof v0.0.0-20240910150728-a0b0bb1d4134 h1:c5FlPPgxOn7kJz3VoPLkQYQXGBS3EklQ4Zfi57uOuqQ= +github.com/google/pprof v0.0.0-20240910150728-a0b0bb1d4134/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= @@ -125,11 +133,21 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v1.20.5 h1:cxppBPuYhUnsO6yo/aoRol4L7q7UFfdm+bR9r+8l63Y= +github.com/prometheus/client_golang v1.20.5/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE= +github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E= +github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY= +github.com/prometheus/common v0.55.0 h1:KEi6DK7lXW/m7Ig5i47x0vRzuBsHuvJdi5ee6Y3G1dc= +github.com/prometheus/common v0.55.0/go.mod h1:2SECS4xJG1kd8XF9IcM1gMX6510RAEL65zxzNImwdc8= +github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= +github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw= @@ -139,8 +157,12 @@ github.com/redis/go-redis/v9 v9.21.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3b github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3 h1:f/FNXud6gA3MNr8meMVVGxhp+QBTqY91tM8HjEuMjGg= +github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3/go.mod h1:HgjTstvQsPGkxUsCd2KWxErBblirPizecHcpD3ffK+s= github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= +github.com/shadowsocks/go-shadowsocks2 v0.1.5 h1:PDSQv9y2S85Fl7VBeOMF9StzeXZyK1HakRm86CUbr28= +github.com/shadowsocks/go-shadowsocks2 v0.1.5/go.mod h1:AGGpIoek4HRno4xzyFiAtLHkOpcoznZEkAccaI/rplM= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -180,12 +202,16 @@ go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI= golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= +golang.org/x/exp v0.0.0-20241204233417-43b7b7cde48d h1:0olWaB5pg3+oychR51GUVCEsGkeCU/2JxjBgIo4f3M0= +golang.org/x/exp v0.0.0-20241204233417-43b7b7cde48d/go.mod h1:qj5a5QZpwLU2NLQudwIN5koi3beDhSAlJwa67PuM98c= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= @@ -199,6 +225,7 @@ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -209,6 +236,7 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -219,6 +247,8 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= +golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= +golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= @@ -245,6 +275,8 @@ gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ= gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8= gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo= gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs= +gvisor.dev/gvisor v0.0.0-20241220022509-4690b2e35d70 h1:YAGAbMnGNRna7ajnsDuRjV1o/Mc2LDwEliRemNFDVF4= +gvisor.dev/gvisor v0.0.0-20241220022509-4690b2e35d70/go.mod h1:5DMfjtclAbTIjbXqO1qCe2K5GKKxWz2JHvCChuTcJEM= modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE= modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY= modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ= diff --git a/backend/internal/app/console_routes_test.go b/backend/internal/app/console_routes_test.go index 01331b52..91f5d002 100644 --- a/backend/internal/app/console_routes_test.go +++ b/backend/internal/app/console_routes_test.go @@ -32,12 +32,23 @@ func TestConsoleRoutesUseStableProviderNamespace(t *testing.T) { if seen["Console/grok-4.3"] == nil { t.Fatal("canonical Console/grok-4.3 route is missing") } - for _, modelID := range []string{"Console/grok-imagine-image-quality", "Console/grok-imagine-image"} { + for _, modelID := range []string{"Console/grok-imagine-image", "Console/grok-imagine-image-quality", "Console/grok-imagine-image-2.0"} { if !seen[modelID]["image"] || !seen[modelID]["image_edit"] { t.Fatalf("Console image route capabilities for %s = %#v", modelID, seen[modelID]) } } + for _, modelID := range []string{"Console/grok-voice-latest", "Console/grok-voice-think-fast-2.0", "Console/grok-voice-think-fast-1.0"} { + if !seen[modelID]["realtime"] || !seen[modelID]["tts"] { + t.Fatalf("Console voice route capabilities for %s = %#v", modelID, seen[modelID]) + } + } + if !seen["Console/grok-stt"]["stt"] { + t.Fatal("Console STT route is missing") + } if !seen["Console/grok-imagine-video"]["video"] { t.Fatal("Console video route is missing") } + if !seen["Console/grok-imagine-video-1.5"]["video"] { + t.Fatal("Console video 1.5 route is missing") + } } diff --git a/backend/internal/application/account/quota_refresh_test.go b/backend/internal/application/account/quota_refresh_test.go index 4a3bf7df..a459ed56 100644 --- a/backend/internal/application/account/quota_refresh_test.go +++ b/backend/internal/application/account/quota_refresh_test.go @@ -24,10 +24,12 @@ func TestWebQuotaRefreshDeduplicatesPerMode(t *testing.T) { service.QueueQuotaRefresh(43, "console") service.QueueQuotaRefresh(43, "console_image") service.QueueQuotaRefresh(43, "console_video") + service.QueueQuotaRefresh(44, accountdomain.QuotaModeWebImagePro) + service.QueueQuotaRefresh(44, accountdomain.QuotaModeWebVideo720p) service.quotaRefreshMu.Lock() defer service.quotaRefreshMu.Unlock() - if len(service.quotaRefreshes) != 5 { + if len(service.quotaRefreshes) != 6 { t.Fatalf("refresh states = %#v", service.quotaRefreshes) } if service.quotaRefreshes["42:fast"].generation != 2 || !service.quotaRefreshes["42:fast"].queued { @@ -44,7 +46,10 @@ func TestWebQuotaRefreshDeduplicatesPerMode(t *testing.T) { t.Fatalf("Console %s refresh state is invalid: %#v", mode, state) } } - if len(service.quotaRefreshQueue) != 5 { + if state := service.quotaRefreshes["44:"+accountdomain.QuotaGroupWebImagine]; state == nil || state.generation != 2 || !state.queued { + t.Fatalf("Imagine group refresh state is invalid: %#v", state) + } + if len(service.quotaRefreshQueue) != 6 { t.Fatalf("queued refreshes = %d", len(service.quotaRefreshQueue)) } } @@ -354,6 +359,58 @@ func TestRefreshQuotaModeDoesNotTriggerFullProviderSyncForAutoTier(t *testing.T) } } +func TestRefreshWebImagineQuotaModeAtomicallyReplacesGroup(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "imagine-quota-group.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = database.Close() }) + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accounts := relational.NewAccountRepository(database) + credential, _, err := accounts.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderWeb, AuthType: accountdomain.AuthTypeSSO, + Name: "web-imagine", SourceKey: "web-imagine", EncryptedAccessToken: "encrypted", + Enabled: true, AuthStatus: accountdomain.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + if err := accounts.SaveQuotaWindows(ctx, credential.ID, accountdomain.WebTierSuper, now, []accountdomain.QuotaWindow{ + {AccountID: credential.ID, Mode: "weekly", Remaining: 90, Total: 100, UpdatedAt: now}, + {AccountID: credential.ID, Mode: accountdomain.QuotaModeWebImagePro, Remaining: 4, UpdatedAt: now}, + {AccountID: credential.ID, Mode: accountdomain.QuotaModeWebVideo720p, Remaining: 1, UpdatedAt: now}, + }); err != nil { + t.Fatal(err) + } + adapter := &imagineQuotaGroupAdapter{} + service := NewService(accounts, nil, nil, nil, provider.NewRegistry(adapter), nil, nil) + window, err := service.RefreshQuotaMode(ctx, credential.ID, accountdomain.QuotaModeWebImagePro) + if err != nil { + t.Fatal(err) + } + if window.Remaining != 3 || adapter.calls.Load() != 1 { + t.Fatalf("window = %#v, calls = %d", window, adapter.calls.Load()) + } + stored, err := accounts.GetQuotaWindows(ctx, []uint64{credential.ID}) + if err != nil { + t.Fatal(err) + } + byMode := make(map[string]accountdomain.QuotaWindow) + for _, current := range stored[credential.ID] { + byMode[current.Mode] = current + } + if byMode["weekly"].Remaining != 90 || byMode[accountdomain.QuotaModeWebImagePro].Remaining != 3 { + t.Fatalf("stored = %#v", stored[credential.ID]) + } + if _, exists := byMode[accountdomain.QuotaModeWebVideo720p]; exists { + t.Fatalf("stale video_720p window survived group replacement: %#v", stored[credential.ID]) + } +} + func TestRefreshConsoleQuotaModePersistsCompleteUsageSnapshot(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "console-quota-mode.db")) @@ -839,6 +896,36 @@ type quotaCountingAdapter struct { modeRelease chan struct{} } +type imagineQuotaGroupAdapter struct { + calls atomic.Int64 +} + +func (a *imagineQuotaGroupAdapter) Provider() accountdomain.Provider { + return accountdomain.ProviderWeb +} + +func (a *imagineQuotaGroupAdapter) Definition() provider.Definition { + return provider.Definition{ + Provider: accountdomain.ProviderWeb, ModelNamespace: accountdomain.ProviderWeb.ModelNamespace(), + Quota: provider.QuotaRemoteWindow, Credential: provider.CredentialSurface{AuthType: accountdomain.AuthTypeSSO}, + } +} + +func (a *imagineQuotaGroupAdapter) SyncQuotaGroup(_ context.Context, credential accountdomain.Credential, group string) (provider.QuotaGroupSnapshot, error) { + a.calls.Add(1) + if group != accountdomain.QuotaGroupWebImagine { + return provider.QuotaGroupSnapshot{}, errors.New("unexpected group") + } + now := time.Now().UTC() + return provider.QuotaGroupSnapshot{ + Group: group, Modes: accountdomain.WebImagineQuotaModes(), SyncedAt: now, + Windows: []accountdomain.QuotaWindow{{ + AccountID: credential.ID, Mode: accountdomain.QuotaModeWebImagePro, Remaining: 3, + WindowSeconds: 86400, SyncedAt: &now, Source: accountdomain.QuotaSourceUpstream, UpdatedAt: now, + }}, + }, nil +} + type consoleQuotaSnapshotAdapter struct { fullCalls atomic.Int64 modeCalls atomic.Int64 diff --git a/backend/internal/application/account/service.go b/backend/internal/application/account/service.go index 62931634..afad1f0b 100644 --- a/backend/internal/application/account/service.go +++ b/backend/internal/application/account/service.go @@ -134,6 +134,7 @@ type quotaRefreshRequest struct { type quotaRefreshResult struct { Credential accountdomain.Credential Windows []accountdomain.QuotaWindow + Modes []string } type QuotaRefreshStats struct { @@ -2833,6 +2834,9 @@ func (s *Service) RefreshQuotaMode(ctx context.Context, id uint64, mode string) mode = strings.TrimSpace(mode) key := quotaSyncKey(id, mode) result, err, _ := s.quotaSyncs.Do(key, func() (any, error) { + if isWebImagineQuotaMode(mode) { + return s.refreshQuotaGroup(ctx, id, accountdomain.QuotaGroupWebImagine) + } return s.refreshQuotaMode(ctx, id, mode) }) if err != nil { @@ -2842,19 +2846,26 @@ func (s *Service) RefreshQuotaMode(ctx context.Context, id uint64, mode string) if !ok { return accountdomain.QuotaWindow{}, fmt.Errorf("Provider 模式额度同步返回类型无效") } + if len(refreshed.Modes) > 0 { + if err := s.reconcileQuotaGroupWindows(ctx, refreshed.Credential.Provider, id, refreshed.Modes, refreshed.Windows); err != nil { + return accountdomain.QuotaWindow{}, err + } + } window, ok := quotaWindowByMode(refreshed.Windows, mode) if !ok { return accountdomain.QuotaWindow{}, fmt.Errorf("Provider usage 响应缺少 %s 额度", mode) } - if refreshed.Credential.Provider == accountdomain.ProviderConsole { + if len(refreshed.Modes) == 0 && refreshed.Credential.Provider == accountdomain.ProviderConsole { // One Console request refreshes all three authoritative windows. Reconcile // every matching recovery event so externally consumed media quota cannot // remain unscheduled merely because a different kind triggered the refresh. if err := s.reconcileQuotaRecoveryWindows(ctx, refreshed.Credential.Provider, id, refreshed.Windows); err != nil { return window, err } - } else if err := s.reconcileQuotaRecoveryWindow(ctx, refreshed.Credential.Provider, id, window); err != nil { - return window, err + } else if len(refreshed.Modes) == 0 { + if err := s.reconcileQuotaRecoveryWindow(ctx, refreshed.Credential.Provider, id, window); err != nil { + return window, err + } } return window, nil } @@ -2866,6 +2877,9 @@ func (s *Service) ProbeQuotaMode(ctx context.Context, id uint64, mode string) (a mode = strings.TrimSpace(mode) key := quotaSyncKey(id, mode) result, err, _ := s.quotaSyncs.Do(key, func() (any, error) { + if isWebImagineQuotaMode(mode) { + return s.refreshQuotaGroup(ctx, id, accountdomain.QuotaGroupWebImagine) + } return s.refreshQuotaMode(ctx, id, mode) }) if err != nil { @@ -2882,6 +2896,34 @@ func (s *Service) ProbeQuotaMode(ctx context.Context, id uint64, mode string) (a return window, nil } +func (s *Service) refreshQuotaGroup(ctx context.Context, id uint64, group string) (quotaRefreshResult, error) { + value, err := s.accounts.Get(ctx, id) + if err != nil { + return quotaRefreshResult{}, mapRepositoryError(err) + } + adapter, ok := s.providers.QuotaGroup(value.Provider) + if !ok { + return quotaRefreshResult{}, fmt.Errorf("%s quota group Provider 未注册", value.Provider) + } + snapshot, err := adapter.SyncQuotaGroup(ctx, value, group) + if err != nil { + if errors.Is(err, provider.ErrUnauthorized) { + err = errors.Join(err, s.markSSOCredentialRejected(ctx, value, fmt.Sprintf("%s SSO credential rejected", value.Provider))) + } + return quotaRefreshResult{}, err + } + if snapshot.Group != group || len(snapshot.Modes) == 0 { + return quotaRefreshResult{}, fmt.Errorf("Provider quota group %s 返回无效快照", group) + } + if snapshot.SyncedAt.IsZero() { + snapshot.SyncedAt = s.now() + } + if err := s.accounts.ReplaceQuotaWindowGroup(ctx, id, snapshot.SyncedAt, snapshot.Modes, snapshot.Windows); err != nil { + return quotaRefreshResult{}, err + } + return quotaRefreshResult{Credential: value, Windows: snapshot.Windows, Modes: snapshot.Modes}, nil +} + func (s *Service) refreshQuotaMode(ctx context.Context, id uint64, mode string) (quotaRefreshResult, error) { value, err := s.accounts.Get(ctx, id) if err != nil { @@ -2949,6 +2991,9 @@ func quotaSyncKey(accountID uint64, mode string) string { if isConsoleUsageQuotaMode(mode) { return "all:" + strconv.FormatUint(accountID, 10) } + if isWebImagineQuotaMode(mode) || mode == accountdomain.QuotaGroupWebImagine { + return accountdomain.QuotaGroupWebImagine + ":" + strconv.FormatUint(accountID, 10) + } return mode + ":" + strconv.FormatUint(accountID, 10) } @@ -2970,6 +3015,27 @@ func (s *Service) reconcileQuotaRecoveryWindows(ctx context.Context, providerVal return nil } +func (s *Service) reconcileQuotaGroupWindows(ctx context.Context, providerValue accountdomain.Provider, accountID uint64, modes []string, windows []accountdomain.QuotaWindow) error { + byMode := make(map[string]accountdomain.QuotaWindow, len(windows)) + for _, window := range windows { + byMode[window.Mode] = window + } + for _, mode := range modes { + if window, ok := byMode[mode]; ok { + if err := s.reconcileQuotaRecoveryWindow(ctx, providerValue, accountID, window); err != nil { + return err + } + continue + } + if s.quotaQueue != nil { + if err := s.quotaQueue.CancelQuotaRecovery(ctx, accountID, mode); err != nil { + return fmt.Errorf("取消额度恢复事件: %w", err) + } + } + } + return nil +} + func (s *Service) reconcileQuotaRecoveryWindow(ctx context.Context, providerValue accountdomain.Provider, accountID uint64, window accountdomain.QuotaWindow) error { if s.quotaQueue == nil || !quotaWindowControlsRouting(providerValue, window.Mode) { return nil @@ -3012,7 +3078,10 @@ func quotaRecoveryDueAt(window accountdomain.QuotaWindow, now time.Time, exhaust // QueueQuotaRefresh asynchronously refreshes the remote quota window after a successful request. func (s *Service) QueueQuotaRefresh(id uint64, mode string) { mode = strings.TrimSpace(mode) - if id == 0 || (!isConsoleUsageQuotaMode(mode) && mode != "weekly" && !isWebChatQuotaMode(mode)) { + if isWebImagineQuotaMode(mode) { + mode = accountdomain.QuotaGroupWebImagine + } + if id == 0 || (!isConsoleUsageQuotaMode(mode) && mode != "weekly" && mode != accountdomain.QuotaGroupWebImagine && !isWebChatQuotaMode(mode)) { return } key := strconv.FormatUint(id, 10) + ":" + mode @@ -3181,9 +3250,10 @@ func (s *Service) runQuotaRefresh(parent context.Context, request quotaRefreshRe break } } - } else { + } else if request.mode != accountdomain.QuotaGroupWebImagine { // Weekly remains a Grok Web capability. Console never inherits this // legacy mode and always refreshes its authoritative /usage snapshot. + // Imagine 配额组走 /rest/media/imagine/quota_info,不可被改刷 weekly。 for _, window := range windows[request.accountID] { if window.Mode == "weekly" { refreshMode = "weekly" @@ -3206,7 +3276,15 @@ func (s *Service) runQuotaRefresh(parent context.Context, request quotaRefreshRe } if !skipUpstream && refreshErr == nil && acquired { if err := s.syncPool.Do(ctx, func(workCtx context.Context) error { - _, refreshErr = s.RefreshQuotaMode(workCtx, request.accountID, refreshMode) + if refreshMode == accountdomain.QuotaGroupWebImagine { + var refreshed quotaRefreshResult + refreshed, refreshErr = s.refreshQuotaGroup(workCtx, request.accountID, refreshMode) + if refreshErr == nil { + refreshErr = s.reconcileQuotaGroupWindows(workCtx, refreshed.Credential.Provider, request.accountID, refreshed.Modes, refreshed.Windows) + } + } else { + _, refreshErr = s.RefreshQuotaMode(workCtx, request.accountID, refreshMode) + } return refreshErr }); err != nil { refreshErr = err @@ -3460,6 +3538,10 @@ func isConsoleUsageQuotaMode(mode string) bool { } } +func isWebImagineQuotaMode(mode string) bool { + return accountdomain.IsWebImagineQuotaMode(mode) +} + func quotaWindowControlsRouting(providerValue accountdomain.Provider, mode string) bool { return providerValue != accountdomain.ProviderConsole || isConsoleUsageQuotaMode(mode) } diff --git a/backend/internal/application/egress/assignment.go b/backend/internal/application/egress/assignment.go index b0cde2a1..0abb1e0e 100644 --- a/backend/internal/application/egress/assignment.go +++ b/backend/internal/application/egress/assignment.go @@ -304,7 +304,7 @@ func (s *Service) RunMaintenance(ctx context.Context) error { resultErr = errors.Join(resultErr, err) } else { for _, source := range sources { - if _, syncErr := s.syncSourceWithConfig(ctx, operations, source, config); syncErr != nil { + if _, syncErr := s.syncSource(ctx, operations, source); syncErr != nil { resultErr = errors.Join(resultErr, syncErr) } } diff --git a/backend/internal/application/egress/operations.go b/backend/internal/application/egress/operations.go index ca8e8868..fd3822ac 100644 --- a/backend/internal/application/egress/operations.go +++ b/backend/internal/application/egress/operations.go @@ -58,6 +58,8 @@ type SubscriptionSourceInput struct { Enabled bool URL *string ClearURL bool + ProxyURL *string + ClearProxyURL bool RefreshIntervalSeconds *int DefaultAccountCapacity *int } @@ -90,12 +92,7 @@ type OperationsConfigInput struct { AutoAssignEnabled bool AutoBalanceEnabled bool AssignmentIntervalSeconds int - // SubscriptionProxyURL updates the optional proxy used when fetching remote - // subscription sources and must be non-empty when supplied. The explicit - // ClearSubscriptionProxy flag clears it; nil leaves the secret unchanged. - SubscriptionProxyURL *string - ClearSubscriptionProxy bool - Fallbacks map[domain.Scope]FallbackConfigInput + Fallbacks map[domain.Scope]FallbackConfigInput } type FallbackConfigInput struct { @@ -413,31 +410,10 @@ func (s *Service) UpdateOperationsConfig(ctx context.Context, input OperationsCo return domain.OperationsConfig{}, err } } - subscriptionProxyURL := current.EncryptedSubscriptionProxyURL - if input.ClearSubscriptionProxy { - subscriptionProxyURL = "" - } else if input.SubscriptionProxyURL != nil { - normalized, normalizeErr := NormalizeProxyURL(*input.SubscriptionProxyURL) - if normalizeErr != nil { - return domain.OperationsConfig{}, fmt.Errorf("%w: 订阅拉取代理地址无效: %v", ErrInvalidInput, normalizeErr) - } - if normalized == "" { - return domain.OperationsConfig{}, fmt.Errorf("%w: 订阅拉取代理地址不能为空;如需清除请显式指定 clearSubscriptionProxy", ErrInvalidInput) - } - if strings.Contains(normalized, ProxyAccountPlaceholder) { - return domain.OperationsConfig{}, fmt.Errorf("%w: 订阅拉取代理不能使用账号占位符", ErrInvalidInput) - } - encrypted, encryptErr := s.cipher.Encrypt(normalized) - if encryptErr != nil { - return domain.OperationsConfig{}, encryptErr - } - subscriptionProxyURL = encrypted - } saved, err := operations.SaveEgressOperationsConfig(ctx, domain.OperationsConfig{ ProbeProvider: probeProvider, ProbeIntervalSeconds: input.ProbeIntervalSeconds, AutoAssignEnabled: input.AutoAssignEnabled, AutoBalanceEnabled: input.AutoBalanceEnabled, AssignmentIntervalSeconds: input.AssignmentIntervalSeconds, - EncryptedSubscriptionProxyURL: subscriptionProxyURL, - Fallbacks: fallbacks, UpdatedAt: time.Now().UTC(), + Fallbacks: fallbacks, UpdatedAt: time.Now().UTC(), }) if errors.Is(err, repository.ErrEgressFallbackInUse) { return domain.OperationsConfig{}, fmt.Errorf("%w: 固定回退节点必须保持启用且可用", ErrInvalidInput) @@ -553,7 +529,26 @@ func (s *Service) applySourceInput(value domain.SubscriptionSource, input Subscr if create && value.EncryptedURL == "" { return domain.SubscriptionSource{}, fmt.Errorf("%w: 必须提供订阅地址", ErrInvalidInput) } - if create || input.URL != nil || input.ClearURL { + if input.ClearProxyURL { + value.EncryptedProxyURL = "" + } else if input.ProxyURL != nil { + proxyURL, err := NormalizeProxyURL(*input.ProxyURL) + if err != nil { + return domain.SubscriptionSource{}, fmt.Errorf("%w: %v", ErrInvalidInput, err) + } + if proxyURL == "" { + return domain.SubscriptionSource{}, fmt.Errorf("%w: 订阅代理地址不能为空", ErrInvalidInput) + } + if strings.Contains(proxyURL, ProxyAccountPlaceholder) { + return domain.SubscriptionSource{}, fmt.Errorf("%w: 订阅代理地址不能包含账号占位符", ErrInvalidInput) + } + encryptedProxyURL, err := s.cipher.Encrypt(proxyURL) + if err != nil { + return domain.SubscriptionSource{}, err + } + value.EncryptedProxyURL = encryptedProxyURL + } + if create || input.URL != nil || input.ClearURL || input.ProxyURL != nil || input.ClearProxyURL { value.NextSyncAt = nil value.LastSyncError = "" } @@ -563,6 +558,7 @@ func (s *Service) applySourceInput(value domain.SubscriptionSource, input Subscr func publicSource(value domain.SubscriptionSource) domain.PublicSubscriptionSource { return domain.PublicSubscriptionSource{ ID: value.ID, Name: value.Name, Scope: value.Scope, Enabled: value.Enabled, URLConfigured: value.EncryptedURL != "", + ProxyConfigured: value.EncryptedProxyURL != "", RefreshIntervalSeconds: value.RefreshIntervalSeconds, DefaultAccountCapacity: value.DefaultAccountCapacity, LastSyncedAt: value.LastSyncedAt, NextSyncAt: value.NextSyncAt, LastSyncImported: value.LastSyncImported, LastSyncError: value.LastSyncError, CreatedAt: value.CreatedAt, UpdatedAt: value.UpdatedAt, diff --git a/backend/internal/application/egress/operations_config_test.go b/backend/internal/application/egress/operations_config_test.go deleted file mode 100644 index bff839c0..00000000 --- a/backend/internal/application/egress/operations_config_test.go +++ /dev/null @@ -1,153 +0,0 @@ -package egress - -import ( - "context" - "errors" - "testing" - "time" - - domain "github.com/chenyme/grok2api/backend/internal/domain/egress" - "github.com/chenyme/grok2api/backend/internal/infra/security" -) - -type operationsConfigRepositoryStub struct { - OperationsRepository - config domain.OperationsConfig - getErr error - saved domain.OperationsConfig - saveCalls int - syncUpdates int -} - -func (r *operationsConfigRepositoryStub) GetEgressOperationsConfig(context.Context) (domain.OperationsConfig, error) { - if r.getErr != nil { - return domain.OperationsConfig{}, r.getErr - } - return r.config, nil -} - -func (r *operationsConfigRepositoryStub) SaveEgressOperationsConfig(_ context.Context, value domain.OperationsConfig) (domain.OperationsConfig, error) { - r.saved = value - r.config = value - r.saveCalls++ - return value, nil -} - -func (r *operationsConfigRepositoryStub) UpdateEgressSourceSync(context.Context, uint64, time.Time, time.Time, int, string) error { - r.syncUpdates++ - return nil -} - -func testOperationsConfigInput() OperationsConfigInput { - return OperationsConfigInput{ - ProbeProvider: domain.ProbeProviderCloudflare, - ProbeIntervalSeconds: 900, - AssignmentIntervalSeconds: 300, - } -} - -func testEgressCipher(t *testing.T) *security.Cipher { - t.Helper() - cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") - if err != nil { - t.Fatal(err) - } - return cipher -} - -func TestUpdateOperationsConfigUsesExplicitSubscriptionProxyTriState(t *testing.T) { - cipher := testEgressCipher(t) - existing, err := cipher.Encrypt("socks5h://old.example:1080") - if err != nil { - t.Fatal(err) - } - - t.Run("omitted preserves existing secret", func(t *testing.T) { - repository := &operationsConfigRepositoryStub{config: domain.DefaultOperationsConfig()} - repository.config.EncryptedSubscriptionProxyURL = existing - service := &Service{operations: repository, cipher: cipher} - if _, err := service.UpdateOperationsConfig(context.Background(), testOperationsConfigInput()); err != nil { - t.Fatal(err) - } - if repository.saved.EncryptedSubscriptionProxyURL != existing { - t.Fatal("omitted subscription proxy did not preserve the existing secret") - } - }) - - t.Run("empty value requires explicit clear", func(t *testing.T) { - repository := &operationsConfigRepositoryStub{config: domain.DefaultOperationsConfig()} - repository.config.EncryptedSubscriptionProxyURL = existing - service := &Service{operations: repository, cipher: cipher} - input := testOperationsConfigInput() - empty := "" - input.SubscriptionProxyURL = &empty - _, err := service.UpdateOperationsConfig(context.Background(), input) - if !errors.Is(err, ErrInvalidInput) || repository.saveCalls != 0 { - t.Fatalf("empty proxy error=%v saveCalls=%d", err, repository.saveCalls) - } - }) - - t.Run("clear removes existing secret", func(t *testing.T) { - repository := &operationsConfigRepositoryStub{config: domain.DefaultOperationsConfig()} - repository.config.EncryptedSubscriptionProxyURL = existing - service := &Service{operations: repository, cipher: cipher} - input := testOperationsConfigInput() - input.ClearSubscriptionProxy = true - if _, err := service.UpdateOperationsConfig(context.Background(), input); err != nil { - t.Fatal(err) - } - if repository.saved.EncryptedSubscriptionProxyURL != "" { - t.Fatal("explicit clear preserved the subscription proxy") - } - }) - - t.Run("new value is encrypted", func(t *testing.T) { - repository := &operationsConfigRepositoryStub{config: domain.DefaultOperationsConfig()} - service := &Service{operations: repository, cipher: cipher} - input := testOperationsConfigInput() - proxyURL := "socks5h://user:secret@new.example:1080" - input.SubscriptionProxyURL = &proxyURL - if _, err := service.UpdateOperationsConfig(context.Background(), input); err != nil { - t.Fatal(err) - } - if repository.saved.EncryptedSubscriptionProxyURL == "" || repository.saved.EncryptedSubscriptionProxyURL == proxyURL { - t.Fatal("new subscription proxy was not encrypted") - } - decrypted, err := cipher.Decrypt(repository.saved.EncryptedSubscriptionProxyURL) - if err != nil || decrypted != proxyURL { - t.Fatalf("decrypted proxy=%q err=%v", decrypted, err) - } - }) - - t.Run("account placeholder is rejected", func(t *testing.T) { - repository := &operationsConfigRepositoryStub{config: domain.DefaultOperationsConfig()} - service := &Service{operations: repository, cipher: cipher} - input := testOperationsConfigInput() - proxyURL := "socks5h://Default.{account}:secret@proxy.example:1080" - input.SubscriptionProxyURL = &proxyURL - _, err := service.UpdateOperationsConfig(context.Background(), input) - if !errors.Is(err, ErrInvalidInput) || repository.saveCalls != 0 { - t.Fatalf("placeholder proxy error=%v saveCalls=%d", err, repository.saveCalls) - } - }) -} - -func TestSyncSourceFailsClosedWhenOperationsConfigCannotBeRead(t *testing.T) { - repository := &operationsConfigRepositoryStub{getErr: errors.New("database unavailable")} - service := &Service{operations: repository, cipher: testEgressCipher(t)} - _, err := service.syncSource(context.Background(), repository, domain.SubscriptionSource{ID: 7, RefreshIntervalSeconds: 900}) - if !errors.Is(err, ErrSubscriptionSync) { - t.Fatalf("sync error=%v", err) - } - if repository.syncUpdates != 1 { - t.Fatalf("failure status updates=%d", repository.syncUpdates) - } -} - -func TestSubscriptionFetchProxyRejectsCorruptConfiguredSecret(t *testing.T) { - service := &Service{cipher: testEgressCipher(t)} - _, err := service.subscriptionFetchProxy(domain.OperationsConfig{EncryptedSubscriptionProxyURL: "not-ciphertext"}) - if err == nil { - t.Fatal("corrupt configured subscription proxy was accepted") - } -} diff --git a/backend/internal/application/egress/service.go b/backend/internal/application/egress/service.go index 4ab205dc..7bdefb59 100644 --- a/backend/internal/application/egress/service.go +++ b/backend/internal/application/egress/service.go @@ -12,6 +12,7 @@ import ( accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" domain "github.com/chenyme/grok2api/backend/internal/domain/egress" "github.com/chenyme/grok2api/backend/internal/infra/security" + "github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy" "github.com/chenyme/grok2api/backend/internal/repository" ) @@ -851,13 +852,27 @@ func NormalizeProxyURL(value string) (string, error) { } parseValue := strings.ReplaceAll(value, ProxyAccountPlaceholder, proxyAccountSentinel) parsed, err := url.Parse(parseValue) - if err != nil || parsed.Host == "" || parsed.Hostname() == "" { + if err != nil { return "", errors.New("代理地址格式无效") } - switch strings.ToLower(parsed.Scheme) { + scheme := strings.ToLower(parsed.Scheme) + if tunnelproxy.IsSupportedScheme(scheme) { + if hasAccountPlaceholder { + return "", errors.New("隧道代理不支持 {account} 占位符") + } + normalized, normalizeErr := tunnelproxy.Normalize(value) + if normalizeErr != nil { + return "", normalizeErr + } + return normalized, nil + } + if parsed.Host == "" || parsed.Hostname() == "" { + return "", errors.New("代理地址格式无效") + } + switch scheme { case "http", "https", "socks4", "socks4a", "socks5", "socks5h": default: - return "", errors.New("代理地址协议必须是 HTTP、HTTPS、SOCKS4 或 SOCKS5") + return "", errors.New("代理地址协议必须是 HTTP、HTTPS、SOCKS4、SOCKS5、Trojan、VLESS、SS 或 VMess") } if parsed.RawQuery != "" || parsed.Fragment != "" || (parsed.Path != "" && parsed.Path != "/") { return "", errors.New("代理地址不能包含路径、查询参数或片段") diff --git a/backend/internal/application/egress/service_test.go b/backend/internal/application/egress/service_test.go index d848d6cd..02507e41 100644 --- a/backend/internal/application/egress/service_test.go +++ b/backend/internal/application/egress/service_test.go @@ -1,6 +1,7 @@ package egress import ( + "encoding/base64" "errors" "strings" "testing" @@ -21,23 +22,48 @@ func TestSanitizeCloudflareCookiesDropsControlsAndNonCloudflareValues(t *testing } func TestNormalizeProxyURLValidatesStructure(t *testing.T) { + vmess := "vmess://" + base64.RawStdEncoding.EncodeToString([]byte(`{"v":"2","ps":"node","add":"proxy.example","port":"443","id":"123e4567-e89b-12d3-a456-426614174000","aid":"0","scy":"auto","net":"ws","tls":"tls","sni":"edge.example","host":"edge.example","path":"/ws"}`)) for _, raw := range []string{ "http://user:password@127.0.0.1:8080", "https://proxy.example:8443", "socks4://127.0.0.1:1080", "socks4a://proxy.example:1080", "socks5://user:password@127.0.0.1:1080", "socks5h://user:password@proxy.example:1080", + "trojan://password@proxy.example:443?security=tls&sni=edge.example#remark", + "vless://123e4567-e89b-12d3-a456-426614174000@proxy.example:443?encryption=none&security=tls&sni=edge.example#remark", + "ss://YWVzLTEyOC1nY206c2VjcmV0@proxy.example:8388#remark", + vmess, } { value, err := NormalizeProxyURL(raw) if err != nil || value == "" { t.Fatalf("valid proxy %q = %q, err = %v", raw, value, err) } } - for _, invalid := range []string{"file:///tmp/proxy", "https://", "http://proxy.example/path", "http://proxy.example\r\nX-Leak: yes"} { + for _, invalid := range []string{ + "file:///tmp/proxy", "https://", "http://proxy.example/path", "http://proxy.example\r\nX-Leak: yes", + "vless://uuid@127.0.0.1:443?encryption=none&flow=xtls-rprx-vision#remark", + "ss://base64#remark", "vmess://base64#remark", "hysteria://127.0.0.1:443", + "hysteria2://127.0.0.1:443", "tuic://user:pass@127.0.0.1:443", "tuicv5://user:pass@127.0.0.1:443", + } { if _, err := NormalizeProxyURL(invalid); err == nil { t.Fatalf("invalid proxy accepted: %q", invalid) } } } +func TestNormalizeProxyURLStripsTunnelRemarks(t *testing.T) { + base := "trojan://password@proxy.example:443?security=tls&sni=edge.example" + one, err := NormalizeProxyURL(base + "#one") + if err != nil { + t.Fatal(err) + } + two, err := NormalizeProxyURL(base + "#two") + if err != nil { + t.Fatal(err) + } + if one != two || strings.Contains(one, "#") { + t.Fatalf("normalized tunnel identities = %q and %q", one, two) + } +} + func TestNormalizeProxyURLAllowsAccountPlaceholderOnlyInUsername(t *testing.T) { value, err := NormalizeProxyURL("socks5h://Default.{account}:token@resin:2260") if err != nil { diff --git a/backend/internal/application/egress/subscription.go b/backend/internal/application/egress/subscription.go index bb882462..42ddff98 100644 --- a/backend/internal/application/egress/subscription.go +++ b/backend/internal/application/egress/subscription.go @@ -17,6 +17,7 @@ import ( "unicode/utf8" _ "github.com/bdandy/go-socks4" + "github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy" xproxy "golang.org/x/net/proxy" ) @@ -163,8 +164,14 @@ func subscriptionTransport(viaProxy string) (*http.Transport, error) { return nil, fmt.Errorf("创建订阅拉取 SOCKS 代理: %w", err) } transport.DialContext = subscriptionProxyDialContext(dialer) + case "trojan", "vless", "ss", "vmess": + dialer, err := tunnelproxy.NewDialer(viaProxy) + if err != nil { + return nil, fmt.Errorf("创建订阅拉取隧道代理: %w", err) + } + transport.DialContext = dialer.DialContext default: - return nil, errors.New("订阅拉取代理协议必须是 HTTP、HTTPS、SOCKS4 或 SOCKS5") + return nil, errors.New("订阅拉取代理协议不受支持") } return transport, nil } @@ -361,7 +368,7 @@ func parseProxySubscription(value string) ([]subscriptionEntry, int, error) { return entries, decodedSkipped, nil } } - return nil, skipped, errors.New("订阅中没有可用的 HTTP 或 SOCKS 代理") + return nil, skipped, errors.New("订阅中没有可用的代理节点") } func parseProxyLines(value string) ([]subscriptionEntry, int) { diff --git a/backend/internal/application/egress/subscription_test.go b/backend/internal/application/egress/subscription_test.go index 4ee997c5..d7bb2cb4 100644 --- a/backend/internal/application/egress/subscription_test.go +++ b/backend/internal/application/egress/subscription_test.go @@ -4,12 +4,42 @@ import ( "context" "encoding/base64" "net" + "net/http" + "net/http/httptest" "net/netip" "strings" + "sync" + "sync/atomic" "testing" "time" + + domain "github.com/chenyme/grok2api/backend/internal/domain/egress" + "github.com/chenyme/grok2api/backend/internal/infra/security" ) +type subscriptionSyncRepositoryStub struct { + OperationsRepository + mu sync.Mutex + nodes map[uint64][]domain.Node +} + +func (r *subscriptionSyncRepositoryStub) UpsertEgressNodesFromSource(_ context.Context, sourceID uint64, nodes []domain.Node) (int, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.nodes[sourceID] = append([]domain.Node(nil), nodes...) + return len(nodes), nil +} + +func (r *subscriptionSyncRepositoryStub) UpdateEgressSourceSync(context.Context, uint64, time.Time, time.Time, int, string) error { + return nil +} + +func (r *subscriptionSyncRepositoryStub) nodesFor(sourceID uint64) []domain.Node { + r.mu.Lock() + defer r.mu.Unlock() + return append([]domain.Node(nil), r.nodes[sourceID]...) +} + func TestParseProxySubscriptionAcceptsPlainAndBase64Lists(t *testing.T) { plain, skipped, err := parseProxySubscription(strings.Join([]string{ "# proxy list", @@ -46,6 +76,30 @@ func TestParseProxySubscriptionRejectsNoUsableEntries(t *testing.T) { } } +func TestParseProxySubscriptionImportsSupportedTunnelSchemes(t *testing.T) { + vmess := "vmess://" + base64.RawStdEncoding.EncodeToString([]byte(`{"v":"2","ps":"node","add":"proxy.example","port":"443","id":"123e4567-e89b-12d3-a456-426614174000","aid":"0","scy":"auto","net":"tcp"}`)) + entries, skipped, err := parseProxySubscription(strings.Join([]string{ + "http://proxy.example:8080", + "trojan://password@proxy.example:443#remark", + "vless://123e4567-e89b-12d3-a456-426614174000@proxy.example:443?encryption=none#remark", + "ss://YWVzLTEyOC1nY206c2VjcmV0@proxy.example:8388#remark", + vmess, + "hysteria2://proxy.example:443", + "tuic://user:pass@proxy.example:443", + }, "\n")) + if err != nil { + t.Fatal(err) + } + if len(entries) != 5 || skipped != 2 || entries[0].ProxyURL != "http://proxy.example:8080" { + t.Fatalf("entries=%#v skipped=%d", entries, skipped) + } + for _, entry := range entries[1:] { + if strings.Contains(entry.ProxyURL, "#") { + t.Fatalf("subscription remark was retained: %q", entry.ProxyURL) + } + } +} + func TestIsPublicAddressRejectsNonPublicRanges(t *testing.T) { for _, raw := range []string{ "0.0.0.1", "10.0.0.1", "100.64.0.1", "127.0.0.1", "169.254.10.1", @@ -118,3 +172,78 @@ func TestSubscriptionTransportSupportsConfiguredProxyProtocols(t *testing.T) { transport.CloseIdleConnections() } } + +func TestSubscriptionFetchProxyRejectsCorruptSourceSecret(t *testing.T) { + cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") + if err != nil { + t.Fatal(err) + } + service := &Service{cipher: cipher} + if _, err := service.subscriptionFetchProxy(domain.SubscriptionSource{EncryptedProxyURL: "not-ciphertext"}); err == nil { + t.Fatal("corrupt per-source subscription proxy was accepted") + } +} + +func TestSyncSourceUsesItsOwnFetchProxy(t *testing.T) { + cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") + if err != nil { + t.Fatal(err) + } + type proxyFixture struct { + hits atomic.Int32 + server *httptest.Server + nodeProxy string + } + newProxy := func(nodeProxy string) *proxyFixture { + fixture := &proxyFixture{nodeProxy: nodeProxy} + fixture.server = httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) { + fixture.hits.Add(1) + if request.URL.Host != "1.1.1.1" { + response.WriteHeader(http.StatusBadGateway) + return + } + _, _ = response.Write([]byte(fixture.nodeProxy + "\n")) + })) + t.Cleanup(fixture.server.Close) + return fixture + } + firstProxy := newProxy("socks5h://first-node.example:1080") + secondProxy := newProxy("http://second-node.example:8080") + + encryptedSourceURL, err := cipher.Encrypt("http://1.1.1.1/subscription") + if err != nil { + t.Fatal(err) + } + repository := &subscriptionSyncRepositoryStub{nodes: make(map[uint64][]domain.Node)} + service := &Service{cipher: cipher} + for id, fixture := range map[uint64]*proxyFixture{1: firstProxy, 2: secondProxy} { + encryptedProxyURL, encryptErr := cipher.Encrypt(fixture.server.URL) + if encryptErr != nil { + t.Fatal(encryptErr) + } + _, syncErr := service.syncSource(context.Background(), repository, domain.SubscriptionSource{ + ID: id, Name: "source", Scope: domain.ScopeBuild, Enabled: true, + EncryptedURL: encryptedSourceURL, EncryptedProxyURL: encryptedProxyURL, RefreshIntervalSeconds: 900, + }) + if syncErr != nil { + t.Fatalf("sync source %d: %v", id, syncErr) + } + } + + if firstProxy.hits.Load() != 1 || secondProxy.hits.Load() != 1 { + t.Fatalf("proxy hits: first=%d second=%d", firstProxy.hits.Load(), secondProxy.hits.Load()) + } + for id, expected := range map[uint64]string{1: firstProxy.nodeProxy, 2: secondProxy.nodeProxy} { + nodes := repository.nodesFor(id) + if len(nodes) != 1 { + t.Fatalf("source %d imported %d nodes", id, len(nodes)) + } + actual, decryptErr := cipher.Decrypt(nodes[0].EncryptedProxyURL) + if decryptErr != nil { + t.Fatal(decryptErr) + } + if actual != expected { + t.Fatalf("source %d imported proxy %q, want %q", id, actual, expected) + } + } +} diff --git a/backend/internal/application/egress/sync.go b/backend/internal/application/egress/sync.go index e54d97c4..2418e4d2 100644 --- a/backend/internal/application/egress/sync.go +++ b/backend/internal/application/egress/sync.go @@ -13,17 +13,6 @@ import ( var ErrSubscriptionSync = errors.New("代理订阅同步失败") func (s *Service) syncSource(ctx context.Context, operations OperationsRepository, source domain.SubscriptionSource) (ImportResult, error) { - config, err := operations.GetEgressOperationsConfig(ctx) - if err != nil { - now := time.Now().UTC() - nextSyncAt := sourceNextSyncAt(source, now) - _ = operations.UpdateEgressSourceSync(context.WithoutCancel(ctx), source.ID, now, nextSyncAt, 0, "订阅拉取或解析失败") - return ImportResult{}, ErrSubscriptionSync - } - return s.syncSourceWithConfig(ctx, operations, source, config) -} - -func (s *Service) syncSourceWithConfig(ctx context.Context, operations OperationsRepository, source domain.SubscriptionSource, config domain.OperationsConfig) (ImportResult, error) { now := time.Now().UTC() nextSyncAt := sourceNextSyncAt(source, now) recordFailure := func() { @@ -40,7 +29,7 @@ func (s *Service) syncSourceWithConfig(ctx context.Context, operations Operation recordFailure() return ImportResult{}, ErrSubscriptionSync } - fetchProxy, err := s.subscriptionFetchProxy(config) + fetchProxy, err := s.subscriptionFetchProxy(source) if err != nil { recordFailure() return ImportResult{}, ErrSubscriptionSync @@ -93,8 +82,8 @@ func sourceNextSyncAt(source domain.SubscriptionSource, now time.Time) time.Time return now.Add(time.Duration(source.RefreshIntervalSeconds) * time.Second) } -func (s *Service) subscriptionFetchProxy(config domain.OperationsConfig) (string, error) { - encrypted := strings.TrimSpace(config.EncryptedSubscriptionProxyURL) +func (s *Service) subscriptionFetchProxy(source domain.SubscriptionSource) (string, error) { + encrypted := strings.TrimSpace(source.EncryptedProxyURL) if encrypted == "" { return "", nil } diff --git a/backend/internal/application/gateway/image.go b/backend/internal/application/gateway/image.go index 9da4fad3..37dba1ac 100644 --- a/backend/internal/application/gateway/image.go +++ b/backend/internal/application/gateway/image.go @@ -26,6 +26,7 @@ type ImageGenerationInput struct { Size string AspectRatio string Resolution string + Quality string ResponseFormat string Streaming bool PartialImages int @@ -42,6 +43,7 @@ type ImageEditInput struct { Size string AspectRatio string Resolution string + Quality string ResponseFormat string Streaming bool PartialImages int @@ -63,10 +65,10 @@ func (s *Service) GenerateImage(ctx context.Context, input ImageGenerationInput) } return adapter.GenerateImage(executionCtx, provider.ImageGenerationRequest{ Credential: credential, Model: upstream, Prompt: input.Prompt, Count: input.Count, - Size: input.Size, AspectRatio: input.AspectRatio, Resolution: input.Resolution, + Size: input.Size, AspectRatio: input.AspectRatio, Resolution: input.Resolution, Quality: input.Quality, ResponseFormat: input.ResponseFormat, Streaming: input.Streaming, PartialImages: input.PartialImages, }) - }, input.Streaming, input.Resolution, input.Count, 0) + }, input.Streaming, input.Resolution, input.Quality, input.Count, 0) } // EditImage 选择支持图片编辑的路由和账号,并返回可统一审计的上游响应。 @@ -82,10 +84,10 @@ func (s *Service) EditImage(ctx context.Context, input ImageEditInput) (*Result, return adapter.EditImage(executionCtx, provider.ImageEditRequest{ Credential: credential, Model: upstream, Prompt: input.Prompt, ImageURLs: input.ImageURLs, Count: input.Count, Size: input.Size, AspectRatio: input.AspectRatio, - Resolution: input.Resolution, ResponseFormat: input.ResponseFormat, + Resolution: input.Resolution, Quality: input.Quality, ResponseFormat: input.ResponseFormat, Streaming: input.Streaming, PartialImages: input.PartialImages, }) - }, input.Streaming, input.Resolution, input.Count, len(input.ImageURLs)) + }, input.Streaming, input.Resolution, input.Quality, input.Count, len(input.ImageURLs)) } func (s *Service) executeImage( @@ -99,6 +101,7 @@ func (s *Service) executeImage( execute imageExecution, streaming bool, resolution string, + quality string, requestedCount int, inputImageCount int, ) (*Result, error) { @@ -109,9 +112,16 @@ func (s *Service) executeImage( if err != nil { return nil, ErrModelNotFound } - route, err := s.selectMediaRoute(routes, key, capability, supports) + route, preselectedSession, err := s.selectSchedulableMediaRoute(ctx, routes, key, capability, true, supports) if err != nil { - return nil, err + // Preserve the established failure-audit path when every eligible target + // is currently unschedulable. The request loop will reproduce the + // selection error for the representative route after auditBase exists. + route, err = s.selectMediaRoute(routes, key, capability, supports) + if err != nil { + return nil, err + } + preselectedSession = nil } externalModel := modeldomain.ExternalPublicID(route.Provider, route.PublicID) auditBase := audit.Record{ @@ -148,9 +158,9 @@ func (s *Service) executeImage( var priced bool switch operation { case audit.OperationImage: - reservation, priced = audit.EstimateOfficialImageCost(pricingModel, resolution, requestedCount) + reservation, priced = audit.EstimateOfficialImageCost(pricingModel, resolution, quality, requestedCount) case audit.OperationImageEdit: - reservation, priced = audit.EstimateOfficialImageEditCost(pricingModel, resolution, requestedCount, inputImageCount) + reservation, priced = audit.EstimateOfficialImageEditCost(pricingModel, resolution, quality, requestedCount, inputImageCount) } reserved := false if priced { @@ -166,9 +176,10 @@ func (s *Service) executeImage( } }() quotaMode := s.providers.QuotaMode(route.Provider, route.UpstreamModel) + quotaRefreshGroup := s.providers.QuotaRefreshGroup(route.Provider, route.UpstreamModel) attemptPolicy := newRoutingAttemptPolicy(int(s.maxAttempts.Load())) excluded := make(map[uint64]bool) - var selection *selectionSession + selection := preselectedSession var lease *accountLease var credential accountdomain.Credential var response *provider.Response @@ -284,9 +295,9 @@ func (s *Service) executeImage( var priced bool switch operation { case audit.OperationImage: - pricing, priced = audit.EstimateOfficialImageCost(pricingModel, resolution, requestedCount) + pricing, priced = audit.EstimateOfficialImageCost(pricingModel, resolution, quality, requestedCount) case audit.OperationImageEdit: - pricing, priced = audit.EstimateOfficialImageEditCost(pricingModel, resolution, requestedCount, inputImageCount) + pricing, priced = audit.EstimateOfficialImageEditCost(pricingModel, resolution, quality, requestedCount, inputImageCount) } if priced { record.EstimatedCostInUSDTicks = pricing.CostInUSDTicks @@ -295,22 +306,28 @@ func (s *Service) executeImage( } } quotaKind, _ := s.providers.QuotaKind(route.Provider) - if successful && quotaKind == provider.QuotaRemoteWindow && effectiveQuotaMode != "" { - if effectiveQuotaMode != "weekly" { + refreshMode := effectiveQuotaMode + decrementMode := effectiveQuotaMode + if quotaRefreshGroup != "" { + refreshMode = quotaRefreshGroup + decrementMode = quotaMode + } + if successful && quotaKind == provider.QuotaRemoteWindow && refreshMode != "" { + if decrementMode != "" && decrementMode != "weekly" { units := max(1, response.QuotaUnits) var updated bool err := budget.run("quota_decrement", finalizationQuotaBudget, func(stageCtx context.Context) error { var decrementErr error - updated, decrementErr = s.accounts.DecrementWebQuota(stageCtx, accountID, effectiveQuotaMode, units) + updated, decrementErr = s.accounts.DecrementWebQuota(stageCtx, accountID, decrementMode, units) return decrementErr }) if err != nil { - s.logger.Warn("web_quota_decrement_failed", "account_id", accountID, "mode", effectiveQuotaMode, "units", units, "error", err) + s.logger.Warn("web_quota_decrement_failed", "account_id", accountID, "mode", decrementMode, "units", units, "error", err) } else if updated { - s.selector.ConsumeQuota(route.Provider, accountID, effectiveQuotaMode, units) + s.selector.ConsumeQuota(route.Provider, accountID, decrementMode, units) } } - s.accounts.QueueQuotaRefresh(accountID, effectiveQuotaMode) + s.accounts.QueueQuotaRefresh(accountID, refreshMode) } if err := budget.run("audit", finalizationAuditBudget, func(stageCtx context.Context) error { return s.audits.Create(stageCtx, record) diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index 8e29bd64..e1cbde7a 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -44,6 +44,7 @@ var ( ErrConversationUnsupported = errors.New("目标模型不支持当前对话协议") ErrVideoInputTooLarge = errors.New("视频参考图片编码后总输入超过 32 MiB") ErrVideoInputUnavailable = errors.New("视频临时输入不存在或已过期") + ErrVideoOperationUnsupported = errors.New("视频编辑/延长仅支持路由到 Console grok-imagine-video") ErrLedgerUnavailable = errors.New("计费账本暂不可用") ) @@ -160,8 +161,8 @@ type routeResolver interface { type videoAssetStore interface { SaveVideo(ctx context.Context, jobID, contentType string, body io.Reader) (mediadomain.Asset, error) OpenVideo(ctx context.Context, id string) (mediadomain.Asset, io.ReadCloser, error) - OpenInputImage(ctx context.Context, id string) (mediadomain.Asset, io.ReadCloser, error) - ReleaseInputImages(ctx context.Context, references []string) error + OpenInputAsset(ctx context.Context, id string) (mediadomain.Asset, io.ReadCloser, error) + ReleaseInputAssets(ctx context.Context, references []string) error } type accountModelSyncer interface { @@ -686,10 +687,19 @@ func routeTargetSeed(input Input) string { // selectMediaRoute selects a same-name route that satisfies media capability, key permissions, and Provider support. func (s *Service) selectMediaRoute(routes []modeldomain.Route, key clientkey.Key, capability modeldomain.Capability, providerSupported func(accountdomain.Provider) bool) (modeldomain.Route, error) { + eligible, fallback, err := s.eligibleMediaRoutes(routes, key, capability, providerSupported) + if err != nil { + return fallback, err + } + return eligible[0], nil +} + +func (s *Service) eligibleMediaRoutes(routes []modeldomain.Route, key clientkey.Key, capability modeldomain.Capability, providerSupported func(accountdomain.Provider) bool) ([]modeldomain.Route, modeldomain.Route, error) { if len(routes) == 0 { - return modeldomain.Route{}, ErrModelNotFound + return nil, modeldomain.Route{}, ErrModelNotFound } fallback := routes[0] + eligible := make([]modeldomain.Route, 0, len(routes)) accountScope := key.AccountScope() capabilityMatched := false scopeMatched := false @@ -709,19 +719,68 @@ func (s *Service) selectMediaRoute(routes []modeldomain.Route, key clientkey.Key } allowed = true if providerSupported(route.Provider) { - return route, nil + eligible = append(eligible, route) } } + if len(eligible) > 0 { + return eligible, fallback, nil + } if !capabilityMatched { - return fallback, ErrModelNotFound + return nil, fallback, ErrModelNotFound } if !scopeMatched { - return fallback, &SelectionUnavailableError{Reason: SelectionNoAccounts, Scope: accountScope} + return nil, fallback, &SelectionUnavailableError{Reason: SelectionNoAccounts, Scope: accountScope} } if !allowed { - return fallback, clientkeyapp.ErrModelNotAllowed + return nil, fallback, clientkeyapp.ErrModelNotAllowed } - return fallback, ErrNoAvailableAccount + return nil, fallback, ErrNoAvailableAccount +} + +// selectSchedulableMediaRoute resolves a concrete same-name media target and +// its immutable account plan together. A cooling or exhausted first target +// therefore cannot hide a healthy target from another Provider. +func (s *Service) selectSchedulableMediaRoute(ctx context.Context, routes []modeldomain.Route, key clientkey.Key, capability modeldomain.Capability, consumesQuota bool, providerSupported func(accountdomain.Provider) bool) (modeldomain.Route, *selectionSession, error) { + return s.selectSchedulableMediaRouteWithQuotaMode(ctx, routes, key, capability, consumesQuota, providerSupported, nil) +} + +func (s *Service) selectSchedulableMediaRouteWithQuotaMode(ctx context.Context, routes []modeldomain.Route, key clientkey.Key, capability modeldomain.Capability, consumesQuota bool, providerSupported func(accountdomain.Provider) bool, resolveQuotaMode func(modeldomain.Route) string) (modeldomain.Route, *selectionSession, error) { + eligible, fallback, err := s.eligibleMediaRoutes(routes, key, capability, providerSupported) + if err != nil { + return fallback, nil, err + } + var firstSelectionErr error + for _, route := range eligible { + quotaMode := "" + if consumesQuota { + if resolveQuotaMode != nil { + quotaMode = resolveQuotaMode(route) + } else { + quotaMode = s.providers.QuotaMode(route.Provider, route.UpstreamModel) + } + } + session, selectionErr := s.selector.beginSelectionSessionForKey( + ctx, + route.Provider, + route.ID, + route.UpstreamModel, + quotaMode, + "", + nil, + false, + key.AccountScope(), + ) + if selectionErr == nil { + return route, session, nil + } + if firstSelectionErr == nil { + firstSelectionErr = selectionErr + } + } + if firstSelectionErr == nil { + firstSelectionErr = ErrNoAvailableAccount + } + return eligible[0], nil, firstSelectionErr } func (s *Service) createResponseAt(ctx context.Context, input Input, path string) (*Result, error) { @@ -1294,7 +1353,7 @@ attemptLoop: record.ReasoningTokens = usage.ReasoningTokens record.TotalTokens = usage.TotalTokens record.CostInUSDTicks = usage.CostInUSDTicks - imagePricing, imagePriced := audit.EstimateOfficialImageCost(pricingModel, "", response.QuotaUnits) + imagePricing, imagePriced := audit.EstimateOfficialImageCost(pricingModel, "", "", response.QuotaUnits) if imagePriced { record.MediaOutputImages = int64(max(0, response.QuotaUnits)) } diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index e1b29c9d..ff5862a1 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -51,6 +51,79 @@ func TestQueueAccountModelSyncDeduplicatesConcurrentETagRefresh(t *testing.T) { close(resolver.release) } +func TestVoiceWebSocketAuditOutcomeUsesLogicalSuccessStatus(t *testing.T) { + if status, code := voiceWebSocketAuditOutcome(VoiceWebSocketOutcome{}); status != http.StatusOK || code != "" { + t.Fatalf("successful outcome = status %d code %q", status, code) + } + if status, code := voiceWebSocketAuditOutcome(VoiceWebSocketOutcome{ErrorCode: " upstream_stream_interrupted "}); status != http.StatusBadGateway || code != "upstream_stream_interrupted" { + t.Fatalf("failed outcome = status %d code %q", status, code) + } +} + +func TestStreamingSTTPricingUsesCompletedDuration(t *testing.T) { + result, ok := audit.EstimateOfficialSTTCost(3.45, true) + if !ok || result.Model != "grok-stt-streaming" || result.CostInUSDTicks != 1_916_667 { + t.Fatalf("streaming STT pricing = %#v, ok = %t", result, ok) + } +} + +func TestVoiceErrorResponseDoesNotExposeUnclassifiedErrors(t *testing.T) { + response, err := voiceErrorResponse(testVoiceStatusError{status: http.StatusBadGateway, message: "access_token=secret"}) + if err != nil { + t.Fatal(err) + } + body, readErr := io.ReadAll(response.Body) + response.Body.Close() + if readErr != nil { + t.Fatal(readErr) + } + if strings.Contains(string(body), "access_token") || strings.Contains(string(body), "secret") { + t.Fatalf("unclassified provider error leaked through public response: %s", body) + } +} + +type testVoiceStatusError struct { + status int + message string +} + +func (e testVoiceStatusError) Error() string { return e.message } +func (e testVoiceStatusError) HTTPStatusCode() int { return e.status } + +func TestFormatSTTResponseHonorsOpenAIFormats(t *testing.T) { + speaker := 2 + result := provider.STTResult{ + Text: "hello", Language: "en", Duration: 1.25, + Words: []provider.STTWord{{Text: "hello", Start: 0.1, End: 0.8, Speaker: &speaker}}, + RawJSON: []byte(`{"text":"native","provider_field":true}`), + } + for _, test := range []struct { + format string + contentType string + contains []string + }{ + {format: "text", contentType: "text/plain; charset=utf-8", contains: []string{"hello"}}, + {format: "json", contentType: "application/json", contains: []string{`"text":"hello"`}}, + {format: "verbose_json", contentType: "application/json", contains: []string{`"task":"transcribe"`, `"word":"hello"`, `"speaker":2`}}, + {format: "", contentType: "application/json", contains: []string{`"provider_field":true`}}, + } { + response := formatSTTResponse(result, test.format) + body, err := io.ReadAll(response.Body) + response.Body.Close() + if err != nil { + t.Fatal(err) + } + if response.Header.Get("Content-Type") != test.contentType { + t.Fatalf("format %q content type = %q", test.format, response.Header.Get("Content-Type")) + } + for _, expected := range test.contains { + if !strings.Contains(string(body), expected) { + t.Fatalf("format %q body %q missing %q", test.format, body, expected) + } + } + } +} + type etagSyncResolver struct { calls atomic.Int64 started chan uint64 @@ -972,6 +1045,293 @@ func TestSelectMediaRouteSkipsSameNamedConversationRoute(t *testing.T) { } } +func TestSelectSchedulableMediaRouteSkipsUnavailableFirstTarget(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "media-route-failover.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accountRepo := relational.NewAccountRepository(database) + modelRepo := relational.NewModelRepository(database) + now := time.Now().UTC() + coolingUntil := now.Add(time.Hour) + buildAccount, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, AuthType: account.AuthTypeOAuth, + Name: "cooling-build", SourceKey: "cooling-build", EncryptedAccessToken: "build-token", + Enabled: true, AuthStatus: account.AuthStatusActive, MaxConcurrent: 1, CooldownUntil: &coolingUntil, + }) + if err != nil { + t.Fatal(err) + } + webAccount, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderWeb, AuthType: account.AuthTypeSSO, WebTier: account.WebTierSuper, + Name: "healthy-web", SourceKey: "healthy-web", EncryptedAccessToken: "web-token", + Enabled: true, AuthStatus: account.AuthStatusActive, MaxConcurrent: 1, + }) + if err != nil { + t.Fatal(err) + } + const publicModel = "shared-media-target" + routeInputs := []modeldomain.Route{ + {PublicID: publicModel, Provider: account.ProviderBuild, UpstreamModel: "build-image-target", Capability: modeldomain.CapabilityImage, Enabled: true}, + {PublicID: publicModel, Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image", Capability: modeldomain.CapabilityImage, Enabled: true}, + } + if err := modelRepo.UpsertRoutes(ctx, routeInputs); err != nil { + t.Fatal(err) + } + if err := modelRepo.ReplaceAccountCapabilities(ctx, buildAccount.ID, []string{"build-image-target"}, now); err != nil { + t.Fatal(err) + } + if err := modelRepo.ReplaceAccountCapabilities(ctx, webAccount.ID, []string{"grok-imagine-image"}, now); err != nil { + t.Fatal(err) + } + routes, err := modelRepo.GetByPublicIDCandidates(ctx, publicModel) + if err != nil { + t.Fatal(err) + } + registry := provider.NewRegistry(&credentialFailureImageAdapter{}, &webImageStreamAdapter{}) + sticky := memory.NewStickyStore() + selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute) + service := &Service{ + clientKeys: clientkeyapp.NewService(nil, nil, nil, 60, 4, nil), + providers: registry, + selector: selector, + } + selected, selection, err := service.selectSchedulableMediaRoute(ctx, routes, clientkey.Key{}, modeldomain.CapabilityImage, true, func(providerValue account.Provider) bool { + _, ok := registry.ImageGeneration(providerValue) + return ok + }) + if err != nil { + t.Fatal(err) + } + if selected.Provider != account.ProviderWeb || selection == nil { + t.Fatalf("selected route = %#v, selection = %#v", selected, selection) + } + lease, err := selection.Acquire(ctx, nil, false) + if err != nil { + t.Fatal(err) + } + if lease.Credential.ID != webAccount.ID { + t.Fatalf("selected account = %d, want %d", lease.Credential.ID, webAccount.ID) + } + lease.Release() + + // Non-consuming metadata calls (for example voice listing) must not inherit + // the Provider quota mode from route probing. Otherwise an account with an + // exhausted inference window cannot serve a request that consumes no quota. + if err := accountRepo.SaveQuotaWindows(ctx, webAccount.ID, account.WebTierSuper, now, []account.QuotaWindow{{ + AccountID: webAccount.ID, Mode: "fast", Remaining: 0, Total: 10, WindowSeconds: 3600, + Source: account.QuotaSourceUpstream, SyncedAt: &now, + }}); err != nil { + t.Fatal(err) + } + quotaSelector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), registry, time.Hour, time.Second, time.Minute) + service.selector = quotaSelector + if _, _, err := service.selectSchedulableMediaRoute(ctx, routes, clientkey.Key{}, modeldomain.CapabilityImage, true, func(providerValue account.Provider) bool { + _, ok := registry.ImageGeneration(providerValue) + return ok + }); err == nil { + t.Fatal("quota-consuming selection unexpectedly accepted an exhausted account") + } + selected, selection, err = service.selectSchedulableMediaRoute(ctx, routes, clientkey.Key{}, modeldomain.CapabilityImage, false, func(providerValue account.Provider) bool { + _, ok := registry.ImageGeneration(providerValue) + return ok + }) + if err != nil || selected.Provider != account.ProviderWeb || selection == nil { + t.Fatalf("non-consuming route = %#v, selection = %#v, err = %v", selected, selection, err) + } +} + +func TestUnpricedVoiceRemainsAvailableToFiniteClientKey(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "voice-billing-policy.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accountRepo := relational.NewAccountRepository(database) + modelRepo := relational.NewModelRepository(database) + auditRepo := relational.NewAuditRepository(database) + credential, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderConsole, AuthType: account.AuthTypeSSO, + Name: "console-voice", SourceKey: "console-voice", EncryptedAccessToken: "console-token", + Enabled: true, AuthStatus: account.AuthStatusActive, MaxConcurrent: 1, + }) + if err != nil { + t.Fatal(err) + } + const voiceModel = "voice-billing-policy" + if err := modelRepo.UpsertRoutes(ctx, []modeldomain.Route{{ + PublicID: voiceModel, Provider: account.ProviderConsole, UpstreamModel: voiceModel, + Capability: modeldomain.CapabilityTTS, Enabled: true, + }}); err != nil { + t.Fatal(err) + } + if err := modelRepo.ReplaceAccountCapabilities(ctx, credential.ID, []string{voiceModel}, time.Now().UTC()); err != nil { + t.Fatal(err) + } + registry := provider.NewRegistry(statelessConsoleAdapter{}) + sticky := memory.NewStickyStore() + selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute) + accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil) + service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(nil, nil, nil, 60, 4, nil), registry, selector, nil, 1) + executed := false + result, err := service.executeVoice(ctx, "req-voice-billing", clientkey.Key{ID: 1, BillingLimitUSDTicks: 1}, voiceModel, audit.OperationTTS, modeldomain.CapabilityTTS, true, audit.PricingResult{}, func(account.Provider) bool { + return true + }, func(context.Context, account.Provider, account.Credential, string) (voiceExecutionResult, error) { + executed = true + return voiceExecutionResult{response: jsonVoiceResponse(http.StatusOK, map[string]any{"ok": true})}, nil + }) + if err != nil { + t.Fatal(err) + } + if !executed { + t.Fatal("unpriced voice request did not reach the provider") + } + result.Finalize(Usage{}, "", "") + _ = result.Body.Close() +} + +func TestVoicePricingSettlesTTSAndRESTSTTUsage(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "voice-pricing.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + + accountRepo := relational.NewAccountRepository(database) + modelRepo := relational.NewModelRepository(database) + auditRepo := relational.NewAuditRepository(database) + keyRepo := relational.NewClientKeyRepository(database) + credential, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderConsole, AuthType: account.AuthTypeSSO, + Name: "console-priced-voice", SourceKey: "console-priced-voice", EncryptedAccessToken: "console-token", + Enabled: true, AuthStatus: account.AuthStatusActive, MaxConcurrent: 1, + }) + if err != nil { + t.Fatal(err) + } + const ( + ttsModel = "voice-priced-tts" + sttModel = "voice-priced-stt" + ) + if err := modelRepo.UpsertRoutes(ctx, []modeldomain.Route{ + {PublicID: ttsModel, Provider: account.ProviderConsole, UpstreamModel: ttsModel, Capability: modeldomain.CapabilityTTS, Enabled: true}, + {PublicID: sttModel, Provider: account.ProviderConsole, UpstreamModel: sttModel, Capability: modeldomain.CapabilitySTT, Enabled: true}, + }); err != nil { + t.Fatal(err) + } + if err := modelRepo.ReplaceAccountCapabilities(ctx, credential.ID, []string{ttsModel, sttModel}, time.Now().UTC()); err != nil { + t.Fatal(err) + } + limitedKey, err := keyRepo.Create(ctx, clientkey.Key{ + Name: "voice-priced-key", Prefix: "voice-priced", SecretHash: strings.Repeat("a", 64), EncryptedSecret: "encrypted", + Enabled: true, BillingLimitUSDTicks: 10_000_000_000, + }) + if err != nil { + t.Fatal(err) + } + + registry := provider.NewRegistry(statelessConsoleAdapter{}) + sticky := memory.NewStickyStore() + selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute) + accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil) + clientKeyService := clientkeyapp.NewService(keyRepo, nil, nil, 60, 4, nil) + service := NewService(modelRepo, auditRepo, accountService, clientKeyService, registry, selector, nil, 1) + + ttsPricing, ok := audit.EstimateOfficialTTSCost("Hello 世界") + if !ok { + t.Fatal("TTS pricing unavailable") + } + ttsResult, err := service.executeVoice(ctx, "req-priced-tts", limitedKey, ttsModel, audit.OperationTTS, modeldomain.CapabilityTTS, true, ttsPricing, func(account.Provider) bool { + return true + }, func(context.Context, account.Provider, account.Credential, string) (voiceExecutionResult, error) { + return voiceExecutionResult{response: jsonVoiceResponse(http.StatusOK, map[string]any{"ok": true}), pricing: ttsPricing}, nil + }) + if err != nil { + t.Fatal(err) + } + ttsResult.Finalize(Usage{}, "", "") + _ = ttsResult.Body.Close() + + settledKey, err := keyRepo.Get(ctx, limitedKey.ID) + if err != nil { + t.Fatal(err) + } + if settledKey.BilledUsageUSDTicks != ttsPricing.CostInUSDTicks || settledKey.ReservedUsageUSDTicks != 0 { + t.Fatalf("TTS billing = billed %d reserved %d, want billed %d reserved 0", settledKey.BilledUsageUSDTicks, settledKey.ReservedUsageUSDTicks, ttsPricing.CostInUSDTicks) + } + + sttPricing, ok := audit.EstimateOfficialSTTCost(3.45, false) + if !ok { + t.Fatal("STT pricing unavailable") + } + sttResult, err := service.executeVoice(ctx, "req-priced-stt", limitedKey, sttModel, audit.OperationSTT, modeldomain.CapabilitySTT, true, audit.PricingResult{}, func(account.Provider) bool { + return true + }, func(context.Context, account.Provider, account.Credential, string) (voiceExecutionResult, error) { + return voiceExecutionResult{response: jsonVoiceResponse(http.StatusOK, map[string]any{"text": "hello"}), pricing: sttPricing}, nil + }) + if err != nil { + t.Fatal(err) + } + sttResult.Finalize(Usage{}, "", "") + _ = sttResult.Body.Close() + + settledKey, err = keyRepo.Get(ctx, limitedKey.ID) + if err != nil { + t.Fatal(err) + } + wantBilled := ttsPricing.CostInUSDTicks + sttPricing.CostInUSDTicks + if settledKey.BilledUsageUSDTicks != wantBilled || settledKey.ReservedUsageUSDTicks != 0 { + t.Fatalf("voice billing = billed %d reserved %d, want billed %d reserved 0", settledKey.BilledUsageUSDTicks, settledKey.ReservedUsageUSDTicks, wantBilled) + } + audits, total, err := auditRepo.List(ctx, 0, 10) + if err != nil { + t.Fatal(err) + } + if total != 2 || len(audits) != 2 { + t.Fatalf("voice audits = %d/%d, want 2/2", len(audits), total) + } + if audits[0].RequestID != "req-priced-stt" || audits[0].PricingModel != sttPricing.Model || audits[0].EstimatedCostInUSDTicks != sttPricing.CostInUSDTicks { + t.Fatalf("STT audit = %#v", audits[0]) + } + if audits[1].RequestID != "req-priced-tts" || audits[1].PricingModel != ttsPricing.Model || audits[1].EstimatedCostInUSDTicks != ttsPricing.CostInUSDTicks { + t.Fatalf("TTS audit = %#v", audits[1]) + } + + cappedKey, err := keyRepo.Create(ctx, clientkey.Key{ + Name: "voice-capped-key", Prefix: "voice-capped", SecretHash: strings.Repeat("b", 64), EncryptedSecret: "encrypted", + Enabled: true, BillingLimitUSDTicks: ttsPricing.CostInUSDTicks - 1, + }) + if err != nil { + t.Fatal(err) + } + executed := false + _, err = service.executeVoice(ctx, "req-capped-tts", cappedKey, ttsModel, audit.OperationTTS, modeldomain.CapabilityTTS, true, ttsPricing, func(account.Provider) bool { + return true + }, func(context.Context, account.Provider, account.Credential, string) (voiceExecutionResult, error) { + executed = true + return voiceExecutionResult{response: jsonVoiceResponse(http.StatusOK, map[string]any{"ok": true}), pricing: ttsPricing}, nil + }) + if !errors.Is(err, clientkeyapp.ErrBillingLimit) { + t.Fatalf("capped TTS error = %v, want billing limit", err) + } + if executed { + t.Fatal("TTS reached upstream after exact reservation exceeded the key limit") + } +} + func TestGenerateImageReturnsWhenEveryCredentialRefreshFails(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "image-credential-failure.db")) diff --git a/backend/internal/application/gateway/video.go b/backend/internal/application/gateway/video.go index 50ede4ea..9b048876 100644 --- a/backend/internal/application/gateway/video.go +++ b/backend/internal/application/gateway/video.go @@ -40,27 +40,97 @@ func VideoInputFileReference(fileID string) string { } type VideoInput struct { - RequestID string - ClientKey clientkey.Key - PublicModel string - Prompt string - Duration int - AspectRatio string - Resolution string + RequestID string + ClientKey clientkey.Key + PublicModel string + // Operation defaults to generate when empty. + Operation provider.VideoOperation + Prompt string + Duration int + AspectRatio string + Resolution string + // ImageURL is the optional first-frame image (official "image"). + ImageURL string + // ReferenceURLs are style/content references (official "reference_images"). ReferenceURLs []string + // ReferenceAudios are preset voice_ids for reference-to-video. + ReferenceAudios []string + // VideoURL is required for edit/extend (official "video"). + VideoURL string } func (s *Service) CreateVideo(ctx context.Context, input VideoInput) (media.Job, error) { if s.mediaJobs == nil || s.mediaQueue == nil { return media.Job{}, fmt.Errorf("视频任务服务未配置") } - if len(input.Prompt) > 100000 || (len(input.Prompt) == 0 && len(input.ReferenceURLs) == 0) { - return media.Job{}, fmt.Errorf("文本生视频必须提供 prompt;图片生视频可以省略 prompt") + operation := input.Operation + if operation == "" { + operation = provider.VideoOperationGenerate } - if err := s.validateVideoInputReferences(ctx, input.ReferenceURLs); err != nil { + switch operation { + case provider.VideoOperationGenerate, provider.VideoOperationEdit, provider.VideoOperationExtend: + default: + return media.Job{}, fmt.Errorf("不支持的视频操作") + } + if len(input.Prompt) > 100000 { + return media.Job{}, fmt.Errorf("prompt 过长") + } + if operation == provider.VideoOperationGenerate { + hasImage := strings.TrimSpace(input.ImageURL) != "" + hasRefs := len(input.ReferenceURLs) > 0 + hasRefAudio := len(input.ReferenceAudios) > 0 + if hasImage && (hasRefs || hasRefAudio) { + return media.Job{}, fmt.Errorf("image 不能与 reference_images/reference_audios 同时使用") + } + if hasRefs || hasRefAudio { + if len(input.Prompt) == 0 { + return media.Job{}, fmt.Errorf("参考图/参考音频视频必须提供 prompt") + } + if resolution := strings.ToLower(strings.TrimSpace(input.Resolution)); resolution == "1080p" { + return media.Job{}, fmt.Errorf("参考图视频 resolution 最高 720p") + } + } + if len(input.Prompt) == 0 && !hasImage && !hasRefs && !hasRefAudio { + return media.Job{}, fmt.Errorf("文本生视频必须提供 prompt;图片生视频可以省略 prompt") + } + if strings.TrimSpace(input.VideoURL) != "" { + return media.Job{}, fmt.Errorf("视频生成不支持 video 输入") + } + if err := validateVideoReferenceAudios(input.ReferenceAudios); err != nil { + return media.Job{}, err + } + } else { + if strings.TrimSpace(input.Prompt) == "" { + return media.Job{}, fmt.Errorf("视频编辑/延长必须提供 prompt") + } + if strings.TrimSpace(input.VideoURL) == "" { + return media.Job{}, fmt.Errorf("视频编辑/延长必须提供 video") + } + if strings.TrimSpace(input.ImageURL) != "" || len(input.ReferenceURLs) > 0 || len(input.ReferenceAudios) > 0 { + return media.Job{}, fmt.Errorf("视频编辑/延长不支持 image、reference_images 或 reference_audios") + } + if operation == provider.VideoOperationEdit && input.Duration != 0 { + return media.Job{}, fmt.Errorf("视频编辑不支持 duration") + } + if operation == provider.VideoOperationExtend { + if input.Duration == 0 { + input.Duration = 6 + } + if input.Duration < 2 || input.Duration > 10 { + return media.Job{}, fmt.Errorf("视频延长 duration 必须在 2 到 10 秒之间") + } + } + } + allRefs := videoInputReferences(input.ImageURL, input.ReferenceURLs) + if err := s.validateVideoInputReferences(ctx, allRefs, "image"); err != nil { return media.Job{}, err } - inputJSON, err := encodeVideoInput(input.ReferenceURLs) + if videoURL := strings.TrimSpace(input.VideoURL); videoURL != "" { + if err := s.validateVideoInputReferences(ctx, []string{videoURL}, "video"); err != nil { + return media.Job{}, err + } + } + inputJSON, err := encodeVideoInputFull(operation, input.ImageURL, input.ReferenceURLs, input.ReferenceAudios, input.VideoURL) if err != nil { return media.Job{}, err } @@ -68,19 +138,28 @@ func (s *Service) CreateVideo(ctx context.Context, input VideoInput) (media.Job, if err != nil { return media.Job{}, ErrModelNotFound } - route, err := s.selectMediaRoute(routes, input.ClientKey, model.CapabilityVideo, func(providerValue account.Provider) bool { + routes, err = routesForVideoOperation(routes, operation) + if err != nil { + return media.Job{}, err + } + route, selection, err := s.selectSchedulableMediaRouteWithQuotaMode(ctx, routes, input.ClientKey, model.CapabilityVideo, true, func(providerValue account.Provider) bool { _, ok := s.providers.Videos(providerValue) return ok + }, func(route model.Route) string { + return videoQuotaMode(route.Provider, s.providers.QuotaMode(route.Provider, route.UpstreamModel), input.Resolution) }) if err != nil { return media.Job{}, err } + if err := validateVideoRouteParameters(operation, route.UpstreamModel, input.Resolution, len(input.ReferenceURLs) > 0); err != nil { + return media.Job{}, err + } if err := s.checkLedgerReady(); err != nil { return media.Job{}, err } + pricing, priced := resolveVideoPricing(operation, route.UpstreamModel, input.Resolution, input.Duration, len(allRefs)) externalModel := model.ExternalPublicID(route.Provider, route.PublicID) - quotaMode := s.providers.QuotaMode(route.Provider, route.UpstreamModel) - lease, err := s.selector.AcquireForKey(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, "", nil, false, input.ClientKey.AccountScope()) + lease, err := selection.Acquire(ctx, nil, false) if err != nil { return media.Job{}, fmt.Errorf("%w: %w", ErrNoAvailableAccount, err) } @@ -95,12 +174,12 @@ func (s *Service) CreateVideo(ctx context.Context, input VideoInput) (media.Job, ID: "video_" + token, RequestID: input.RequestID, ClientKeyID: input.ClientKey.ID, ClientKeyName: input.ClientKey.Name, AccountID: accountID, AccountName: lease.Credential.Name, - Provider: string(route.Provider), Model: externalModel, ModelRouteID: route.ID, UpstreamModel: model.DisplayUpstreamModel(route.Provider, route.UpstreamModel), Prompt: input.Prompt, + Provider: string(route.Provider), Model: externalModel, ModelRouteID: route.ID, UpstreamModel: model.DisplayUpstreamModel(route.Provider, route.UpstreamModel), Operation: operation, Prompt: input.Prompt, Seconds: input.Duration, Size: input.AspectRatio, Quality: input.Resolution, - Status: media.StatusQueued, Progress: 0, InputJSON: inputJSON, InputImageCount: len(input.ReferenceURLs), CreatedAt: now, UpdatedAt: now, + Status: media.StatusQueued, Progress: 0, InputJSON: inputJSON, InputImageCount: len(allRefs), CreatedAt: now, UpdatedAt: now, } reserved := false - if pricing, ok := audit.EstimateOfficialVideoCost(externalModel, input.Resolution, input.Duration); ok { + if priced { reserved, err = s.clientKeys.ReserveBilling(ctx, input.ClientKey, "video_usage_"+job.ID, pricing.CostInUSDTicks, mediaBillingReservationTTL) if err != nil { return media.Job{}, err @@ -118,6 +197,42 @@ func (s *Service) CreateVideo(ctx context.Context, input VideoInput) (media.Job, return job, nil } +func validateVideoRouteParameters(operation provider.VideoOperation, upstreamModel, resolution string, hasReferences bool) error { + if operation != provider.VideoOperationGenerate || !strings.EqualFold(strings.TrimSpace(resolution), "1080p") { + return nil + } + if strings.TrimSpace(upstreamModel) != "grok-imagine-video-1.5" { + return fmt.Errorf("%w: %s 不支持 1080p", ErrVideoOperationUnsupported, upstreamModel) + } + if hasReferences { + return fmt.Errorf("%w: reference_images 模式最高支持 720p", ErrVideoOperationUnsupported) + } + return nil +} + +func routesForVideoOperation(routes []model.Route, operation provider.VideoOperation) ([]model.Route, error) { + if operation == provider.VideoOperationGenerate { + return routes, nil + } + compatible := make([]model.Route, 0, len(routes)) + for _, candidate := range routes { + if candidate.Provider == account.ProviderConsole && strings.TrimSpace(candidate.UpstreamModel) == "grok-imagine-video" { + compatible = append(compatible, candidate) + } + } + if len(compatible) == 0 { + return nil, ErrVideoOperationUnsupported + } + return compatible, nil +} + +func resolveVideoPricing(operation provider.VideoOperation, upstreamModel, resolution string, duration, inputImages int) (audit.PricingResult, bool) { + if operation == provider.VideoOperationGenerate { + return audit.EstimateOfficialVideoCost(upstreamModel, resolution, duration, inputImages) + } + return audit.PricingResult{}, false +} + func (s *Service) GetVideo(ctx context.Context, id string, key clientkey.Key) (media.Job, error) { if s.mediaJobs == nil { return media.Job{}, ErrResponseNotFound @@ -311,7 +426,8 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model defer releaseInputSlot() // 视频任务创建时已持久化账号归属;恢复只能重新获取原账号,禁止因后续 // 轮询或结果处理失败切换到其他账号。 - quotaMode := s.providers.QuotaMode(route.Provider, route.UpstreamModel) + quotaMode := videoQuotaMode(route.Provider, s.providers.QuotaMode(route.Provider, route.UpstreamModel), job.Quality) + quotaRefreshGroup := s.providers.QuotaRefreshGroup(route.Provider, route.UpstreamModel) lease, err := s.selector.AcquirePinned(ctx, route.Provider, job.AccountID, route.ID, route.UpstreamModel, quotaMode, true) if err != nil { if parent.Err() != nil { @@ -333,15 +449,30 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model s.failVideoJob(parent, job, "provider_unavailable", ErrNoAvailableAccount) return } - referenceURLs, err := s.resolveVideoInputReferences(ctx, inputReferences) + operation := provider.VideoOperation(job.Operation) + if operation == "" { + operation = decodeVideoOperation(job.InputJSON) + } + imageURL, referenceURLs, referenceAudios, videoURL, err := s.resolveVideoJobInputs(ctx, operation, job.InputJSON) if err != nil { s.failVideoJob(parent, job, "input_unavailable", err) return } lastProgress := job.Progress + duration := job.Seconds + aspectRatio := job.Size + resolution := job.Quality + switch operation { + case provider.VideoOperationEdit: + duration, aspectRatio, resolution = 0, "", "" + case provider.VideoOperationExtend: + aspectRatio, resolution = "", "" + } result, err := adapter.GenerateVideo(ctx, provider.VideoRequest{ - Credential: lease.Credential, Billing: lease.Billing, JobID: job.ID, Prompt: job.Prompt, Duration: job.Seconds, AspectRatio: job.Size, Resolution: job.Quality, - ReferenceURLs: referenceURLs, + Credential: lease.Credential, Billing: lease.Billing, JobID: job.ID, Model: route.UpstreamModel, + Operation: operation, + Prompt: job.Prompt, Duration: duration, AspectRatio: aspectRatio, Resolution: resolution, + ImageURL: imageURL, ReferenceURLs: referenceURLs, ReferenceAudios: referenceAudios, VideoURL: videoURL, Progress: func(value int) { value = min(99, max(1, value)) if value-lastProgress < 5 { @@ -433,26 +564,42 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model return } s.selector.MarkSuccess(context.Background(), lease.Credential) - if lease.QuotaMode != "" && lease.QuotaMode != "weekly" { + refreshMode := lease.QuotaMode + decrementMode := lease.QuotaMode + if quotaRefreshGroup != "" { + refreshMode = quotaRefreshGroup + decrementMode = quotaMode + } + if decrementMode != "" && decrementMode != "weekly" { quotaCtx, quotaCancel := context.WithTimeout(context.Background(), accountStateWriteTimeout) - updated, quotaErr := s.accounts.DecrementQuota(quotaCtx, job.AccountID, lease.QuotaMode, 1) + updated, quotaErr := s.accounts.DecrementQuota(quotaCtx, job.AccountID, decrementMode, 1) quotaCancel() if quotaErr != nil { - s.logger.Warn("video_quota_decrement_failed", "provider", route.Provider, "account_id", job.AccountID, "mode", lease.QuotaMode, "error", quotaErr) + s.logger.Warn("video_quota_decrement_failed", "provider", route.Provider, "account_id", job.AccountID, "mode", decrementMode, "error", quotaErr) } else if updated { - s.selector.ConsumeQuota(route.Provider, job.AccountID, lease.QuotaMode, 1) + s.selector.ConsumeQuota(route.Provider, job.AccountID, decrementMode, 1) } } if err := s.recordVideoAudit(context.Background(), job, time.Since(startedAt).Milliseconds()); err != nil { s.logger.Error("video_usage_record_failed", "job_id", job.ID, "event_id", "video_usage_"+job.ID, "error", err) } - if quotaKind, _ := s.providers.QuotaKind(route.Provider); quotaKind == provider.QuotaRemoteWindow && lease.QuotaMode != "" { - s.accounts.QueueQuotaRefresh(job.AccountID, lease.QuotaMode) + if quotaKind, _ := s.providers.QuotaKind(route.Provider); quotaKind == provider.QuotaRemoteWindow && refreshMode != "" { + s.accounts.QueueQuotaRefresh(job.AccountID, refreshMode) } // 输入回收放在账号状态、计费和审计收尾之后,存储抖动不得延迟关键终态逻辑。 s.releaseVideoInputs(job) } +func videoQuotaMode(providerValue account.Provider, catalogMode, resolution string) string { + if providerValue == account.ProviderWeb && catalogMode == account.QuotaModeWebVideo { + resolution = strings.ToLower(strings.TrimSpace(resolution)) + if resolution == "" || resolution == "720p" { + return account.QuotaModeWebVideo720p + } + } + return catalogMode +} + func (s *Service) acquireVideoInputSlot(ctx context.Context, references []string) (func(), error) { hasLocalInput := false for _, reference := range references { @@ -473,7 +620,7 @@ func (s *Service) acquireVideoInputSlot(ctx context.Context, references []string } } -func (s *Service) validateVideoInputReferences(ctx context.Context, references []string) error { +func (s *Service) validateVideoInputReferences(ctx context.Context, references []string, expectedKind string) error { estimatedBytes := videoInputJSONBaseBytes for _, reference := range references { fileID, local := media.ParseInputReference(reference) @@ -486,11 +633,14 @@ func (s *Service) validateVideoInputReferences(ctx context.Context, references [ if s.mediaAssets == nil || !local { return ErrVideoInputUnavailable } - asset, body, err := s.mediaAssets.OpenInputImage(ctx, fileID) + asset, body, err := s.mediaAssets.OpenInputAsset(ctx, fileID) if err != nil { return fmt.Errorf("%w: %v", ErrVideoInputUnavailable, err) } _ = body.Close() + if asset.Kind != expectedKind { + return fmt.Errorf("%w: file_id 必须引用%s", ErrVideoInputUnavailable, expectedKind) + } if !addVideoReferenceBytes(&estimatedBytes, materializedVideoReferenceBytes(asset.MIMEType, asset.SizeBytes)) { return ErrVideoInputTooLarge } @@ -498,7 +648,38 @@ func (s *Service) validateVideoInputReferences(ctx context.Context, references [ return nil } -func (s *Service) resolveVideoInputReferences(ctx context.Context, references []string) ([]string, error) { +func (s *Service) resolveVideoInputParts(ctx context.Context, inputJSON string) (string, []string, error) { + imageURL, referenceURLs := decodeVideoInputParts(inputJSON) + all := videoInputReferences(imageURL, referenceURLs) + resolved, err := s.resolveVideoInputReferences(ctx, all, "image") + if err != nil { + return "", nil, err + } + // Map resolved URLs back while preserving empty/non-empty slots by original order. + next := 0 + take := func(original string) string { + original = strings.TrimSpace(original) + if original == "" { + return "" + } + if next >= len(resolved) { + return original + } + value := resolved[next] + next++ + return value + } + outImage := take(imageURL) + outRefs := make([]string, 0, len(referenceURLs)) + for _, raw := range referenceURLs { + if value := take(raw); value != "" { + outRefs = append(outRefs, value) + } + } + return outImage, outRefs, nil +} + +func (s *Service) resolveVideoInputReferences(ctx context.Context, references []string, expectedKind string) ([]string, error) { resolved := make([]string, 0, len(references)) estimatedBytes := videoInputJSONBaseBytes for _, reference := range references { @@ -513,10 +694,14 @@ func (s *Service) resolveVideoInputReferences(ctx context.Context, references [] if s.mediaAssets == nil || !local { return nil, ErrVideoInputUnavailable } - asset, body, err := s.mediaAssets.OpenInputImage(ctx, fileID) + asset, body, err := s.mediaAssets.OpenInputAsset(ctx, fileID) if err != nil { return nil, fmt.Errorf("%w: %v", ErrVideoInputUnavailable, err) } + if asset.Kind != expectedKind { + _ = body.Close() + return nil, fmt.Errorf("%w: file_id 必须引用%s", ErrVideoInputUnavailable, expectedKind) + } data, readErr := io.ReadAll(io.LimitReader(body, media.MaxInputJSONBytes+1)) closeErr := body.Close() if readErr != nil { @@ -649,10 +834,14 @@ func (s *Service) recordVideoAudit(ctx context.Context, job media.Job, durationM MediaInputImages: int64(job.InputImageCount), DurationMS: durationMS, CreatedAt: createdAt, } - if job.Status == media.StatusCompleted { + if job.Status == media.StatusCompleted && job.Seconds > 0 { record.MediaOutputSeconds = int64(max(0, job.Seconds)) } - if pricing, ok := audit.EstimateOfficialVideoCost(job.Model, job.Quality, job.Seconds); ok && job.Status == media.StatusCompleted { + operation := provider.VideoOperation(job.Operation) + if operation == "" { + operation = provider.VideoOperationGenerate + } + if pricing, ok := audit.EstimateOfficialVideoCost(job.UpstreamModel, job.Quality, job.Seconds, job.InputImageCount); ok && job.Status == media.StatusCompleted && operation == provider.VideoOperationGenerate { record.EstimatedCostInUSDTicks = pricing.CostInUSDTicks record.PricingModel = pricing.Model record.PricingVersion = audit.OfficialPricingAsOf @@ -671,8 +860,44 @@ func (s *Service) recordVideoAudit(ctx context.Context, job media.Job, durationM return s.mediaJobs.MarkMediaJobUsageRecorded(markCtx, job.ID, time.Now().UTC()) } -func encodeVideoInput(referenceURLs []string) (string, error) { - data, err := json.Marshal(map[string][]string{"image_urls": referenceURLs}) +func encodeVideoInput(imageURL string, referenceURLs []string) (string, error) { + return encodeVideoInputFull(provider.VideoOperationGenerate, imageURL, referenceURLs, nil, "") +} + +func encodeVideoInputFull(operation provider.VideoOperation, imageURL string, referenceURLs []string, referenceAudios []string, videoURL string) (string, error) { + payload := map[string]any{} + if operation == "" { + operation = provider.VideoOperationGenerate + } + if operation != provider.VideoOperationGenerate { + payload["operation"] = string(operation) + } + if value := strings.TrimSpace(imageURL); value != "" { + payload["image_url"] = value + } + refs := make([]string, 0, len(referenceURLs)) + for _, raw := range referenceURLs { + if value := strings.TrimSpace(raw); value != "" { + refs = append(refs, value) + } + } + if len(refs) > 0 { + payload["reference_urls"] = refs + } + audios := normalizeVideoReferenceAudios(referenceAudios) + if len(audios) > 0 { + payload["reference_audios"] = audios + } + if value := strings.TrimSpace(videoURL); value != "" { + payload["video_url"] = value + } + // Keep a combined image_urls field for older readers/tools that only + // understand the pre-split shape. New workers prefer image_url/reference_urls. + combined := videoInputReferences(imageURL, referenceURLs) + if len(combined) > 0 { + payload["image_urls"] = combined + } + data, err := json.Marshal(payload) if err != nil { return "", fmt.Errorf("编码视频输入: %w", err) } @@ -683,9 +908,133 @@ func encodeVideoInput(referenceURLs []string) (string, error) { } func decodeVideoInput(value string) []string { - var input map[string][]string + imageURL, refs, videoURL := decodeVideoInputFull(value) + values := videoInputReferences(imageURL, refs) + if v := strings.TrimSpace(videoURL); v != "" { + values = append(values, v) + } + return values +} + +func decodeVideoInputParts(value string) (string, []string) { + imageURL, refs, _ := decodeVideoInputFull(value) + return imageURL, refs +} + +func decodeVideoInputFull(value string) (string, []string, string) { + imageURL, refs, _, videoURL := decodeVideoInputDetailed(value) + return imageURL, refs, videoURL +} + +func decodeVideoInputDetailed(value string) (string, []string, []string, string) { + var input struct { + Operation string `json:"operation"` + ImageURL string `json:"image_url"` + ReferenceURLs []string `json:"reference_urls"` + ReferenceAudios []string `json:"reference_audios"` + ImageURLs []string `json:"image_urls"` + VideoURL string `json:"video_url"` + } _ = json.Unmarshal([]byte(value), &input) - return input["image_urls"] + videoURL := strings.TrimSpace(input.VideoURL) + audios := normalizeVideoReferenceAudios(input.ReferenceAudios) + if strings.TrimSpace(input.ImageURL) != "" || len(input.ReferenceURLs) > 0 || len(audios) > 0 || videoURL != "" || strings.TrimSpace(input.Operation) != "" { + refs := make([]string, 0, len(input.ReferenceURLs)) + for _, raw := range input.ReferenceURLs { + if v := strings.TrimSpace(raw); v != "" { + refs = append(refs, v) + } + } + return strings.TrimSpace(input.ImageURL), refs, audios, videoURL + } + // Legacy jobs stored a flat image_urls list. Preserve historical mapping: + // one URL was treated as the first-frame image; multiple URLs were references. + legacy := make([]string, 0, len(input.ImageURLs)) + for _, raw := range input.ImageURLs { + if v := strings.TrimSpace(raw); v != "" { + legacy = append(legacy, v) + } + } + switch len(legacy) { + case 0: + return "", nil, nil, "" + case 1: + return legacy[0], nil, nil, "" + default: + return "", legacy, nil, "" + } +} + +func decodeVideoOperation(value string) provider.VideoOperation { + var input struct { + Operation string `json:"operation"` + } + _ = json.Unmarshal([]byte(value), &input) + switch provider.VideoOperation(strings.TrimSpace(input.Operation)) { + case provider.VideoOperationEdit: + return provider.VideoOperationEdit + case provider.VideoOperationExtend: + return provider.VideoOperationExtend + default: + return provider.VideoOperationGenerate + } +} + +func (s *Service) resolveVideoJobInputs(ctx context.Context, operation provider.VideoOperation, inputJSON string) (string, []string, []string, string, error) { + _, _, referenceAudios, videoURL := decodeVideoInputDetailed(inputJSON) + resolvedImage, resolvedRefs, err := s.resolveVideoInputParts(ctx, inputJSON) + if err != nil { + return "", nil, nil, "", err + } + if strings.TrimSpace(videoURL) == "" { + return resolvedImage, resolvedRefs, referenceAudios, "", nil + } + if operation == provider.VideoOperationGenerate { + return "", nil, nil, "", ErrVideoInputUnavailable + } + resolvedVideos, err := s.resolveVideoInputReferences(ctx, []string{videoURL}, "video") + if err != nil { + return "", nil, nil, "", err + } + if len(resolvedVideos) == 0 { + return "", nil, nil, "", ErrVideoInputUnavailable + } + return resolvedImage, resolvedRefs, referenceAudios, resolvedVideos[0], nil +} + +func validateVideoReferenceAudios(values []string) error { + if len(values) > 3 { + return fmt.Errorf("reference_audios 最多 3 个") + } + for _, raw := range values { + if strings.TrimSpace(raw) == "" { + return fmt.Errorf("reference_audios.voice_id 不能为空") + } + } + return nil +} + +func normalizeVideoReferenceAudios(values []string) []string { + out := make([]string, 0, len(values)) + for _, raw := range values { + if value := strings.TrimSpace(raw); value != "" { + out = append(out, value) + } + } + return out +} + +func videoInputReferences(imageURL string, referenceURLs []string) []string { + values := make([]string, 0, 1+len(referenceURLs)) + if v := strings.TrimSpace(imageURL); v != "" { + values = append(values, v) + } + for _, raw := range referenceURLs { + if v := strings.TrimSpace(raw); v != "" { + values = append(values, v) + } + } + return values } func (s *Service) failVideoJob(ctx context.Context, job media.Job, code string, err error) { @@ -716,7 +1065,7 @@ func (s *Service) releaseVideoInputs(job media.Job) { } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - if err := s.mediaAssets.ReleaseInputImages(ctx, references); err != nil { + if err := s.mediaAssets.ReleaseInputAssets(ctx, references); err != nil { logger := s.logger if logger == nil { logger = slog.Default() diff --git a/backend/internal/application/gateway/video_test.go b/backend/internal/application/gateway/video_test.go index d8240995..05f82ff0 100644 --- a/backend/internal/application/gateway/video_test.go +++ b/backend/internal/application/gateway/video_test.go @@ -16,16 +16,35 @@ import ( "github.com/chenyme/grok2api/backend/internal/domain/account" "github.com/chenyme/grok2api/backend/internal/domain/audit" "github.com/chenyme/grok2api/backend/internal/domain/media" + "github.com/chenyme/grok2api/backend/internal/domain/model" "github.com/chenyme/grok2api/backend/internal/infra/provider" "github.com/chenyme/grok2api/backend/internal/repository" ) +func TestVideoQuotaModeUsesWeb720pProduct(t *testing.T) { + tests := []struct { + provider account.Provider + resolution string + want string + }{ + {account.ProviderWeb, "", account.QuotaModeWebVideo720p}, + {account.ProviderWeb, "720p", account.QuotaModeWebVideo720p}, + {account.ProviderWeb, "480p", account.QuotaModeWebVideo}, + {account.ProviderConsole, "720p", account.QuotaModeWebVideo}, + } + for _, test := range tests { + if got := videoQuotaMode(test.provider, account.QuotaModeWebVideo, test.resolution); got != test.want { + t.Fatalf("videoQuotaMode(%s, %q) = %q, want %q", test.provider, test.resolution, got, test.want) + } + } +} + func TestRecoverVideoJobsRetriesUsageWithoutRegeneratingVideo(t *testing.T) { completedAt := time.Now().UTC() repository := &videoUsageRepository{job: media.Job{ ID: "video_usage_recovery", RequestID: "request-usage-recovery", ClientKeyID: 1, ClientKeyName: "client", AccountID: 2, AccountName: "account", - Provider: "grok_web", Model: "grok-imagine-video", ModelRouteID: 3, UpstreamModel: "video", + Provider: "grok_web", Model: "custom-video", ModelRouteID: 3, UpstreamModel: "Web/grok-imagine-video", Seconds: 8, Quality: "720p", Status: media.StatusCompleted, InputImageCount: 2, CreatedAt: completedAt.Add(-time.Minute), CompletedAt: &completedAt, }} recorder := &durableVideoAuditRecorder{failures: 1} @@ -47,18 +66,135 @@ func TestRecoverVideoJobsRetriesUsageWithoutRegeneratingVideo(t *testing.T) { } } -func TestEncodeVideoInputEnforcesPersistedLimit(t *testing.T) { - overhead := len(`{"image_urls":[""]}`) - atLimit := strings.Repeat("A", media.MaxInputJSONBytes-overhead) - encoded, err := encodeVideoInput([]string{atLimit}) - if err != nil || len(encoded) != media.MaxInputJSONBytes { - t.Fatalf("encoded len=%d err=%v", len(encoded), err) +func TestVideoEditRouteUsesResolvedUpstreamInsteadOfPublicName(t *testing.T) { + routes := []model.Route{ + {ID: 1, PublicID: "grok-imagine-video", Provider: account.ProviderBuild, UpstreamModel: "grok-imagine-video"}, + {ID: 2, PublicID: "company-video-editor", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-video"}, + {ID: 3, PublicID: "company-video-editor", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-video-1.5"}, } - if _, err := encodeVideoInput([]string{atLimit + "A"}); !errors.Is(err, ErrVideoInputTooLarge) { + compatible, err := routesForVideoOperation(routes, provider.VideoOperationEdit) + if err != nil { + t.Fatal(err) + } + if len(compatible) != 1 || compatible[0].ID != 2 { + t.Fatalf("compatible routes = %#v", compatible) + } + if _, err := routesForVideoOperation(routes[:1], provider.VideoOperationExtend); !errors.Is(err, ErrVideoOperationUnsupported) { + t.Fatalf("unsupported route error = %v", err) + } +} + +func TestVideoPricingLeavesUnmeasurableOperationsUnpriced(t *testing.T) { + pricing, priced := resolveVideoPricing(provider.VideoOperationGenerate, "Console/grok-imagine-video", "720p", 6, 1) + if !priced || pricing.CostInUSDTicks <= 0 { + t.Fatalf("priced generation = %#v, priced=%v", pricing, priced) + } + if pricing, priced := resolveVideoPricing(provider.VideoOperationGenerate, "Console/grok-imagine-video", "", 6, 0); priced || pricing.CostInUSDTicks != 0 { + t.Fatalf("generation without resolution = %#v, priced=%v", pricing, priced) + } + if pricing, priced := resolveVideoPricing(provider.VideoOperationExtend, "Console/grok-imagine-video", "", 6, 0); priced || pricing.CostInUSDTicks != 0 { + t.Fatalf("extension without measurable input duration = %#v, priced=%v", pricing, priced) + } +} + +func TestVideo1080pValidationUsesResolvedUpstreamModel(t *testing.T) { + if err := validateVideoRouteParameters(provider.VideoOperationGenerate, "grok-imagine-video-1.5", "1080P", false); err != nil { + t.Fatalf("1.5 text/image 1080p rejected: %v", err) + } + if err := validateVideoRouteParameters(provider.VideoOperationGenerate, "grok-imagine-video", "1080p", false); !errors.Is(err, ErrVideoOperationUnsupported) { + t.Fatalf("legacy 1080p error = %v", err) + } + if err := validateVideoRouteParameters(provider.VideoOperationGenerate, "grok-imagine-video-1.5", "1080p", true); !errors.Is(err, ErrVideoOperationUnsupported) { + t.Fatalf("reference 1080p error = %v", err) + } +} + +func TestEncodeVideoInputEnforcesPersistedLimit(t *testing.T) { + // image_url and combined image_urls both store the same value, so the URL is counted twice. + base := `{"image_url":"","image_urls":[""]}` + overhead := len(base) + urlLen := (media.MaxInputJSONBytes - overhead) / 2 + atLimit := strings.Repeat("A", urlLen) + encoded, err := encodeVideoInput(atLimit, nil) + if err != nil { + t.Fatalf("encode at limit: %v", err) + } + if len(encoded) > media.MaxInputJSONBytes { + t.Fatalf("encoded len=%d exceeds limit", len(encoded)) + } + if _, err := encodeVideoInput(atLimit+"AA", nil); !errors.Is(err, ErrVideoInputTooLarge) { t.Fatalf("oversized input error = %v", err) } } +func TestEncodeDecodeVideoInputPreservesImageAndReferences(t *testing.T) { + encoded, err := encodeVideoInput("https://example.com/first.png", []string{"https://example.com/ref.png"}) + if err != nil { + t.Fatal(err) + } + imageURL, refs := decodeVideoInputParts(encoded) + if imageURL != "https://example.com/first.png" || len(refs) != 1 || refs[0] != "https://example.com/ref.png" { + t.Fatalf("decoded split = %q %#v from %s", imageURL, refs, encoded) + } + + encoded, err = encodeVideoInput("", []string{"https://example.com/ref-only.png"}) + if err != nil { + t.Fatal(err) + } + imageURL, refs = decodeVideoInputParts(encoded) + if imageURL != "" || len(refs) != 1 || refs[0] != "https://example.com/ref-only.png" { + t.Fatalf("single reference decoded = %q %#v from %s", imageURL, refs, encoded) + } + + imageURL, refs = decodeVideoInputParts(`{"image_urls":["https://legacy/one.png"]}`) + if imageURL != "https://legacy/one.png" || len(refs) != 0 { + t.Fatalf("legacy single = %q %#v", imageURL, refs) + } + imageURL, refs = decodeVideoInputParts(`{"image_urls":["https://legacy/a.png","https://legacy/b.png"]}`) + if imageURL != "" || len(refs) != 2 || refs[0] != "https://legacy/a.png" || refs[1] != "https://legacy/b.png" { + t.Fatalf("legacy multi = %q %#v", imageURL, refs) + } +} + +func TestEncodeDecodeVideoInputPreservesOperationAndReferenceAudio(t *testing.T) { + encoded, err := encodeVideoInputFull( + provider.VideoOperationGenerate, + "", + []string{"https://example.com/ref.png"}, + []string{"eve", " ara "}, + "", + ) + if err != nil { + t.Fatal(err) + } + imageURL, refs, audios, videoURL := decodeVideoInputDetailed(encoded) + if imageURL != "" || videoURL != "" || len(refs) != 1 || refs[0] != "https://example.com/ref.png" || len(audios) != 2 || audios[0] != "eve" || audios[1] != "ara" { + t.Fatalf("decoded reference input = image %q refs %#v audios %#v video %q from %s", imageURL, refs, audios, videoURL, encoded) + } + if operation := decodeVideoOperation(encoded); operation != provider.VideoOperationGenerate { + t.Fatalf("generation operation = %q", operation) + } + + encoded, err = encodeVideoInputFull(provider.VideoOperationExtend, "", nil, nil, media.InputReference("source-video")) + if err != nil { + t.Fatal(err) + } + if operation := decodeVideoOperation(encoded); operation != provider.VideoOperationExtend { + t.Fatalf("extension operation = %q from %s", operation, encoded) + } + _, _, _, videoURL = decodeVideoInputDetailed(encoded) + if videoURL != media.InputReference("source-video") { + t.Fatalf("extension video = %q", videoURL) + } + + if err := validateVideoReferenceAudios([]string{"eve", ""}); err == nil { + t.Fatal("blank reference voice was accepted") + } + if err := validateVideoReferenceAudios([]string{"a", "b", "c", "d"}); err == nil { + t.Fatal("too many reference voices were accepted") + } +} + func TestRecoverVideoJobsRecordsFailedAuditWithEgress(t *testing.T) { completedAt := time.Now().UTC() nodeID := uint64(42) @@ -181,10 +317,13 @@ func TestResolveVideoInputFileReferenceToDataURI(t *testing.T) { store := &videoAssetStoreStub{inputID: inputID, inputData: raw} service := &Service{mediaAssets: store} reference := VideoInputFileReference(inputID) - if err := service.validateVideoInputReferences(context.Background(), []string{reference}); err != nil { + if err := service.validateVideoInputReferences(context.Background(), []string{reference}, "image"); err != nil { t.Fatal(err) } - resolved, err := service.resolveVideoInputReferences(context.Background(), []string{"https://example.com/a.png", reference}) + if err := service.validateVideoInputReferences(context.Background(), []string{reference}, "video"); !errors.Is(err, ErrVideoInputUnavailable) { + t.Fatalf("image accepted as video input: %v", err) + } + resolved, err := service.resolveVideoInputReferences(context.Background(), []string{"https://example.com/a.png", reference}, "image") if err != nil { t.Fatal(err) } @@ -192,11 +331,11 @@ func TestResolveVideoInputFileReferenceToDataURI(t *testing.T) { if len(resolved) != 2 || resolved[0] != "https://example.com/a.png" || resolved[1] != want { t.Fatalf("resolved=%#v", resolved) } - if err := service.validateVideoInputReferences(context.Background(), []string{VideoInputFileReference("missing")}); !errors.Is(err, ErrVideoInputUnavailable) { + if err := service.validateVideoInputReferences(context.Background(), []string{VideoInputFileReference("missing")}, "image"); !errors.Is(err, ErrVideoInputUnavailable) { t.Fatalf("missing input error=%v", err) } store.inputSize = 20 << 20 - if err := service.validateVideoInputReferences(context.Background(), []string{reference, reference}); !errors.Is(err, ErrVideoInputTooLarge) { + if err := service.validateVideoInputReferences(context.Background(), []string{reference, reference}, "image"); !errors.Is(err, ErrVideoInputTooLarge) { t.Fatalf("aggregate local input error=%v", err) } } @@ -257,6 +396,8 @@ type videoAssetStoreStub struct { inputID string inputData []byte inputSize int64 + inputKind string + inputMIME string } func (s *videoAssetStoreStub) SaveVideo(_ context.Context, jobID, contentType string, body io.Reader) (media.Asset, error) { @@ -278,7 +419,7 @@ func (*videoAssetStoreStub) OpenVideo(context.Context, string) (media.Asset, io. return media.Asset{}, nil, errors.New("not implemented") } -func (s *videoAssetStoreStub) OpenInputImage(_ context.Context, id string) (media.Asset, io.ReadCloser, error) { +func (s *videoAssetStoreStub) OpenInputAsset(_ context.Context, id string) (media.Asset, io.ReadCloser, error) { if id != s.inputID || len(s.inputData) == 0 { return media.Asset{}, nil, errors.New("not implemented") } @@ -286,10 +427,18 @@ func (s *videoAssetStoreStub) OpenInputImage(_ context.Context, id string) (medi if size <= 0 { size = int64(len(s.inputData)) } - return media.Asset{ID: id, Kind: "image", MIMEType: "image/png", SizeBytes: size}, io.NopCloser(bytes.NewReader(s.inputData)), nil + kind := s.inputKind + if kind == "" { + kind = "image" + } + mimeType := s.inputMIME + if mimeType == "" { + mimeType = "image/png" + } + return media.Asset{ID: id, Kind: kind, MIMEType: mimeType, SizeBytes: size}, io.NopCloser(bytes.NewReader(s.inputData)), nil } -func (*videoAssetStoreStub) ReleaseInputImages(context.Context, []string) error { return nil } +func (*videoAssetStoreStub) ReleaseInputAssets(context.Context, []string) error { return nil } type durableVideoAuditRecorder struct { failures int diff --git a/backend/internal/application/gateway/voice.go b/backend/internal/application/gateway/voice.go new file mode 100644 index 00000000..1d6b8566 --- /dev/null +++ b/backend/internal/application/gateway/voice.go @@ -0,0 +1,543 @@ +package gateway + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strconv" + "strings" + "sync" + "time" + + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/domain/audit" + "github.com/chenyme/grok2api/backend/internal/domain/clientkey" + modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" + infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" + "github.com/chenyme/grok2api/backend/internal/infra/provider" +) + +type TTSInput struct { + RequestID string + ClientKey clientkey.Key + PublicModel string + Text string + VoiceID string + Language string + OutputFormat provider.TTSOutputFormat + Speed float64 + OptimizeStreamingLatency int + TextNormalization bool + WithTimestamps bool +} + +type STTInput struct { + RequestID string + ClientKey clientkey.Key + PublicModel string + FileName string + FileMIME string + FileData []byte + URL string + AudioFormat string + SampleRate string + Language string + Format bool + Multichannel bool + Channels int + Diarize bool + KeyTerms []string + FillerWords bool + VADThreshold *float64 + // ResponseFormat is empty for the native Console-compatible response, or an + // OpenAI-compatible format normalized by the HTTP transport. + ResponseFormat string +} + +type VoiceListInput struct { + RequestID string + ClientKey clientkey.Key + PublicModel string +} + +type VoiceIDInput struct { + RequestID string + ClientKey clientkey.Key + PublicModel string + VoiceID string +} + +type voiceProviderSupport func(accountdomain.Provider) bool + +type voiceExecutionResult struct { + response *provider.Response + pricing audit.PricingResult +} + +func (s *Service) SynthesizeSpeech(ctx context.Context, input TTSInput) (*Result, error) { + reservation, _ := audit.EstimateOfficialTTSCost(input.Text) + return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationTTS, modeldomain.CapabilityTTS, true, reservation, func(providerValue accountdomain.Provider) bool { + _, ok := s.providers.TTS(providerValue) + return ok + }, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, upstream string) (voiceExecutionResult, error) { + adapter, ok := s.providers.TTS(providerValue) + if !ok { + return voiceExecutionResult{}, ErrNoAvailableAccount + } + result, err := adapter.SynthesizeSpeech(executionCtx, provider.TTSRequest{ + Credential: credential, Model: upstream, Text: input.Text, VoiceID: input.VoiceID, Language: input.Language, + OutputFormat: input.OutputFormat, Speed: input.Speed, OptimizeStreamingLatency: input.OptimizeStreamingLatency, + TextNormalization: input.TextNormalization, WithTimestamps: input.WithTimestamps, + }) + if err != nil { + return voiceExecutionResult{}, err + } + if result.JSONEnvelope || input.WithTimestamps { + payload := map[string]any{ + "audio": firstNonEmpty(result.Base64Audio, base64.StdEncoding.EncodeToString(result.Audio)), + "content_type": firstNonEmpty(result.ContentType, "audio/mpeg"), + "duration": result.Duration, + } + if result.Timestamps != nil { + times := make([]map[string]any, 0, len(result.Timestamps.GraphTimes)) + for _, item := range result.Timestamps.GraphTimes { + times = append(times, map[string]any{"start": item.Start, "end": item.End}) + } + payload["audio_timestamps"] = map[string]any{"graph_chars": result.Timestamps.GraphChars, "graph_times": times} + } + return voiceExecutionResult{response: jsonVoiceResponse(http.StatusOK, payload), pricing: reservation}, nil + } + header := http.Header{} + header.Set("Content-Type", firstNonEmpty(result.ContentType, "audio/mpeg")) + header.Set("Content-Length", fmt.Sprintf("%d", len(result.Audio))) + return voiceExecutionResult{response: &provider.Response{ + StatusCode: http.StatusOK, + Status: fmt.Sprintf("%d %s", http.StatusOK, http.StatusText(http.StatusOK)), + Header: header, + Body: io.NopCloser(bytes.NewReader(result.Audio)), + QuotaUnits: 1, + }, pricing: reservation}, nil + }) +} + +func (s *Service) ListTTSVoices(ctx context.Context, input VoiceListInput) (*Result, error) { + return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationTTS, modeldomain.CapabilityTTS, false, audit.PricingResult{}, func(providerValue accountdomain.Provider) bool { + _, ok := s.providers.TTS(providerValue) + return ok + }, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (voiceExecutionResult, error) { + adapter, ok := s.providers.TTS(providerValue) + if !ok { + return voiceExecutionResult{}, ErrNoAvailableAccount + } + voices, err := adapter.ListTTSVoices(executionCtx, credential) + if err != nil { + return voiceExecutionResult{}, err + } + items := make([]map[string]any, 0, len(voices)) + for _, voice := range voices { + item := map[string]any{"voice_id": voice.VoiceID, "name": voice.Name} + if voice.Language != "" { + item["language"] = voice.Language + } else { + item["language"] = nil + } + items = append(items, item) + } + response := jsonVoiceResponse(http.StatusOK, map[string]any{"voices": items}) + response.QuotaUnits = 0 + return voiceExecutionResult{response: response}, nil + }) +} + +func (s *Service) GetTTSVoice(ctx context.Context, input VoiceIDInput) (*Result, error) { + return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationTTS, modeldomain.CapabilityTTS, false, audit.PricingResult{}, func(providerValue accountdomain.Provider) bool { + _, ok := s.providers.TTS(providerValue) + return ok + }, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (voiceExecutionResult, error) { + adapter, ok := s.providers.TTS(providerValue) + if !ok { + return voiceExecutionResult{}, ErrNoAvailableAccount + } + voice, err := adapter.GetTTSVoice(executionCtx, credential, input.VoiceID) + if err != nil { + return voiceExecutionResult{}, err + } + payload := map[string]any{"voice_id": voice.VoiceID, "name": voice.Name} + if voice.Language != "" { + payload["language"] = voice.Language + } else { + payload["language"] = nil + } + response := jsonVoiceResponse(http.StatusOK, payload) + response.QuotaUnits = 0 + return voiceExecutionResult{response: response}, nil + }) +} + +func (s *Service) TranscribeSpeech(ctx context.Context, input STTInput) (*Result, error) { + return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationSTT, modeldomain.CapabilitySTT, true, audit.PricingResult{}, func(providerValue accountdomain.Provider) bool { + _, ok := s.providers.STT(providerValue) + return ok + }, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, upstream string) (voiceExecutionResult, error) { + adapter, ok := s.providers.STT(providerValue) + if !ok { + return voiceExecutionResult{}, ErrNoAvailableAccount + } + result, err := adapter.TranscribeSpeech(executionCtx, provider.STTRequest{ + Credential: credential, Model: upstream, FileName: input.FileName, FileMIME: input.FileMIME, FileData: input.FileData, + URL: input.URL, AudioFormat: input.AudioFormat, SampleRate: input.SampleRate, Language: input.Language, Format: input.Format, + Multichannel: input.Multichannel, Channels: input.Channels, Diarize: input.Diarize, KeyTerms: input.KeyTerms, + FillerWords: input.FillerWords, VADThreshold: input.VADThreshold, + }) + if err != nil { + return voiceExecutionResult{}, err + } + pricing, _ := audit.EstimateOfficialSTTCost(result.Duration, false) + return voiceExecutionResult{response: formatSTTResponse(result, input.ResponseFormat), pricing: pricing}, nil + }) +} + +func formatSTTResponse(result provider.STTResult, responseFormat string) *provider.Response { + switch responseFormat { + case "text": + data := []byte(result.Text) + header := http.Header{} + header.Set("Content-Type", "text/plain; charset=utf-8") + header.Set("Content-Length", strconv.Itoa(len(data))) + return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: header, Body: io.NopCloser(bytes.NewReader(data)), QuotaUnits: 1} + case "json": + return jsonVoiceResponse(http.StatusOK, map[string]any{"text": result.Text}) + case "verbose_json": + payload := map[string]any{"task": "transcribe", "text": result.Text, "language": result.Language, "duration": result.Duration} + if len(result.Words) > 0 { + words := make([]map[string]any, 0, len(result.Words)) + for _, word := range result.Words { + item := map[string]any{"word": word.Text, "start": word.Start, "end": word.End} + if word.Speaker != nil { + item["speaker"] = *word.Speaker + } + words = append(words, item) + } + payload["words"] = words + } + return jsonVoiceResponse(http.StatusOK, payload) + } + if len(result.RawJSON) > 0 { + header := http.Header{} + header.Set("Content-Type", "application/json") + header.Set("Content-Length", strconv.Itoa(len(result.RawJSON))) + return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: header, Body: io.NopCloser(bytes.NewReader(result.RawJSON)), QuotaUnits: 1} + } + payload := map[string]any{"text": result.Text, "language": result.Language, "duration": result.Duration} + if len(result.Words) > 0 { + words := make([]map[string]any, 0, len(result.Words)) + for _, word := range result.Words { + item := map[string]any{"text": word.Text, "start": word.Start, "end": word.End} + if word.Speaker != nil { + item["speaker"] = *word.Speaker + } + words = append(words, item) + } + payload["words"] = words + } + if len(result.Channels) > 0 { + channels := make([]map[string]any, 0, len(result.Channels)) + for _, channel := range result.Channels { + item := map[string]any{"index": channel.Index, "text": channel.Text} + if len(channel.Words) > 0 { + words := make([]map[string]any, 0, len(channel.Words)) + for _, word := range channel.Words { + wordItem := map[string]any{"text": word.Text, "start": word.Start, "end": word.End} + if word.Speaker != nil { + wordItem["speaker"] = *word.Speaker + } + words = append(words, wordItem) + } + item["words"] = words + } + channels = append(channels, item) + } + payload["channels"] = channels + } + return jsonVoiceResponse(http.StatusOK, payload) +} + +func (s *Service) executeVoice( + ctx context.Context, + requestID string, + key clientkey.Key, + publicModel string, + operation audit.Operation, + capability modeldomain.Capability, + consumesQuota bool, + reservation audit.PricingResult, + supports voiceProviderSupport, + execute func(context.Context, accountdomain.Provider, accountdomain.Credential, string) (voiceExecutionResult, error), +) (*Result, error) { + ctx, egressTrace := infraegress.WithTrace(ctx) + startedAt := time.Now() + eventID := newAuditEventID() + routes, err := s.models.GetByPublicIDCandidates(ctx, publicModel) + if err != nil { + return nil, ErrModelNotFound + } + route, preselectedSession, err := s.selectSchedulableMediaRoute(ctx, routes, key, capability, consumesQuota, supports) + if err != nil { + // Keep selection failures observable in request audits when no same-name + // target is schedulable; capability/scope failures still return directly. + route, err = s.selectMediaRoute(routes, key, capability, supports) + if err != nil { + return nil, err + } + preselectedSession = nil + } + externalModel := modeldomain.ExternalPublicID(route.Provider, route.PublicID) + auditBase := audit.Record{ + EventID: eventID, RequestID: requestID, ClientKeyID: key.ID, ClientKeyName: key.Name, + ModelRouteID: route.ID, ModelPublicID: externalModel, ModelUpstreamModel: modeldomain.DisplayUpstreamModel(route.Provider, route.UpstreamModel), + Provider: string(route.Provider), Operation: operation, UsageSource: audit.UsageSourceNone, + } + if err := s.checkLedgerReady(); err != nil { + return nil, err + } + if reservation.CostInUSDTicks > 0 { + if _, err := s.clientKeys.ReserveBilling(ctx, key, eventID, reservation.CostInUSDTicks, mediaBillingReservationTTL); err != nil { + return nil, err + } + } + writeFailureAudit := func(statusCode int, errorCode string, credential *accountdomain.Credential) { + record := auditBase + record.StatusCode = statusCode + record.ErrorCode = errorCode + record.DurationMS = time.Since(startedAt).Milliseconds() + record.CreatedAt = time.Now().UTC() + if credential != nil { + accountID := credential.ID + record.AccountID = &accountID + record.AccountName = credential.Name + } + applyAuditEgress(&record, egressTrace, route.Provider) + persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout) + defer cancel() + if auditErr := s.audits.Create(persistCtx, record); auditErr != nil { + s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", requestID, "error", auditErr) + } + } + quotaMode := "" + if consumesQuota { + quotaMode = s.providers.QuotaMode(route.Provider, route.UpstreamModel) + } + attemptPolicy := newRoutingAttemptPolicy(int(s.maxAttempts.Load())) + excluded := make(map[uint64]bool) + selection := preselectedSession + var lease *accountLease + var credential accountdomain.Credential + var response *provider.Response + var completedPricing audit.PricingResult + var responseRequestScoped bool + var lastCredentialFailure *accountdomain.Credential + var lastCredentialError error + for attempt := 0; attemptPolicy.allows(attempt); attempt++ { + if selection == nil { + selection, err = s.selector.beginSelectionSessionForKey(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, "", excluded, false, key.AccountScope()) + } + if err == nil { + lease, err = selection.Acquire(ctx, excluded, false) + } + if err != nil { + errorCode := "upstream_unavailable" + var selectionFailure *SelectionUnavailableError + if errors.As(err, &selectionFailure) { + errorCode = selectionFailure.Code() + } + writeFailureAudit(http.StatusServiceUnavailable, errorCode, lastCredentialFailure) + return nil, fmt.Errorf("%w: %w", ErrNoAvailableAccount, err) + } + excluded[lease.Credential.ID] = true + credential, err = s.accounts.EnsureCredential(ctx, lease.Credential, false) + if err != nil { + failedCredential := lease.Credential + lastCredentialFailure = &failedCredential + lastCredentialError = err + lease.Release() + continue + } + lease.markSelectorUpstreamStarted() + responseRequestScoped = false + execution, executionErr := execute(ctx, route.Provider, credential, route.UpstreamModel) + response, completedPricing, err = execution.response, execution.pricing, executionErr + if err != nil { + if _, ok := provider.ErrorHTTPStatus(err); ok { + responseRequestScoped = provider.IsRequestScopedError(err) + response, err = voiceErrorResponse(err) + } else if isSSOCredentialRejected(err, credential) { + s.markSSOCredentialRejected(ctx, credential, fmt.Sprintf("%s SSO credential rejected", credential.Provider)) + failedCredential := credential + lastCredentialFailure = &failedCredential + lastCredentialError = provider.ErrUnauthorized + lease.Release() + continue + } else { + failure := newTransportUpstreamFailure(err, credential.ID, credential.Name) + lastCredentialError = failure + if ctx.Err() == nil && isRetryableTransportFailure(credential.Provider, err) && attemptPolicy.hasNext(attempt) { + // Transport failures are normally tied to the selected egress. Retry the + // same account after the adapter has invalidated/rebuilt that transport, + // without cooling an otherwise healthy credential. + delete(excluded, credential.ID) + if selection != nil { + selection.RetryAccount(credential.ID) + } + lease.Release() + continue + } + lease.Release() + writeFailureAudit(failure.HTTPStatus, failure.AuditCode(), &credential) + return nil, failure + } + if err != nil { + lease.Release() + writeFailureAudit(http.StatusBadGateway, "upstream_unavailable", &credential) + return nil, err + } + } + if response.StatusCode == http.StatusUnauthorized && credential.AuthType == accountdomain.AuthTypeSSO { + _, _ = readRetryableBody(response.Body) + s.markSSOCredentialRejected(ctx, credential, fmt.Sprintf("%s SSO credential rejected", credential.Provider)) + failedCredential := credential + lastCredentialFailure = &failedCredential + lastCredentialError = provider.ErrUnauthorized + response = nil + lease.Release() + continue + } + if s.providers.RetryForbiddenAsEgress(credential.Provider) && response.StatusCode == http.StatusForbidden && !responseRequestScoped && attempt == 0 && attemptPolicy.hasNext(attempt) { + _, _ = readRetryableBody(response.Body) + delete(excluded, credential.ID) + if selection != nil { + selection.RetryAccount(credential.ID) + } + lease.Release() + continue + } + if response.StatusCode == http.StatusPaymentRequired || response.StatusCode == http.StatusTooManyRequests { + retryAfter := parseRetryAfter(response.Header.Get("Retry-After"), time.Now().UTC()) + if quotaKind, _ := s.providers.QuotaKind(credential.Provider); quotaKind == provider.QuotaRemoteWindow && lease.QuotaMode != "" { + exhausted, reconcileErr := s.accounts.ReconcileRateLimit(ctx, credential.ID, lease.QuotaMode, retryAfter) + s.selector.MarkQuotaStateChanged(credential.Provider, credential.ID) + if reconcileErr != nil || !exhausted { + s.selector.MarkFailure(ctx, credential, response.StatusCode, retryAfter) + } + } else { + s.selector.MarkFailure(ctx, credential, response.StatusCode, retryAfter) + } + if attemptPolicy.hasNext(attempt) { + _, _ = readRetryableBody(response.Body) + lease.Release() + continue + } + } + if response.StatusCode >= http.StatusInternalServerError && attemptPolicy.hasNext(attempt) { + _, _ = readRetryableBody(response.Body) + lease.Release() + continue + } + break + } + if response == nil { + writeFailureAudit(http.StatusServiceUnavailable, "upstream_unavailable", lastCredentialFailure) + if lastCredentialError == nil { + lastCredentialError = ErrNoAvailableAccount + } + return nil, fmt.Errorf("%w: %w", ErrNoAvailableAccount, lastCredentialError) + } + accountID := credential.ID + var once sync.Once + finalize := func(_ Usage, _ string, errorCode string) { + once.Do(func() { + successful := auditRequestSucceeded(response.StatusCode, errorCode) + lease.completeSelectorObservation(successful) + lease.Release() + budget := newFinalizationBudget(string(operation), string(route.Provider)) + record := auditBase + record.AccountID, record.AccountName, record.StatusCode = &accountID, credential.Name, response.StatusCode + record.ErrorCode = errorCode + record.DurationMS, record.CreatedAt = time.Since(startedAt).Milliseconds(), time.Now().UTC() + applyAuditEgress(&record, egressTrace, route.Provider) + if successful && completedPricing.CostInUSDTicks > 0 { + record.EstimatedCostInUSDTicks = completedPricing.CostInUSDTicks + record.PricingModel = completedPricing.Model + record.PricingVersion = audit.OfficialPricingAsOf + } + if successful && response.QuotaUnits > 0 && quotaMode != "" && quotaMode != "weekly" { + units := response.QuotaUnits + var updated bool + err := budget.run("quota_decrement", finalizationQuotaBudget, func(stageCtx context.Context) error { + var decrementErr error + updated, decrementErr = s.accounts.DecrementQuota(stageCtx, accountID, quotaMode, units) + return decrementErr + }) + if err != nil { + s.logger.Warn("voice_quota_decrement_failed", "provider", route.Provider, "account_id", accountID, "mode", quotaMode, "units", units, "error", err) + } else if updated { + s.selector.ConsumeQuota(route.Provider, accountID, quotaMode, units) + } + } + if successful && response.QuotaUnits > 0 && quotaMode != "" { + if quotaKind, _ := s.providers.QuotaKind(route.Provider); quotaKind == provider.QuotaRemoteWindow { + s.accounts.QueueQuotaRefresh(accountID, quotaMode) + } + } + if err := budget.run("audit", finalizationAuditBudget, func(stageCtx context.Context) error { + return s.audits.Create(stageCtx, record) + }); err != nil { + s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", requestID, "error", err) + } + }) + } + return &Result{StatusCode: response.StatusCode, Status: response.Status, Header: response.Header, Body: &finalizingBody{ReadCloser: response.Body, finalize: func() { finalize(Usage{}, "", "stream_closed") }}, Finalize: finalize}, nil +} + +func jsonVoiceResponse(status int, value any) *provider.Response { + data, _ := json.Marshal(value) + header := http.Header{} + header.Set("Content-Type", "application/json") + header.Set("Content-Length", fmt.Sprintf("%d", len(data))) + return &provider.Response{ + StatusCode: status, + Status: fmt.Sprintf("%d %s", status, http.StatusText(status)), + Header: header, + Body: io.NopCloser(bytes.NewReader(data)), + QuotaUnits: 1, + } +} + +func voiceErrorResponse(err error) (*provider.Response, error) { + if status, ok := provider.ErrorHTTPStatus(err); ok { + message, safe := provider.ErrorPublicMessage(err) + if !safe { + message = "上游语音服务返回错误" + } + response := jsonVoiceResponse(status, map[string]any{"error": map[string]any{"type": "upstream_error", "message": message}}) + if retryAfter := provider.ErrorRetryAfter(err); retryAfter > 0 { + seconds := max(int64(1), int64((retryAfter+time.Second-1)/time.Second)) + response.Header.Set("Retry-After", strconv.FormatInt(seconds, 10)) + } + return response, nil + } + return nil, err +} + +func firstNonEmpty(values ...string) string { + for _, value := range values { + if strings.TrimSpace(value) != "" { + return strings.TrimSpace(value) + } + } + return "" +} diff --git a/backend/internal/application/gateway/voice_ws.go b/backend/internal/application/gateway/voice_ws.go new file mode 100644 index 00000000..ef53a784 --- /dev/null +++ b/backend/internal/application/gateway/voice_ws.go @@ -0,0 +1,310 @@ +package gateway + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "sync" + "time" + + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/domain/audit" + "github.com/chenyme/grok2api/backend/internal/domain/clientkey" + modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" + infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" + "github.com/chenyme/grok2api/backend/internal/infra/provider" +) + +type VoiceWebSocketInput struct { + RequestID string + ClientKey clientkey.Key + PublicModel string + // Path is one of /realtime or /stt. + Path string +} + +type VoiceWebSocketSession struct { + Conn provider.VoiceWebSocketConn + Finalize func(VoiceWebSocketOutcome) + RequestID string + PublicModel string + Provider accountdomain.Provider + AccountID uint64 + AccountName string + Operation audit.Operation + Capability modeldomain.Capability +} + +type VoiceWebSocketOutcome struct { + ErrorCode string + UpstreamFailed bool + AudioDurationSeconds float64 +} + +// OpenVoiceWebSocket selects a Console account and dials the upstream voice websocket. +func (s *Service) OpenVoiceWebSocket(ctx context.Context, input VoiceWebSocketInput) (*VoiceWebSocketSession, error) { + pathValue := strings.TrimSpace(input.Path) + capability, operation, defaultModel, err := voiceWebSocketRoute(pathValue) + if err != nil { + return nil, err + } + publicModel := strings.TrimSpace(input.PublicModel) + if publicModel == "" { + publicModel = defaultModel + } + + ctx, egressTrace := infraegress.WithTrace(ctx) + startedAt := time.Now() + eventID := newAuditEventID() + + routes, err := s.models.GetByPublicIDCandidates(ctx, publicModel) + if err != nil { + return nil, ErrModelNotFound + } + supportsVoiceWebSocket := func(providerValue accountdomain.Provider) bool { + _, ok := s.providers.VoiceWebSocket(providerValue) + return ok + } + route, preselectedSession, err := s.selectSchedulableMediaRoute(ctx, routes, input.ClientKey, capability, true, supportsVoiceWebSocket) + if err != nil { + // Preserve selection-failure audits when every eligible target is cooling + // or exhausted. The regular request loop will reproduce the error. + route, err = s.selectMediaRoute(routes, input.ClientKey, capability, supportsVoiceWebSocket) + if err != nil { + return nil, err + } + preselectedSession = nil + } + externalModel := modeldomain.ExternalPublicID(route.Provider, route.PublicID) + auditBase := audit.Record{ + EventID: eventID, RequestID: input.RequestID, ClientKeyID: input.ClientKey.ID, ClientKeyName: input.ClientKey.Name, + ModelRouteID: route.ID, ModelPublicID: externalModel, ModelUpstreamModel: modeldomain.DisplayUpstreamModel(route.Provider, route.UpstreamModel), + Provider: string(route.Provider), Operation: operation, UsageSource: audit.UsageSourceNone, Streaming: true, + } + if err := s.checkLedgerReady(); err != nil { + return nil, err + } + quotaMode := s.providers.QuotaMode(route.Provider, route.UpstreamModel) + attemptPolicy := newRoutingAttemptPolicy(int(s.maxAttempts.Load())) + excluded := make(map[uint64]bool) + selection := preselectedSession + var lease *accountLease + var credential accountdomain.Credential + var lastCredentialFailure *accountdomain.Credential + var lastErr error + + writeFailureAudit := func(statusCode int, errorCode string, cred *accountdomain.Credential) { + record := auditBase + record.StatusCode = statusCode + record.ErrorCode = errorCode + record.DurationMS = time.Since(startedAt).Milliseconds() + record.CreatedAt = time.Now().UTC() + if cred != nil { + accountID := cred.ID + record.AccountID = &accountID + record.AccountName = cred.Name + } + applyAuditEgress(&record, egressTrace, route.Provider) + persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout) + defer cancel() + if auditErr := s.audits.Create(persistCtx, record); auditErr != nil { + s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", input.RequestID, "error", auditErr) + } + } + + for attempt := 0; attemptPolicy.allows(attempt); attempt++ { + if selection == nil { + selection, err = s.selector.beginSelectionSessionForKey(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, "", excluded, false, input.ClientKey.AccountScope()) + } + if err == nil { + lease, err = selection.Acquire(ctx, excluded, false) + } + if err != nil { + errorCode := "upstream_unavailable" + var selectionFailure *SelectionUnavailableError + if errors.As(err, &selectionFailure) { + errorCode = selectionFailure.Code() + } + writeFailureAudit(http.StatusServiceUnavailable, errorCode, lastCredentialFailure) + return nil, fmt.Errorf("%w: %w", ErrNoAvailableAccount, err) + } + excluded[lease.Credential.ID] = true + credential, err = s.accounts.EnsureCredential(ctx, lease.Credential, false) + if err != nil { + failed := lease.Credential + lastCredentialFailure = &failed + lastErr = err + lease.Release() + continue + } + adapter, ok := s.providers.VoiceWebSocket(route.Provider) + if !ok { + lease.Release() + writeFailureAudit(http.StatusBadGateway, "upstream_unavailable", &credential) + return nil, ErrNoAvailableAccount + } + lease.markSelectorUpstreamStarted() + conn, cleanup, dialErr := adapter.DialVoiceWebSocket(ctx, provider.VoiceWebSocketRequest{ + Credential: credential, + Path: pathValue, + Model: route.UpstreamModel, + }) + if dialErr != nil { + if cleanup != nil { + cleanup() + } + if status, ok := provider.ErrorHTTPStatus(dialErr); ok { + failure := newHTTPUpstreamFailure(status, nil, credential.ID, credential.Name) + failure.RequestScopedForbidden = provider.IsRequestScopedError(dialErr) + failure.RetryAfter = provider.ErrorRetryAfter(dialErr) + failure.Cause = dialErr + lastErr = failure + switch { + case status == http.StatusUnauthorized && credential.AuthType == accountdomain.AuthTypeSSO: + s.markSSOCredentialRejected(ctx, credential, fmt.Sprintf("%s SSO credential rejected", credential.Provider)) + failed := credential + lastCredentialFailure = &failed + lease.Release() + continue + case status == http.StatusForbidden && s.providers.RetryForbiddenAsEgress(credential.Provider) && !failure.RequestScopedForbidden && attempt == 0 && attemptPolicy.hasNext(attempt): + delete(excluded, credential.ID) + if selection != nil { + selection.RetryAccount(credential.ID) + } + lease.Release() + continue + case status == http.StatusPaymentRequired || status == http.StatusTooManyRequests: + if quotaKind, _ := s.providers.QuotaKind(credential.Provider); quotaKind == provider.QuotaRemoteWindow && lease.QuotaMode != "" { + exhausted, reconcileErr := s.accounts.ReconcileRateLimit(ctx, credential.ID, lease.QuotaMode, failure.RetryAfter) + s.selector.MarkQuotaStateChanged(credential.Provider, credential.ID) + if reconcileErr != nil || !exhausted { + s.selector.MarkFailure(ctx, credential, status, failure.RetryAfter) + } + } else { + s.selector.MarkFailure(ctx, credential, status, failure.RetryAfter) + } + if attemptPolicy.hasNext(attempt) { + lease.Release() + continue + } + case status >= http.StatusInternalServerError && attemptPolicy.hasNext(attempt): + lease.Release() + continue + } + lease.Release() + writeFailureAudit(failure.HTTPStatus, failure.AuditCode(), &credential) + return nil, failure + } + + lastErr = dialErr + if isSSOCredentialRejected(dialErr, credential) { + s.markSSOCredentialRejected(ctx, credential, fmt.Sprintf("%s SSO credential rejected", credential.Provider)) + failed := credential + lastCredentialFailure = &failed + lease.Release() + continue + } + failure := newTransportUpstreamFailure(dialErr, credential.ID, credential.Name) + lastErr = failure + if ctx.Err() == nil && isRetryableTransportFailure(credential.Provider, dialErr) && attempt == 0 && attemptPolicy.hasNext(attempt) { + delete(excluded, credential.ID) + if selection != nil { + selection.RetryAccount(credential.ID) + } + lease.Release() + continue + } + lease.Release() + writeFailureAudit(failure.HTTPStatus, failure.AuditCode(), &credential) + return nil, failure + } + + // Keep the account lease until the websocket finishes so scheduling stays consistent. + accountLeaseRef := lease + accountCredential := credential + var finalizeOnce sync.Once + finalize := func(outcome VoiceWebSocketOutcome) { + finalizeOnce.Do(func() { + if cleanup != nil { + cleanup() + } + successful := strings.TrimSpace(outcome.ErrorCode) == "" + accountLeaseRef.completeSelectorObservation(!outcome.UpstreamFailed) + accountLeaseRef.Release() + + budget := newFinalizationBudget(string(operation), string(route.Provider)) + accountID := accountCredential.ID + if successful && quotaMode != "" && quotaMode != "weekly" { + var updated bool + err := budget.run("quota_decrement", finalizationQuotaBudget, func(stageCtx context.Context) error { + var decrementErr error + updated, decrementErr = s.accounts.DecrementQuota(stageCtx, accountID, quotaMode, 1) + return decrementErr + }) + if err != nil { + s.logger.Warn("voice_quota_decrement_failed", "provider", route.Provider, "account_id", accountID, "mode", quotaMode, "units", 1, "error", err) + } else if updated { + s.selector.ConsumeQuota(route.Provider, accountID, quotaMode, 1) + } + } + if successful && quotaMode != "" { + if quotaKind, _ := s.providers.QuotaKind(route.Provider); quotaKind == provider.QuotaRemoteWindow { + s.accounts.QueueQuotaRefresh(accountID, quotaMode) + } + } + + record := auditBase + record.StatusCode, record.ErrorCode = voiceWebSocketAuditOutcome(outcome) + record.DurationMS = time.Since(startedAt).Milliseconds() + record.CreatedAt = time.Now().UTC() + record.AccountID = &accountID + record.AccountName = accountCredential.Name + applyAuditEgress(&record, egressTrace, route.Provider) + if successful && operation == audit.OperationSTT { + if pricing, priced := audit.EstimateOfficialSTTCost(outcome.AudioDurationSeconds, true); priced { + record.EstimatedCostInUSDTicks = pricing.CostInUSDTicks + record.PricingModel = pricing.Model + record.PricingVersion = audit.OfficialPricingAsOf + } + } + if auditErr := budget.run("audit", finalizationAuditBudget, func(stageCtx context.Context) error { + return s.audits.Create(stageCtx, record) + }); auditErr != nil { + s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", input.RequestID, "error", auditErr) + } + }) + } + return &VoiceWebSocketSession{ + Conn: conn, Finalize: finalize, RequestID: input.RequestID, PublicModel: externalModel, + Provider: route.Provider, AccountID: credential.ID, AccountName: credential.Name, + Operation: operation, Capability: capability, + }, nil + } + if lastErr != nil { + return nil, lastErr + } + return nil, ErrNoAvailableAccount +} + +func voiceWebSocketAuditOutcome(outcome VoiceWebSocketOutcome) (int, string) { + errorCode := strings.TrimSpace(outcome.ErrorCode) + if errorCode == "" { + // Audits store the logical request outcome. The transport handshake remains + // HTTP 101, while successful request accounting uses the common 2xx predicate. + return http.StatusOK, "" + } + return http.StatusBadGateway, errorCode +} + +func voiceWebSocketRoute(pathValue string) (modeldomain.Capability, audit.Operation, string, error) { + switch strings.TrimSpace(pathValue) { + case "/realtime": + return modeldomain.CapabilityRealtime, audit.OperationRealtime, "grok-voice-latest", nil + case "/stt": + return modeldomain.CapabilitySTT, audit.OperationSTT, "grok-stt", nil + default: + return "", "", "", errors.New("不支持的 voice websocket path") + } +} diff --git a/backend/internal/application/media/service.go b/backend/internal/application/media/service.go index 3a1b5444..36281b40 100644 --- a/backend/internal/application/media/service.go +++ b/backend/internal/application/media/service.go @@ -28,12 +28,12 @@ var ( ErrActiveVideoSelection = errors.New("排队中或生成中的视频任务不能删除") ErrInvalidFilter = errors.New("媒体筛选条件无效") ErrMediaJobsUnavailable = errors.New("视频任务仓储未配置") - ErrInputImageNotFound = errors.New("临时输入图片不存在或已过期") + ErrInputAssetNotFound = errors.New("临时输入资产不存在或已过期") ErrMediaCapacity = errors.New("媒体存储容量不足") ) -// InputImageTTL 是临时输入的硬保留上限;无论任务状态如何,超过后都可回收。 -const InputImageTTL = 24 * time.Hour +// InputAssetTTL 是临时输入的硬保留上限;无论任务状态如何,超过后都可回收。 +const InputAssetTTL = 24 * time.Hour // Service 负责图片/视频校验、文件落盘和元数据持久化的一致性收口。 type Service struct { @@ -112,7 +112,8 @@ func (s *Service) SaveImage(ctx context.Context, data []byte) (mediadomain.Asset // SaveInputImage 保存不会进入图库、不会公开读取并会自动过期的视频输入图片。 func (s *Service) SaveInputImage(ctx context.Context, data []byte) (mediadomain.Asset, error) { cfg := s.runtimeConfig() - if len(data) == 0 || int64(len(data)) > cfg.MaxImageBytes { + inputLimit := min(cfg.MaxImageBytes, int64(mediadomain.MaxInputAssetBytes)) + if len(data) == 0 || inputLimit <= 0 || int64(len(data)) > inputLimit { return mediadomain.Asset{}, ErrInvalidImage } s.inputSaveMu.Lock() @@ -132,7 +133,7 @@ func (s *Service) SaveInputImage(ctx context.Context, data []byte) (mediadomain. } return mediadomain.Asset{}, ErrMediaCapacity } - expiresAt := time.Now().UTC().Add(InputImageTTL) + expiresAt := time.Now().UTC().Add(InputAssetTTL) return s.saveImage(ctx, data, &expiresAt, mediadomain.InputAssetIDPrefix) } @@ -172,28 +173,28 @@ func (s *Service) saveImage(ctx context.Context, data []byte, expiresAt *time.Ti return asset, nil } -// OpenInputImage 读取未过期的临时输入;它从不通过公开图片路由暴露。 -func (s *Service) OpenInputImage(ctx context.Context, id string) (mediadomain.Asset, io.ReadCloser, error) { +// OpenInputAsset 读取未过期的临时输入;它从不通过公开媒体路由暴露。 +func (s *Service) OpenInputAsset(ctx context.Context, id string) (mediadomain.Asset, io.ReadCloser, error) { id = strings.TrimSpace(id) if !mediadomain.IsInputAssetID(id) { - return mediadomain.Asset{}, nil, ErrInputImageNotFound + return mediadomain.Asset{}, nil, ErrInputAssetNotFound } asset, err := s.assets.GetMediaAsset(ctx, id) if errors.Is(err, repository.ErrNotFound) { - return mediadomain.Asset{}, nil, ErrInputImageNotFound + return mediadomain.Asset{}, nil, ErrInputAssetNotFound } if err != nil { return mediadomain.Asset{}, nil, err } - if asset.Kind != "image" || asset.ExpiresAt == nil { - return mediadomain.Asset{}, nil, ErrInputImageNotFound + if (asset.Kind != "image" && asset.Kind != "video") || asset.ExpiresAt == nil { + return mediadomain.Asset{}, nil, ErrInputAssetNotFound } if !asset.ExpiresAt.After(time.Now().UTC()) { - return mediadomain.Asset{}, nil, ErrInputImageNotFound + return mediadomain.Asset{}, nil, ErrInputAssetNotFound } body, err := s.objects.Open(ctx, asset.StorageKey) if errors.Is(err, os.ErrNotExist) { - return mediadomain.Asset{}, nil, ErrInputImageNotFound + return mediadomain.Asset{}, nil, ErrInputAssetNotFound } if err != nil { return mediadomain.Asset{}, nil, err @@ -201,8 +202,8 @@ func (s *Service) OpenInputImage(ctx context.Context, id string) (mediadomain.As return asset, body, nil } -// ReleaseInputImages 在任务进入终态后立即回收不再被其他活动任务引用的临时输入。 -func (s *Service) ReleaseInputImages(ctx context.Context, references []string) error { +// ReleaseInputAssets 在任务进入终态后立即回收不再被其他活动任务引用的临时输入。 +func (s *Service) ReleaseInputAssets(ctx context.Context, references []string) error { seen := make(map[string]struct{}, len(references)) for _, reference := range references { id, ok := mediadomain.ParseInputReference(reference) @@ -227,7 +228,7 @@ func (s *Service) ReleaseInputImages(ctx context.Context, references []string) e if getErr != nil { return getErr } - if asset.ExpiresAt == nil || asset.Kind != "image" { + if asset.ExpiresAt == nil || (asset.Kind != "image" && asset.Kind != "video") { continue } if deleteErr := s.objects.Delete(ctx, asset.StorageKey); deleteErr != nil && !errors.Is(deleteErr, os.ErrNotExist) { diff --git a/backend/internal/application/media/service_test.go b/backend/internal/application/media/service_test.go index 18081dd8..d3369f47 100644 --- a/backend/internal/application/media/service_test.go +++ b/backend/internal/application/media/service_test.go @@ -98,7 +98,7 @@ func TestTransientInputIsHiddenReadableAndExpires(t *testing.T) { if _, _, openErr := service.OpenImage(ctx, input.ID); !errors.Is(openErr, ErrAssetNotFound) { t.Fatalf("public open error=%v", openErr) } - stored, body, err := service.OpenInputImage(ctx, input.ID) + stored, body, err := service.OpenInputAsset(ctx, input.ID) if err != nil { t.Fatal(err) } @@ -165,10 +165,10 @@ func TestTransientInputIsHiddenReadableAndExpires(t *testing.T) { }); err != nil { t.Fatal(err) } - if _, _, err := service.OpenInputImage(ctx, activeInputID); !errors.Is(err, ErrInputImageNotFound) { + if _, _, err := service.OpenInputAsset(ctx, activeInputID); !errors.Is(err, ErrInputAssetNotFound) { t.Fatalf("open active expired input error=%v", err) } - if err := service.ReleaseInputImages(ctx, []string{mediadomain.InputReference(activeInputID)}); err != nil { + if err := service.ReleaseInputAssets(ctx, []string{mediadomain.InputReference(activeInputID)}); err != nil { t.Fatal(err) } if _, err := assets.GetMediaAsset(ctx, activeInputID); err != nil { @@ -180,7 +180,7 @@ func TestTransientInputIsHiddenReadableAndExpires(t *testing.T) { if _, err := assets.GetMediaAsset(ctx, activeInputID); !errors.Is(err, repository.ErrNotFound) { t.Fatalf("active expired input metadata error=%v", err) } - if err := service.ReleaseInputImages(ctx, []string{mediadomain.InputReference(input.ID)}); err != nil { + if err := service.ReleaseInputAssets(ctx, []string{mediadomain.InputReference(input.ID)}); err != nil { t.Fatal(err) } if _, err := assets.GetMediaAsset(ctx, input.ID); !errors.Is(err, repository.ErrNotFound) { @@ -215,6 +215,18 @@ func TestSaveInputImageReservesCleanupHeadroom(t *testing.T) { } } +func TestSaveInputImageEnforcesSharedInputAssetLimit(t *testing.T) { + service := NewService(nil, nil, nil, nil, Config{ + MaxImageBytes: mediadomain.MaxInputAssetBytes * 2, + MaxTotalBytes: mediadomain.MaxInputAssetBytes * 4, + }) + data := make([]byte, mediadomain.MaxInputAssetBytes+1) + copy(data, []byte("\x89PNG\r\n\x1a\n")) + if _, err := service.SaveInputImage(context.Background(), data); !errors.Is(err, ErrInvalidImage) { + t.Fatalf("SaveInputImage oversized error = %v, want ErrInvalidImage", err) + } +} + func TestAdminDeleteVideoJobsRemovesTerminalJobAssetAndTicket(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "media-video-delete.db")) diff --git a/backend/internal/application/media/upload.go b/backend/internal/application/media/upload.go index 5af476f7..eaca324a 100644 --- a/backend/internal/application/media/upload.go +++ b/backend/internal/application/media/upload.go @@ -198,7 +198,7 @@ func (s *Service) ReceiveVideoUpload(ctx context.Context, rawToken string, conte } }() - asset, err := s.commitStagedVideo(ctx, staged, now) + asset, err := s.commitStagedVideo(ctx, staged, now, nil) if err != nil { return mediadomain.Asset{}, err } @@ -240,7 +240,7 @@ func (s *Service) SaveVideo(ctx context.Context, jobID, contentType string, body return mediadomain.Asset{}, err } defer func() { _ = s.objects.AbortVideoUpload(context.WithoutCancel(ctx), staged.TempPath) }() - asset, err := s.commitStagedVideo(ctx, staged, time.Now().UTC()) + asset, err := s.commitStagedVideo(ctx, staged, time.Now().UTC(), nil) if err == nil { saved = true } @@ -294,13 +294,54 @@ func (s *Service) stageVideo(ctx context.Context, id, mimeType string, body io.R return stagedVideo{ID: id, TempPath: tempPath, StorageKey: storageKey, MIMEType: mimeType, SizeBytes: written, SHA256: hex.EncodeToString(hasher.Sum(nil))}, nil } -func (s *Service) commitStagedVideo(ctx context.Context, staged stagedVideo, createdAt time.Time) (mediadomain.Asset, error) { +// SaveInputVideo stores a private, expiring video input for edit/extension jobs. +func (s *Service) SaveInputVideo(ctx context.Context, contentType string, body io.Reader) (mediadomain.Asset, error) { + mimeType := normalizeVideoMIME(contentType) + if mimeType == "" { + mimeType = "video/mp4" + } + if !supportedVideoMIME(mimeType) { + return mediadomain.Asset{}, fmt.Errorf("%w: Content-Type 无效", ErrInvalidVideoUpload) + } + id, err := newAssetID(mediadomain.InputAssetIDPrefix) + if err != nil { + return mediadomain.Asset{}, err + } + staged, err := s.stageVideo(ctx, id, mimeType, body, mediadomain.MaxInputAssetBytes) + if err != nil { + return mediadomain.Asset{}, err + } + defer func() { _ = s.objects.AbortVideoUpload(context.WithoutCancel(ctx), staged.TempPath) }() + + s.inputSaveMu.Lock() + defer s.inputSaveMu.Unlock() + cfg := s.runtimeConfig() + total, err := s.assets.TotalMediaAssetBytes(ctx) + if err != nil { + return mediadomain.Asset{}, err + } + capacityLimit := cleanupThresholdBytes(cfg) + if capacityLimit <= 0 || capacityLimit > cfg.MaxTotalBytes { + capacityLimit = cfg.MaxTotalBytes + } + if staged.SizeBytes > capacityLimit || total > capacityLimit-staged.SizeBytes { + select { + case s.cleanupSignal <- struct{}{}: + default: + } + return mediadomain.Asset{}, ErrMediaCapacity + } + expiresAt := time.Now().UTC().Add(InputAssetTTL) + return s.commitStagedVideo(ctx, staged, time.Now().UTC(), &expiresAt) +} + +func (s *Service) commitStagedVideo(ctx context.Context, staged stagedVideo, createdAt time.Time, expiresAt *time.Time) (mediadomain.Asset, error) { if err := s.objects.CommitVideoUpload(ctx, staged.TempPath, staged.StorageKey); err != nil { return mediadomain.Asset{}, err } asset := mediadomain.Asset{ ID: staged.ID, Kind: "video", StorageKey: staged.StorageKey, MIMEType: staged.MIMEType, - SizeBytes: staged.SizeBytes, SHA256: staged.SHA256, CreatedAt: createdAt, + SizeBytes: staged.SizeBytes, SHA256: staged.SHA256, ExpiresAt: expiresAt, CreatedAt: createdAt, } if err := s.assets.CreateMediaAsset(ctx, asset); err != nil { _ = s.objects.Delete(context.WithoutCancel(ctx), staged.StorageKey) @@ -324,7 +365,7 @@ func (s *Service) OpenVideo(ctx context.Context, id string) (mediadomain.Asset, if err != nil { return mediadomain.Asset{}, nil, err } - if asset.Kind != "video" { + if asset.Kind != "video" || asset.ExpiresAt != nil { return mediadomain.Asset{}, nil, ErrAssetNotFound } body, err := s.objects.Open(ctx, asset.StorageKey) diff --git a/backend/internal/application/media/upload_test.go b/backend/internal/application/media/upload_test.go index e87aaed7..a68e46f0 100644 --- a/backend/internal/application/media/upload_test.go +++ b/backend/internal/application/media/upload_test.go @@ -96,6 +96,36 @@ func TestSaveVideoArchivesProviderResultWithoutUploadTicket(t *testing.T) { } } +func TestSaveInputVideoIsPrivateExpiringAsset(t *testing.T) { + database, objects, _, cleanup := openUploadTestDeps(t) + defer cleanup() + ctx := context.Background() + service := NewService( + relational.NewMediaAssetRepository(database), relational.NewMediaJobRepository(database), objects, nil, + Config{MaxImageBytes: mediadomain.MaxInputAssetBytes, MaxTotalBytes: 1 << 30, CleanupThresholdPercent: 80, CleanupInterval: time.Minute}, + ) + payload := append([]byte{0x00, 0x00, 0x00, 0x18, 'f', 't', 'y', 'p', 'i', 's', 'o', 'm'}, bytes.Repeat([]byte{0x04}, 64)...) + asset, err := service.SaveInputVideo(ctx, "video/mp4", bytes.NewReader(payload)) + if err != nil { + t.Fatal(err) + } + if !mediadomain.IsInputAssetID(asset.ID) || asset.Kind != "video" || asset.ExpiresAt == nil || !asset.ExpiresAt.After(time.Now().UTC()) { + t.Fatalf("input asset = %#v", asset) + } + stored, body, err := service.OpenInputAsset(ctx, asset.ID) + if err != nil { + t.Fatal(err) + } + defer body.Close() + raw, err := io.ReadAll(body) + if err != nil || !bytes.Equal(raw, payload) || stored.ExpiresAt == nil { + t.Fatalf("stored = %#v size=%d err=%v", stored, len(raw), err) + } + if _, _, err := service.OpenVideo(ctx, asset.ID); !errors.Is(err, ErrAssetNotFound) { + t.Fatalf("temporary video unexpectedly public: %v", err) + } +} + type bindingTicketRepository struct { repository.MediaUploadTicketRepository jobID string diff --git a/backend/internal/application/model/service.go b/backend/internal/application/model/service.go index 79b3b4eb..d9e41a08 100644 --- a/backend/internal/application/model/service.go +++ b/backend/internal/application/model/service.go @@ -153,9 +153,15 @@ func endpointCapabilitiesForDefinition(routes []modeldomain.Route, definition pr available["image_edit"] = definition.Media.ImageEdit case modeldomain.CapabilityVideo: available["video"] = definition.Media.VideoGeneration + case modeldomain.CapabilityTTS: + available["tts"] = definition.Media.TTS + case modeldomain.CapabilitySTT: + available["stt"] = definition.Media.STT + case modeldomain.CapabilityRealtime: + available["realtime"] = definition.Media.Realtime } } - order := []string{"completions", "responses", "messages", "image", "image_edit", "video"} + order := []string{"completions", "responses", "messages", "image", "image_edit", "video", "tts", "stt", "realtime"} result := make([]string, 0, len(order)) for _, capability := range order { if available[capability] { diff --git a/backend/internal/domain/account/account.go b/backend/internal/domain/account/account.go index fda62ff7..57c84e42 100644 --- a/backend/internal/domain/account/account.go +++ b/backend/internal/domain/account/account.go @@ -269,6 +269,27 @@ const ( QuotaSourceUpstream QuotaSource = "upstream" ) +const ( + QuotaModeWebImagePro = "image_pro" + QuotaModeWebImageEdit = "image_edit" + QuotaModeWebVideo = "video" + QuotaModeWebVideo720p = "video_720p" + QuotaGroupWebImagine = "web_imagine" +) + +func WebImagineQuotaModes() []string { + return []string{QuotaModeWebImagePro, QuotaModeWebImageEdit, QuotaModeWebVideo, QuotaModeWebVideo720p} +} + +func IsWebImagineQuotaMode(mode string) bool { + switch mode { + case QuotaModeWebImagePro, QuotaModeWebImageEdit, QuotaModeWebVideo, QuotaModeWebVideo720p: + return true + default: + return false + } +} + // QuotaWindow 表示 Provider 单个模式的额度窗口。 type QuotaWindow struct { AccountID uint64 diff --git a/backend/internal/domain/audit/audit.go b/backend/internal/domain/audit/audit.go index 7d11ac6e..1cbb1a54 100644 --- a/backend/internal/domain/audit/audit.go +++ b/backend/internal/domain/audit/audit.go @@ -12,6 +12,10 @@ const ( OperationImage Operation = "image" OperationImageEdit Operation = "image_edit" OperationVideo Operation = "video" + OperationTTS Operation = "tts" + OperationSTT Operation = "stt" + OperationRealtime Operation = "realtime" + OperationVoice Operation = "voice" ) type UsageSource string diff --git a/backend/internal/domain/audit/pricing.go b/backend/internal/domain/audit/pricing.go index 19226cba..eab3cfcc 100644 --- a/backend/internal/domain/audit/pricing.go +++ b/backend/internal/domain/audit/pricing.go @@ -2,13 +2,48 @@ package audit import ( "encoding/json" + "math" "regexp" "strings" + "unicode/utf8" ) +const officialTTSCharacterTicks int64 = 150_000 + +// EstimateOfficialTTSCost prices unary TTS from the exact Unicode character +// count accepted by the upstream request. xAI publishes $15 per 1M characters. +func EstimateOfficialTTSCost(text string) (PricingResult, bool) { + characters := utf8.RuneCountInString(text) + if characters <= 0 { + return PricingResult{}, false + } + return PricingResult{ + Model: "grok-voice-tts", + CostInUSDTicks: int64(characters) * officialTTSCharacterTicks, + }, true +} + +// EstimateOfficialSTTCost prices a completed STT request from the duration +// reported by xAI. REST costs $0.10/hour and streaming costs $0.20/hour. +func EstimateOfficialSTTCost(durationSeconds float64, streaming bool) (PricingResult, bool) { + if durationSeconds <= 0 || math.IsNaN(durationSeconds) || math.IsInf(durationSeconds, 0) { + return PricingResult{}, false + } + hourlyTicks := int64(1_000_000_000) + model := "grok-stt-rest" + if streaming { + hourlyTicks = 2_000_000_000 + model = "grok-stt-streaming" + } + // Round upward to one USD tick so a positive billable duration never + // disappears through integer truncation. + cost := int64(math.Ceil(durationSeconds * float64(hourlyTicks) / 3600)) + return PricingResult{Model: model, CostInUSDTicks: max(int64(1), cost)}, true +} + const ( OfficialPricingSource = "https://docs.x.ai/developers/pricing" - OfficialPricingAsOf = "2026-07-14" + OfficialPricingAsOf = "2026-08-13" officialImageEditInputTicks int64 = 100_000_000 officialLiteImageInputTicks int64 = 20_000_000 ) @@ -81,6 +116,7 @@ type tokenPriceRule struct { var officialTokenPriceRules = []tokenPriceRule{ {Pattern: regexp.MustCompile(`^grok-(?:build-0\.1|code-fast(?:-1)?|composer-2\.5-fast)(?:-[a-z0-9.]+)*$`), CanonicalModel: "grok-build-0.1"}, + {Pattern: regexp.MustCompile(`^grok-4\.6(?:-[a-z0-9.]+)*$`), CanonicalModel: "grok-4.6"}, {Pattern: regexp.MustCompile(`^grok-4\.5(?:-[a-z0-9.]+)*$`), CanonicalModel: "grok-4.5"}, {Pattern: regexp.MustCompile(`^grok-4\.3(?:-[a-z0-9.]+)*$`), CanonicalModel: "grok-4.3"}, {Pattern: regexp.MustCompile(`^grok-4\.20-multi-agent(?:-[a-z0-9.]+)*$`), CanonicalModel: "grok-4.20-multi-agent-0309"}, @@ -100,6 +136,8 @@ func buildOfficialTokenPrices() map[string]tokenPrice { } register("grok-build-0.1", tokenPrice{InputTicks: 10000, CachedInputTicks: 2000, OutputTicks: 20000, LongContextTokens: 200000, LongInputTicks: 20000, LongCachedTicks: 4000, LongOutputTicks: 40000}, "grok-code-fast-1", "grok-code-fast", "grok-code-fast-1-0825", "grok-composer-2.5-fast") + register("grok-4.6", tokenPrice{InputTicks: 20000, CachedInputTicks: 5000, OutputTicks: 60000, LongContextTokens: 200000, LongInputTicks: 40000, LongCachedTicks: 10000, LongOutputTicks: 120000}, + "grok-4.6-latest") register("grok-4.5", tokenPrice{InputTicks: 20000, CachedInputTicks: 3000, OutputTicks: 60000, LongContextTokens: 200000, LongInputTicks: 40000, LongCachedTicks: 6000, LongOutputTicks: 120000}, "grok-4.5-latest", "grok-build-latest") standard := tokenPrice{InputTicks: 12500, CachedInputTicks: 2000, OutputTicks: 25000, LongContextTokens: 200000, LongInputTicks: 25000, LongCachedTicks: 4000, LongOutputTicks: 50000} @@ -229,15 +267,36 @@ func estimateJSONTokens(value any) int64 { } // EstimateOfficialImageCost 按客户端请求的 n 计算 Grok Imagine 图片费用。 -func EstimateOfficialImageCost(model, resolution string, count int) (PricingResult, bool) { +func EstimateOfficialImageCost(model, resolution, quality string, count int) (PricingResult, bool) { if count <= 0 { return PricingResult{}, false } model = normalizePricingModel(model) + quality = strings.ToLower(strings.TrimSpace(quality)) if model == "grok-imagine-image" { + if quality != "" { + return PricingResult{}, false + } return PricingResult{Model: "grok-imagine-image", CostInUSDTicks: int64(count) * 200_000_000}, true } - if model != "grok-imagine-image-quality" { + if model == "grok-imagine-image-2.0" { + resolution = strings.ToLower(strings.TrimSpace(resolution)) + if resolution == "" { + resolution = "1k" + } + if quality == "" { + quality = "medium" + } + outputTicks, ok := officialImage20OutputTicks(resolution, quality) + if !ok { + return PricingResult{}, false + } + return PricingResult{ + Model: "grok-imagine-image-2.0-" + quality + "-" + resolution, + CostInUSDTicks: int64(count) * outputTicks, + }, true + } + if model != "grok-imagine-image-quality" || quality != "" { return PricingResult{}, false } resolution = strings.ToLower(strings.TrimSpace(resolution)) @@ -260,12 +319,13 @@ func EstimateOfficialImageCost(model, resolution string, count int) (PricingResu } // EstimateOfficialImageEditCost 按输出图片数量计费,并叠加每张输入图片的处理费用。 -func EstimateOfficialImageEditCost(model, resolution string, outputCount, inputCount int) (PricingResult, bool) { +func EstimateOfficialImageEditCost(model, resolution, quality string, outputCount, inputCount int) (PricingResult, bool) { model = normalizePricingModel(model) if outputCount <= 0 || inputCount <= 0 { return PricingResult{}, false } resolution = strings.ToLower(strings.TrimSpace(resolution)) + quality = strings.ToLower(strings.TrimSpace(quality)) if resolution == "" { resolution = "1k" } @@ -274,10 +334,29 @@ func EstimateOfficialImageEditCost(model, resolution string, outputCount, inputC var outputTicks int64 switch model { case "grok-imagine-image-edit": + if quality != "" { + return PricingResult{}, false + } pricingModel = "grok-imagine-image-edit-" + resolution + case "grok-imagine-image-2.0": + if quality == "" { + quality = "medium" + } + var ok bool + outputTicks, ok = officialImage20OutputTicks(resolution, quality) + if !ok { + return PricingResult{}, false + } + pricingModel = "grok-imagine-image-2.0-edit-" + quality + "-" + resolution case "grok-imagine-image-quality": + if quality != "" { + return PricingResult{}, false + } pricingModel = "grok-imagine-image-quality-edit-" + resolution case "grok-imagine-image": + if quality != "" { + return PricingResult{}, false + } pricingModel = "grok-imagine-image-edit-lite-" + resolution inputTicks = officialLiteImageInputTicks outputTicks = 200_000_000 @@ -300,10 +379,23 @@ func EstimateOfficialImageEditCost(model, resolution string, outputCount, inputC }, true } +func officialImage20OutputTicks(resolution, quality string) (int64, bool) { + switch resolution + "/" + quality { + case "1k/low": + return 400_000_000, true + case "2k/low", "1k/medium": + return 600_000_000, true + case "2k/medium": + return 800_000_000, true + default: + return 0, false + } +} + // EstimateOfficialVideoCost 按请求视频时长和分辨率计算费用。 // 仅精确支持 grok-imagine-video 与 grok-imagine-video-1.5(可带来源前缀);未知后缀拒绝。 -func EstimateOfficialVideoCost(model, resolution string, seconds int) (PricingResult, bool) { - if seconds <= 0 { +func EstimateOfficialVideoCost(model, resolution string, seconds, inputImages int) (PricingResult, bool) { + if seconds <= 0 || inputImages < 0 { return PricingResult{}, false } baseModel, ok := officialVideoPricingModel(model) @@ -311,18 +403,34 @@ func EstimateOfficialVideoCost(model, resolution string, seconds int) (PricingRe return PricingResult{}, false } resolution = strings.ToLower(strings.TrimSpace(resolution)) - var ticksPerSecond int64 - switch resolution { - case "480p": - ticksPerSecond = 800_000_000 - case "720p": - ticksPerSecond = 1_400_000_000 - default: - return PricingResult{}, false + var ticksPerSecond, ticksPerInputImage int64 + switch baseModel { + case "grok-imagine-video": + ticksPerInputImage = officialLiteImageInputTicks + switch resolution { + case "480p": + ticksPerSecond = 500_000_000 + case "720p": + ticksPerSecond = 700_000_000 + default: + return PricingResult{}, false + } + case "grok-imagine-video-1.5": + ticksPerInputImage = officialImageEditInputTicks + switch resolution { + case "480p": + ticksPerSecond = 800_000_000 + case "720p": + ticksPerSecond = 1_400_000_000 + case "1080p": + ticksPerSecond = 2_500_000_000 + default: + return PricingResult{}, false + } } return PricingResult{ Model: baseModel + "-" + resolution, - CostInUSDTicks: int64(seconds) * ticksPerSecond, + CostInUSDTicks: int64(seconds)*ticksPerSecond + int64(inputImages)*ticksPerInputImage, }, true } @@ -331,36 +439,80 @@ func ReconstructOfficialCost(model string, inputTokens, cachedInputTokens, outpu normalized := normalizePricingModel(model) switch normalized { case "grok-imagine-image": - return reconstructImageCost(normalized, "", outputImages) + return reconstructImageCost(normalized, "", "", outputImages) + case "grok-imagine-image-2.0": + // Records written before the quality-aware pricing revision stored the + // former flat $0.04 estimate under this identifier. Preserve an exact + // reconstruction for those immutable audit rows. + return reconstructLegacyImage20Cost(normalized, outputImages, 400_000_000) + case "grok-imagine-image-2.0-low-1k": + return reconstructImageCost("grok-imagine-image-2.0", "1k", "low", outputImages) + case "grok-imagine-image-2.0-low-2k": + return reconstructImageCost("grok-imagine-image-2.0", "2k", "low", outputImages) + case "grok-imagine-image-2.0-medium-1k": + return reconstructImageCost("grok-imagine-image-2.0", "1k", "medium", outputImages) + case "grok-imagine-image-2.0-medium-2k": + return reconstructImageCost("grok-imagine-image-2.0", "2k", "medium", outputImages) case "grok-imagine-image-quality-1k": - return reconstructImageCost("grok-imagine-image-quality", "1k", outputImages) + return reconstructImageCost("grok-imagine-image-quality", "1k", "", outputImages) case "grok-imagine-image-quality-2k": - return reconstructImageCost("grok-imagine-image-quality", "2k", outputImages) + return reconstructImageCost("grok-imagine-image-quality", "2k", "", outputImages) case "grok-imagine-image-edit-1k": - return reconstructImageEditCost("grok-imagine-image-edit", "1k", inputImages, outputImages) + return reconstructImageEditCost("grok-imagine-image-edit", "1k", "", inputImages, outputImages) case "grok-imagine-image-edit-2k": - return reconstructImageEditCost("grok-imagine-image-edit", "2k", inputImages, outputImages) + return reconstructImageEditCost("grok-imagine-image-edit", "2k", "", inputImages, outputImages) + case "grok-imagine-image-2.0-edit-low-1k": + return reconstructImageEditCost("grok-imagine-image-2.0", "1k", "low", inputImages, outputImages) + case "grok-imagine-image-2.0-edit-low-2k": + return reconstructImageEditCost("grok-imagine-image-2.0", "2k", "low", inputImages, outputImages) + case "grok-imagine-image-2.0-edit-medium-1k": + return reconstructImageEditCost("grok-imagine-image-2.0", "1k", "medium", inputImages, outputImages) + case "grok-imagine-image-2.0-edit-medium-2k": + return reconstructImageEditCost("grok-imagine-image-2.0", "2k", "medium", inputImages, outputImages) + case "grok-imagine-image-2.0-edit-1k", "grok-imagine-image-2.0-edit-2k": + return reconstructLegacyImage20EditCost(normalized, inputImages, outputImages) case "grok-imagine-image-quality-edit-1k": - return reconstructImageEditCost("grok-imagine-image-quality", "1k", inputImages, outputImages) + return reconstructImageEditCost("grok-imagine-image-quality", "1k", "", inputImages, outputImages) case "grok-imagine-image-quality-edit-2k": - return reconstructImageEditCost("grok-imagine-image-quality", "2k", inputImages, outputImages) + return reconstructImageEditCost("grok-imagine-image-quality", "2k", "", inputImages, outputImages) case "grok-imagine-image-edit-lite-1k": - return reconstructImageEditCost("grok-imagine-image", "1k", inputImages, outputImages) + return reconstructImageEditCost("grok-imagine-image", "1k", "", inputImages, outputImages) case "grok-imagine-image-edit-lite-2k": - return reconstructImageEditCost("grok-imagine-image", "2k", inputImages, outputImages) + return reconstructImageEditCost("grok-imagine-image", "2k", "", inputImages, outputImages) case "grok-imagine-video-480p": - return reconstructVideoCost("grok-imagine-video", "480p", outputSeconds) + return reconstructVideoCost("grok-imagine-video", "480p", inputImages, outputSeconds) case "grok-imagine-video-720p": - return reconstructVideoCost("grok-imagine-video", "720p", outputSeconds) + return reconstructVideoCost("grok-imagine-video", "720p", inputImages, outputSeconds) case "grok-imagine-video-1.5-480p": - return reconstructVideoCost("grok-imagine-video-1.5", "480p", outputSeconds) + return reconstructVideoCost("grok-imagine-video-1.5", "480p", inputImages, outputSeconds) case "grok-imagine-video-1.5-720p": - return reconstructVideoCost("grok-imagine-video-1.5", "720p", outputSeconds) + return reconstructVideoCost("grok-imagine-video-1.5", "720p", inputImages, outputSeconds) + case "grok-imagine-video-1.5-1080p": + return reconstructVideoCost("grok-imagine-video-1.5", "1080p", inputImages, outputSeconds) default: return reconstructTextCost(normalized, inputTokens, cachedInputTokens, outputTokens, contextInputTokens) } } +func reconstructLegacyImage20Cost(model string, outputCount, outputTicks int64) (PricingBreakdown, bool) { + if outputCount <= 0 { + return PricingBreakdown{}, false + } + return newPricingBreakdown(model, PricingTierMedia, + newPricingComponent(PricingComponentOutputImage, PricingUnitImage, outputCount, outputTicks), + ), true +} + +func reconstructLegacyImage20EditCost(model string, inputCount, outputCount int64) (PricingBreakdown, bool) { + if inputCount <= 0 || outputCount <= 0 { + return PricingBreakdown{}, false + } + return newPricingBreakdown(model, PricingTierMedia, + newPricingComponent(PricingComponentOutputImage, PricingUnitImage, outputCount, 400_000_000), + newPricingComponent(PricingComponentInputImage, PricingUnitImage, inputCount, officialImageEditInputTicks), + ), true +} + func reconstructTextCost(model string, inputTokens, cachedInputTokens, outputTokens, contextInputTokens int64) (PricingBreakdown, bool) { price, ok := resolveOfficialTokenPrice(model) if !ok { @@ -384,11 +536,11 @@ func reconstructTextCost(model string, inputTokens, cachedInputTokens, outputTok ), true } -func reconstructImageCost(model, resolution string, count int64) (PricingBreakdown, bool) { +func reconstructImageCost(model, resolution, quality string, count int64) (PricingBreakdown, bool) { if count <= 0 || int64(int(count)) != count { return PricingBreakdown{}, false } - result, ok := EstimateOfficialImageCost(model, resolution, int(count)) + result, ok := EstimateOfficialImageCost(model, resolution, quality, int(count)) if !ok { return PricingBreakdown{}, false } @@ -397,11 +549,11 @@ func reconstructImageCost(model, resolution string, count int64) (PricingBreakdo ), true } -func reconstructImageEditCost(model, resolution string, inputCount, outputCount int64) (PricingBreakdown, bool) { +func reconstructImageEditCost(model, resolution, quality string, inputCount, outputCount int64) (PricingBreakdown, bool) { if inputCount <= 0 || outputCount <= 0 || int64(int(inputCount)) != inputCount || int64(int(outputCount)) != outputCount { return PricingBreakdown{}, false } - result, ok := EstimateOfficialImageEditCost(model, resolution, int(outputCount), int(inputCount)) + result, ok := EstimateOfficialImageEditCost(model, resolution, quality, int(outputCount), int(inputCount)) if !ok { return PricingBreakdown{}, false } @@ -419,16 +571,25 @@ func reconstructImageEditCost(model, resolution string, inputCount, outputCount ), true } -func reconstructVideoCost(model, resolution string, seconds int64) (PricingBreakdown, bool) { - if seconds <= 0 || int64(int(seconds)) != seconds { +func reconstructVideoCost(model, resolution string, inputImages, seconds int64) (PricingBreakdown, bool) { + if seconds <= 0 || inputImages < 0 || int64(int(seconds)) != seconds || int64(int(inputImages)) != inputImages { return PricingBreakdown{}, false } - result, ok := EstimateOfficialVideoCost(model, resolution, int(seconds)) + result, ok := EstimateOfficialVideoCost(model, resolution, int(seconds), int(inputImages)) if !ok { return PricingBreakdown{}, false } + inputTicks := officialLiteImageInputTicks + if normalizePricingModel(model) == "grok-imagine-video-1.5" { + inputTicks = officialImageEditInputTicks + } + outputCost := result.CostInUSDTicks - inputImages*inputTicks + if outputCost < 0 || outputCost%seconds != 0 { + return PricingBreakdown{}, false + } return newPricingBreakdown(result.Model, PricingTierMedia, - newPricingComponent(PricingComponentOutputSecond, PricingUnitSecond, seconds, result.CostInUSDTicks/seconds), + newPricingComponent(PricingComponentOutputSecond, PricingUnitSecond, seconds, outputCost/seconds), + newPricingComponent(PricingComponentInputImage, PricingUnitImage, inputImages, inputTicks), ), true } diff --git a/backend/internal/domain/audit/pricing_test.go b/backend/internal/domain/audit/pricing_test.go index a5440bbd..9706f346 100644 --- a/backend/internal/domain/audit/pricing_test.go +++ b/backend/internal/domain/audit/pricing_test.go @@ -27,6 +27,7 @@ func TestEstimateOfficialCostMatchesControlledModelFamilies(t *testing.T) { canonical string }{ {model: "Build/grok-build-0.1", canonical: "grok-build-0.1"}, + {model: "Console/grok-4.6-latest", canonical: "grok-4.6"}, {model: "grok_build/grok-code-fast-1-0825", canonical: "grok-build-0.1"}, {model: "Console/grok-4.3-high", canonical: "grok-4.3"}, {model: "Web/grok-4.5-2026-07-14", canonical: "grok-4.5"}, @@ -53,6 +54,7 @@ func TestOfficialPricingMatchesPublishedTokenRates(t *testing.T) { inputCost, cachedCost, outputCost int64 }{ {model: "grok-build-0.1", inputCost: 10_000_000_000, cachedCost: 2_000_000_000, outputCost: 20_000_000_000}, + {model: "grok-4.6", inputCost: 20_000_000_000, cachedCost: 5_000_000_000, outputCost: 60_000_000_000}, {model: "grok-4.5", inputCost: 20_000_000_000, cachedCost: 3_000_000_000, outputCost: 60_000_000_000}, {model: "grok-4.3", inputCost: 12_500_000_000, cachedCost: 2_000_000_000, outputCost: 25_000_000_000}, {model: "grok-4.20-multi-agent-0309", inputCost: 12_500_000_000, cachedCost: 2_000_000_000, outputCost: 25_000_000_000}, @@ -74,13 +76,13 @@ func TestOfficialPricingMatchesPublishedTokenRates(t *testing.T) { } func TestMediaPricingAcceptsProviderPrefixes(t *testing.T) { - if result, ok := EstimateOfficialImageCost("Web/grok-imagine-image", "1k", 1); !ok || result.CostInUSDTicks != 200_000_000 { + if result, ok := EstimateOfficialImageCost("Web/grok-imagine-image", "1k", "", 1); !ok || result.CostInUSDTicks != 200_000_000 { t.Fatalf("prefixed image price = %#v, %v", result, ok) } - if result, ok := EstimateOfficialImageEditCost("grok_web/grok-imagine-image-edit", "1k", 1, 1); !ok || result.CostInUSDTicks != 600_000_000 { + if result, ok := EstimateOfficialImageEditCost("grok_web/grok-imagine-image-edit", "1k", "", 1, 1); !ok || result.CostInUSDTicks != 600_000_000 { t.Fatalf("prefixed image edit price = %#v, %v", result, ok) } - if result, ok := EstimateOfficialVideoCost("Web/grok-imagine-video", "480p", 1); !ok || result.CostInUSDTicks != 800_000_000 { + if result, ok := EstimateOfficialVideoCost("Web/grok-imagine-video", "480p", 1, 0); !ok || result.CostInUSDTicks != 500_000_000 { t.Fatalf("prefixed video price = %#v, %v", result, ok) } } @@ -100,71 +102,124 @@ func TestEstimateOfficialTextReservationUsesOutputLimitAndIgnoresInlineMediaByte } func TestEstimateOfficialImageCost(t *testing.T) { - result, ok := EstimateOfficialImageCost("grok-imagine-image-quality", "1k", 2) + result, ok := EstimateOfficialImageCost("grok-imagine-image-quality", "1k", "", 2) if !ok || result.Model != "grok-imagine-image-quality-1k" || result.CostInUSDTicks != 1_000_000_000 { t.Fatalf("1k result = %#v, ok = %v", result, ok) } - result, ok = EstimateOfficialImageCost("grok-imagine-image-quality", "2k", 3) + result, ok = EstimateOfficialImageCost("grok-imagine-image-quality", "2k", "", 3) if !ok || result.Model != "grok-imagine-image-quality-2k" || result.CostInUSDTicks != 2_100_000_000 { t.Fatalf("2k result = %#v, ok = %v", result, ok) } - result, ok = EstimateOfficialImageCost("grok-imagine-image", "2k", 4) + result, ok = EstimateOfficialImageCost("grok-imagine-image", "2k", "", 4) if !ok || result.Model != "grok-imagine-image" || result.CostInUSDTicks != 800_000_000 { t.Fatalf("Lite result = %#v, ok = %v", result, ok) } + result, ok = EstimateOfficialImageCost("Console/grok-imagine-image-2.0", "2k", "", 2) + if !ok || result.Model != "grok-imagine-image-2.0-medium-2k" || result.CostInUSDTicks != 1_600_000_000 { + t.Fatalf("2.0 default-medium result = %#v, ok = %v", result, ok) + } + result, ok = EstimateOfficialImageCost("Console/grok-imagine-image-2.0", "2k", "low", 2) + if !ok || result.Model != "grok-imagine-image-2.0-low-2k" || result.CostInUSDTicks != 1_200_000_000 { + t.Fatalf("2.0 low result = %#v, ok = %v", result, ok) + } +} + +func TestImage20PricingMatchesPublishedResolutionAndQualityRates(t *testing.T) { + tests := []struct { + resolution string + quality string + wantTicks int64 + }{ + {resolution: "1k", quality: "low", wantTicks: 400_000_000}, + {resolution: "2k", quality: "low", wantTicks: 600_000_000}, + {resolution: "1k", quality: "medium", wantTicks: 600_000_000}, + {resolution: "2k", quality: "medium", wantTicks: 800_000_000}, + } + for _, test := range tests { + result, ok := EstimateOfficialImageCost("grok-imagine-image-2.0", test.resolution, test.quality, 1) + if !ok || result.CostInUSDTicks != test.wantTicks { + t.Fatalf("Image 2.0 %s/%s = %#v, ok=%v", test.resolution, test.quality, result, ok) + } + } + if _, ok := EstimateOfficialImageCost("grok-imagine-image-2.0", "1k", "high", 1); ok { + t.Fatal("unsupported Image 2.0 quality was priced") + } } func TestEstimateOfficialImageEditCost(t *testing.T) { - result, ok := EstimateOfficialImageEditCost("grok-imagine-image-edit", "1k", 2, 1) + result, ok := EstimateOfficialImageEditCost("grok-imagine-image-edit", "1k", "", 2, 1) if !ok || result.Model != "grok-imagine-image-edit-1k" || result.CostInUSDTicks != 1_100_000_000 { t.Fatalf("1k edit result = %#v, ok = %v", result, ok) } - result, ok = EstimateOfficialImageEditCost("grok-imagine-image-edit", "2K", 3, 4) + result, ok = EstimateOfficialImageEditCost("grok-imagine-image-edit", "2K", "", 3, 4) if !ok || result.Model != "grok-imagine-image-edit-2k" || result.CostInUSDTicks != 2_500_000_000 { t.Fatalf("2k edit result = %#v, ok = %v", result, ok) } - if result, ok = EstimateOfficialImageEditCost("grok-imagine-image-edit", "4k", 1, 1); ok || result.CostInUSDTicks != 0 { + if result, ok = EstimateOfficialImageEditCost("grok-imagine-image-edit", "4k", "", 1, 1); ok || result.CostInUSDTicks != 0 { t.Fatalf("unknown edit resolution = %#v, ok = %v", result, ok) } - result, ok = EstimateOfficialImageEditCost("Console/grok-imagine-image-quality", "2k", 1, 2) + result, ok = EstimateOfficialImageEditCost("Console/grok-imagine-image-quality", "2k", "", 1, 2) if !ok || result.Model != "grok-imagine-image-quality-edit-2k" || result.CostInUSDTicks != 900_000_000 { t.Fatalf("Console quality edit price = %#v, ok = %v", result, ok) } - result, ok = EstimateOfficialImageEditCost("Console/grok-imagine-image", "1k", 1, 2) + result, ok = EstimateOfficialImageEditCost("Console/grok-imagine-image", "1k", "", 1, 2) if !ok || result.Model != "grok-imagine-image-edit-lite-1k" || result.CostInUSDTicks != 240_000_000 { t.Fatalf("Console lite edit price = %#v, ok = %v", result, ok) } + result, ok = EstimateOfficialImageEditCost("Console/grok-imagine-image-2.0", "2k", "medium", 2, 1) + if !ok || result.Model != "grok-imagine-image-2.0-edit-medium-2k" || result.CostInUSDTicks != 1_700_000_000 { + t.Fatalf("Console 2.0 edit price = %#v, ok = %v", result, ok) + } } func TestEstimateOfficialVideoCost(t *testing.T) { - result, ok := EstimateOfficialVideoCost("grok-imagine-video", "480p", 10) - if !ok || result.Model != "grok-imagine-video-480p" || result.CostInUSDTicks != 8_000_000_000 { + result, ok := EstimateOfficialVideoCost("grok-imagine-video", "480p", 10, 0) + if !ok || result.Model != "grok-imagine-video-480p" || result.CostInUSDTicks != 5_000_000_000 { t.Fatalf("480p video result = %#v, ok = %v", result, ok) } - result, ok = EstimateOfficialVideoCost("grok-imagine-video", "720P", 6) - if !ok || result.Model != "grok-imagine-video-720p" || result.CostInUSDTicks != 8_400_000_000 { + result, ok = EstimateOfficialVideoCost("grok-imagine-video", "720P", 6, 2) + if !ok || result.Model != "grok-imagine-video-720p" || result.CostInUSDTicks != 4_240_000_000 { t.Fatalf("720p video result = %#v, ok = %v", result, ok) } - if result, ok = EstimateOfficialVideoCost("grok-imagine-video", "1080p", 10); ok || result.CostInUSDTicks != 0 { + if result, ok = EstimateOfficialVideoCost("grok-imagine-video", "1080p", 10, 0); ok || result.CostInUSDTicks != 0 { t.Fatalf("unpriced video resolution = %#v, ok = %v", result, ok) } - result, ok = EstimateOfficialVideoCost("grok-imagine-video-1.5", "720p", 6) + result, ok = EstimateOfficialVideoCost("grok-imagine-video-1.5", "720p", 6, 0) if !ok || result.Model != "grok-imagine-video-1.5-720p" || result.CostInUSDTicks != 8_400_000_000 { t.Fatalf("1.5 720p video result = %#v, ok = %v", result, ok) } - result, ok = EstimateOfficialVideoCost("Build/grok-imagine-video-1.5", "480p", 1) - if !ok || result.Model != "grok-imagine-video-1.5-480p" || result.CostInUSDTicks != 800_000_000 { + result, ok = EstimateOfficialVideoCost("Build/grok-imagine-video-1.5", "480p", 1, 1) + if !ok || result.Model != "grok-imagine-video-1.5-480p" || result.CostInUSDTicks != 900_000_000 { t.Fatalf("prefixed 1.5 video result = %#v, ok = %v", result, ok) } - if result, ok = EstimateOfficialVideoCost("grok-imagine-video-1.5-fast", "720p", 6); ok || result.CostInUSDTicks != 0 { + result, ok = EstimateOfficialVideoCost("grok-imagine-video-1.5", "1080p", 6, 0) + if !ok || result.Model != "grok-imagine-video-1.5-1080p" || result.CostInUSDTicks != 15_000_000_000 { + t.Fatalf("1.5 1080p video result = %#v, ok = %v", result, ok) + } + if result, ok = EstimateOfficialVideoCost("grok-imagine-video-1.5-fast", "720p", 6, 0); ok || result.CostInUSDTicks != 0 { t.Fatalf("unknown 1.5 suffix was priced = %#v, ok = %v", result, ok) } - if result, ok = EstimateOfficialVideoCost("grok-imagine-video-2.0", "720p", 6); ok || result.CostInUSDTicks != 0 { + if result, ok = EstimateOfficialVideoCost("grok-imagine-video-2.0", "720p", 6, 0); ok || result.CostInUSDTicks != 0 { t.Fatalf("unknown video model was priced = %#v, ok = %v", result, ok) } } +func TestEstimateOfficialVoiceCosts(t *testing.T) { + if result, ok := EstimateOfficialTTSCost("Hello 世界"); !ok || result.Model != "grok-voice-tts" || result.CostInUSDTicks != 8*150_000 { + t.Fatalf("tts pricing = %#v, ok=%v", result, ok) + } + if result, ok := EstimateOfficialSTTCost(3600, false); !ok || result.Model != "grok-stt-rest" || result.CostInUSDTicks != 1_000_000_000 { + t.Fatalf("rest stt pricing = %#v, ok=%v", result, ok) + } + if result, ok := EstimateOfficialSTTCost(3.45, true); !ok || result.Model != "grok-stt-streaming" || result.CostInUSDTicks != 1_916_667 { + t.Fatalf("streaming stt pricing = %#v, ok=%v", result, ok) + } + if _, ok := EstimateOfficialSTTCost(0, false); ok { + t.Fatal("zero-duration STT must remain unpriced") + } +} + func TestReconstructOfficialCostReturnsExactStoredFormulaInputs(t *testing.T) { textResult, ok := ReconstructOfficialCost("grok-build-0.1", 100, 20, 50, 100, 0, 0, 0) if !ok || textResult.Tier != PricingTierStandard || textResult.CostInUSDTicks != 1_840_000 || len(textResult.Components) != 3 { @@ -179,7 +234,11 @@ func TestReconstructOfficialCostReturnsExactStoredFormulaInputs(t *testing.T) { t.Fatalf("image reconstruction = %#v, %v", imageResult, ok) } videoResult, ok := ReconstructOfficialCost("grok-imagine-video-1.5-720p", 0, 0, 0, 0, 1, 0, 6) - if !ok || videoResult.CostInUSDTicks != 8_400_000_000 || videoResult.Components[0].Unit != PricingUnitSecond { + if !ok || videoResult.CostInUSDTicks != 8_500_000_000 || len(videoResult.Components) != 2 || videoResult.Components[0].Unit != PricingUnitSecond || videoResult.Components[1].Kind != PricingComponentInputImage { t.Fatalf("video reconstruction = %#v, %v", videoResult, ok) } + legacyImage20, ok := ReconstructOfficialCost("grok-imagine-image-2.0", 0, 0, 0, 0, 0, 2, 0) + if !ok || legacyImage20.CostInUSDTicks != 800_000_000 { + t.Fatalf("legacy Image 2.0 reconstruction = %#v, %v", legacyImage20, ok) + } } diff --git a/backend/internal/domain/egress/egress.go b/backend/internal/domain/egress/egress.go index c17a1d8d..b704cafe 100644 --- a/backend/internal/domain/egress/egress.go +++ b/backend/internal/domain/egress/egress.go @@ -131,6 +131,7 @@ type SubscriptionSource struct { Scope Scope Enabled bool EncryptedURL string + EncryptedProxyURL string RefreshIntervalSeconds int DefaultAccountCapacity int LastSyncedAt *time.Time @@ -147,6 +148,7 @@ type PublicSubscriptionSource struct { Scope Scope Enabled bool URLConfigured bool + ProxyConfigured bool RefreshIntervalSeconds int DefaultAccountCapacity int LastSyncedAt *time.Time @@ -218,11 +220,8 @@ type OperationsConfig struct { AutoAssignEnabled bool AutoBalanceEnabled bool AssignmentIntervalSeconds int - // EncryptedSubscriptionProxyURL is the optional proxy used only when - // fetching remote proxy subscription sources. It is write-only at rest. - EncryptedSubscriptionProxyURL string - Fallbacks map[Scope]FallbackConfig - UpdatedAt time.Time + Fallbacks map[Scope]FallbackConfig + UpdatedAt time.Time } func DefaultOperationsConfig() OperationsConfig { diff --git a/backend/internal/domain/media/asset.go b/backend/internal/domain/media/asset.go index 7739b114..14ee2d7d 100644 --- a/backend/internal/domain/media/asset.go +++ b/backend/internal/domain/media/asset.go @@ -7,7 +7,7 @@ import ( ) const ( - // InputAssetIDPrefix 标识不会公开展示、带生命周期的视频输入资产。 + // InputAssetIDPrefix 标识不会公开展示、带生命周期的视频任务输入资产。 InputAssetIDPrefix = "input_" // InputReferencePrefix 标识 media_jobs.input_json 中的本地临时输入引用。 InputReferencePrefix = "grok2api-input:" diff --git a/backend/internal/domain/media/job.go b/backend/internal/domain/media/job.go index 0d1b8591..afcbbea3 100644 --- a/backend/internal/domain/media/job.go +++ b/backend/internal/domain/media/job.go @@ -18,6 +18,17 @@ const MaxInputJSONBytes = 32 << 20 // MaxInputImages is the maximum number of reference images accepted for a video job. const MaxInputImages = 8 +// MaxInputAssetBytes limits each temporary image or video input to 20 MiB. +const MaxInputAssetBytes = 20 << 20 + +type VideoOperation string + +const ( + VideoOperationGenerate VideoOperation = "generate" + VideoOperationEdit VideoOperation = "edit" + VideoOperationExtend VideoOperation = "extend" +) + // Job 表示可跨进程重启恢复的异步视频任务。 type Job struct { ID string @@ -34,6 +45,7 @@ type Job struct { Model string ModelRouteID uint64 UpstreamModel string + Operation VideoOperation Prompt string Seconds int Size string diff --git a/backend/internal/domain/model/model.go b/backend/internal/domain/model/model.go index 684d5b98..3eb4fa36 100644 --- a/backend/internal/domain/model/model.go +++ b/backend/internal/domain/model/model.go @@ -22,6 +22,9 @@ const ( CapabilityImage Capability = "image" CapabilityImageEdit Capability = "image_edit" CapabilityVideo Capability = "video" + CapabilityTTS Capability = "tts" + CapabilitySTT Capability = "stt" + CapabilityRealtime Capability = "realtime" ) // Capabilities returns every persisted route capability. Callers use this as @@ -33,6 +36,9 @@ func Capabilities() []Capability { CapabilityImage, CapabilityImageEdit, CapabilityVideo, + CapabilityTTS, + CapabilitySTT, + CapabilityRealtime, } } diff --git a/backend/internal/infra/egress/buildclient.go b/backend/internal/infra/egress/buildclient.go index 196639ca..d01a5b1d 100644 --- a/backend/internal/infra/egress/buildclient.go +++ b/backend/internal/infra/egress/buildclient.go @@ -10,6 +10,7 @@ import ( "time" _ "github.com/bdandy/go-socks4" + "github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy" xproxy "golang.org/x/net/proxy" ) @@ -58,6 +59,12 @@ func newBuildClientWithOptions(proxyURL string, responseHeaderTimeout time.Durat return nil, fmt.Errorf("创建 Grok Build SOCKS 代理: %w", err) } transport.DialContext = dialContext(dialer) + case "trojan", "vless", "ss", "vmess": + dialer, err := tunnelproxy.NewDialer(proxyURL) + if err != nil { + return nil, fmt.Errorf("创建 Grok Build 隧道代理: %w", err) + } + transport.DialContext = dialer.DialContext default: return nil, fmt.Errorf("Grok Build 不支持代理协议 %q", parsed.Scheme) } diff --git a/backend/internal/infra/egress/buildclient_test.go b/backend/internal/infra/egress/buildclient_test.go index 1afe1b70..a0ceaec6 100644 --- a/backend/internal/infra/egress/buildclient_test.go +++ b/backend/internal/infra/egress/buildclient_test.go @@ -1,6 +1,7 @@ package egress import ( + "encoding/base64" "encoding/binary" "fmt" "io" @@ -11,6 +12,7 @@ import ( "testing" "time" + application "github.com/chenyme/grok2api/backend/internal/application/egress" neterrorpkg "github.com/chenyme/grok2api/backend/internal/pkg/neterror" ) @@ -123,6 +125,39 @@ func TestNewBuildClientRejectsUnsupportedProxyScheme(t *testing.T) { } } +func TestValidatedProxySchemesCreateBuildAndBrowserClients(t *testing.T) { + vmess := "vmess://" + base64.RawStdEncoding.EncodeToString([]byte(`{"v":"2","add":"proxy.example","port":"443","id":"123e4567-e89b-12d3-a456-426614174000","aid":"0","scy":"auto","net":"tcp"}`)) + for _, raw := range []string{ + "http://user:password@127.0.0.1:8080", + "https://proxy.example:8443", + "socks4://127.0.0.1:1080", + "socks4a://proxy.example:1080", + "socks5://user:password@127.0.0.1:1080", + "socks5h://user:password@proxy.example:1080", + "trojan://password@proxy.example:443?security=tls&sni=edge.example", + "vless://123e4567-e89b-12d3-a456-426614174000@proxy.example:443?encryption=none&security=tls&sni=edge.example", + "ss://YWVzLTEyOC1nY206c2VjcmV0@proxy.example:8388", + vmess, + } { + t.Run(raw, func(t *testing.T) { + normalized, err := application.NormalizeProxyURL(raw) + if err != nil { + t.Fatal(err) + } + build, err := newBuildClient(normalized, 5*time.Minute) + if err != nil { + t.Fatalf("build client: %v", err) + } + build.CloseIdleConnections() + browser, err := newBrowserClient(normalized, DefaultUserAgent) + if err != nil { + t.Fatalf("browser client: %v", err) + } + browser.CloseIdleConnections() + }) + } +} + func TestBuildClientRoutesThroughSOCKS5HWithRemoteDNS(t *testing.T) { target := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { if request.Header.Get("User-Agent") != "grok-shell/0.2.102 (linux; x86_64)" { diff --git a/backend/internal/infra/egress/flaresolverr.go b/backend/internal/infra/egress/flaresolverr.go index a76ec42b..9e94426e 100644 --- a/backend/internal/infra/egress/flaresolverr.go +++ b/backend/internal/infra/egress/flaresolverr.go @@ -14,12 +14,14 @@ import ( "time" application "github.com/chenyme/grok2api/backend/internal/application/egress" + "github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy" ) const maxFlareSolverrResponseBytes = 2 << 20 var ( proxyCredentialPattern = regexp.MustCompile(`(?i)\b(https?|socks4a?|socks5h?)://[^\s/@:]+:[^\s/@]+@`) + tunnelCredentialPattern = regexp.MustCompile(`(?i)\b(?:trojan|vless)://[^\s/@]+@|\b(?:ss|vmess)://[^\s,;]+`) bearerCredentialPattern = regexp.MustCompile(`(?i)\bbearer\s+[a-z0-9._~+/=-]+`) namedCredentialPattern = regexp.MustCompile(`(?i)\b(token|password|passwd|authorization|cookie)\s*[:=]\s*[^\s,;]+`) ) @@ -44,6 +46,9 @@ type clearanceSolver interface { type flaresolverrSolver struct{} func (flaresolverrSolver) Solve(ctx context.Context, cfg ClearanceConfig, proxyURL string) (clearanceSolution, error) { + if parsedProxy, parseErr := url.Parse(proxyURL); parseErr == nil && tunnelproxy.IsSupportedScheme(parsedProxy.Scheme) { + return clearanceSolution{}, errors.New("FlareSolverr 暂不支持 Trojan、VLESS、SS 或 VMess 隧道代理") + } endpoint, err := flaresolverrEndpoint(cfg.FlareSolverrURL) if err != nil { return clearanceSolution{}, err @@ -139,6 +144,7 @@ func sanitizeFlareSolverrMessage(value string) string { } return candidate[:separator+3] + "***:***@" }) + value = tunnelCredentialPattern.ReplaceAllString(value, "[redacted tunnel proxy]") value = bearerCredentialPattern.ReplaceAllString(value, "Bearer [redacted]") value = namedCredentialPattern.ReplaceAllString(value, "$1=[redacted]") characters := []rune(value) diff --git a/backend/internal/infra/egress/flaresolverr_test.go b/backend/internal/infra/egress/flaresolverr_test.go index e067e943..e41062d8 100644 --- a/backend/internal/infra/egress/flaresolverr_test.go +++ b/backend/internal/infra/egress/flaresolverr_test.go @@ -60,6 +60,13 @@ func TestFlareSolverrSolveAcceptsNoChallengeWithoutCloudflareCookies(t *testing. } } +func TestFlareSolverrSolveRejectsTunnelProxy(t *testing.T) { + _, err := (flaresolverrSolver{}).Solve(context.Background(), ClearanceConfig{}, "trojan://secret@proxy.example:443") + if err == nil || !strings.Contains(err.Error(), "FlareSolverr") { + t.Fatalf("tunnel proxy error = %v", err) + } +} + func TestFlareSolverrEndpointAcceptsBaseAndV1Path(t *testing.T) { for input, expected := range map[string]string{ "http://flaresolverr:8191": "http://flaresolverr:8191/v1", @@ -74,8 +81,8 @@ func TestFlareSolverrEndpointAcceptsBaseAndV1Path(t *testing.T) { } func TestSanitizeFlareSolverrMessageRedactsCredentials(t *testing.T) { - message := sanitizeFlareSolverrMessage("proxy socks5h://user:secret@resin:2260 failed; token=abc123 Authorization: Bearer.SECRET cookie=sso-value") - for _, secret := range []string{"user", "secret", "abc123", "Bearer.SECRET", "sso-value"} { + message := sanitizeFlareSolverrMessage("proxy socks5h://user:secret@resin:2260 and trojan://tunnel-secret@proxy.example:443 and vmess://base64-secret failed; token=abc123 Authorization: Bearer.SECRET cookie=sso-value") + for _, secret := range []string{"user", "secret", "tunnel-secret", "base64-secret", "abc123", "Bearer.SECRET", "sso-value"} { if strings.Contains(message, secret) { t.Fatalf("sanitized message leaked %q: %q", secret, message) } diff --git a/backend/internal/infra/egress/pinnedclient.go b/backend/internal/infra/egress/pinnedclient.go index 11fa8328..996cc518 100644 --- a/backend/internal/infra/egress/pinnedclient.go +++ b/backend/internal/infra/egress/pinnedclient.go @@ -11,6 +11,7 @@ import ( "strings" "time" + "github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy" xproxy "golang.org/x/net/proxy" ) @@ -81,6 +82,12 @@ func newPinnedHTTPSClient(proxyURL, serverName string, tlsConfig *tls.Config) (* return nil, fmt.Errorf("创建固定地址 SOCKS 代理: %w", err) } transport.DialContext = dialContext(dialer) + case "trojan", "vless", "ss", "vmess": + dialer, err := tunnelproxy.NewDialer(proxyURL) + if err != nil { + return nil, fmt.Errorf("创建固定地址隧道代理: %w", err) + } + transport.DialContext = dialer.DialContext default: return nil, fmt.Errorf("固定地址请求不支持代理协议 %q", parsed.Scheme) } diff --git a/backend/internal/infra/egress/tlsclient.go b/backend/internal/infra/egress/tlsclient.go index 4b9d2b2a..52b4d425 100644 --- a/backend/internal/infra/egress/tlsclient.go +++ b/backend/internal/infra/egress/tlsclient.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "net/http" + "net/url" "regexp" "strconv" "strings" @@ -15,6 +16,7 @@ import ( tlsclient "github.com/bogdanfinn/tls-client" "github.com/bogdanfinn/tls-client/profiles" "github.com/bogdanfinn/websocket" + "github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy" ) type browserClient struct{ inner tlsclient.HttpClient } @@ -62,7 +64,19 @@ func newBrowserClient(proxyURL, userAgent string) (*browserClient, error) { tlsclient.WithNotFollowRedirects(), } if proxyURL != "" { - options = append(options, tlsclient.WithProxyUrl(proxyURL)) + parsed, err := url.Parse(proxyURL) + if err != nil { + return nil, fmt.Errorf("解析浏览器出口代理: %w", err) + } + if tunnelproxy.IsSupportedScheme(parsed.Scheme) { + dialer, err := tunnelproxy.NewDialer(proxyURL) + if err != nil { + return nil, fmt.Errorf("创建浏览器隧道代理: %w", err) + } + options = append(options, tlsclient.WithDialContext(dialer.DialContext)) + } else { + options = append(options, tlsclient.WithProxyUrl(proxyURL)) + } } client, err := tlsclient.NewHttpClient(tlsclient.NewNoopLogger(), options...) if err != nil { diff --git a/backend/internal/infra/persistence/relational/account_repository.go b/backend/internal/infra/persistence/relational/account_repository.go index f216af86..81491d6c 100644 --- a/backend/internal/infra/persistence/relational/account_repository.go +++ b/backend/internal/infra/persistence/relational/account_repository.go @@ -642,7 +642,10 @@ func (r *AccountRepository) getRoutingQuotaWindows(ctx context.Context, provider return result, nil } modes := make([]string, 0, 2) - if provider == account.ProviderWeb { + // Paid Web chat routes are governed by the shared weekly pool. Imagine + // products have independent authoritative windows and must not be hidden by + // a weekly row merely because the same account also has paid chat access. + if provider == account.ProviderWeb && !account.IsWebImagineQuotaMode(quotaMode) { modes = append(modes, "weekly") } if quotaMode != "" { @@ -2305,7 +2308,7 @@ func (r *AccountRepository) GetQuotaWindows(ctx context.Context, accountIDs []ui } func (r *AccountRepository) SaveQuotaWindows(ctx context.Context, accountID uint64, tier account.WebTier, syncedAt time.Time, values []account.QuotaWindow) error { - err := r.saveQuotaWindows(ctx, accountID, tier, syncedAt, values, false) + err := r.saveQuotaWindows(ctx, accountID, tier, syncedAt, values, false, nil) if err == nil { r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountQuotaChanged, AccountID: accountID}) } @@ -2313,14 +2316,48 @@ func (r *AccountRepository) SaveQuotaWindows(ctx context.Context, accountID uint } func (r *AccountRepository) ReplaceQuotaWindows(ctx context.Context, accountID uint64, tier account.WebTier, syncedAt time.Time, values []account.QuotaWindow) error { - err := r.saveQuotaWindows(ctx, accountID, tier, syncedAt, values, true) + err := r.saveQuotaWindows(ctx, accountID, tier, syncedAt, values, true, nil) if err == nil { r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountQuotaChanged, AccountID: accountID}) } return err } -func (r *AccountRepository) saveQuotaWindows(ctx context.Context, accountID uint64, tier account.WebTier, syncedAt time.Time, values []account.QuotaWindow, replace bool) error { +func (r *AccountRepository) ReplaceQuotaWindowGroup(ctx context.Context, accountID uint64, syncedAt time.Time, modes []string, values []account.QuotaWindow) error { + allowed := make(map[string]struct{}, len(modes)) + cleanModes := make([]string, 0, len(modes)) + for _, mode := range modes { + mode = strings.TrimSpace(mode) + if mode == "" { + return repository.ErrConflict + } + if _, exists := allowed[mode]; !exists { + allowed[mode] = struct{}{} + cleanModes = append(cleanModes, mode) + } + } + if accountID == 0 || len(cleanModes) == 0 { + return repository.ErrConflict + } + seen := make(map[string]struct{}, len(values)) + for _, value := range values { + mode := strings.TrimSpace(value.Mode) + if _, ok := allowed[mode]; !ok { + return repository.ErrConflict + } + if _, duplicate := seen[mode]; duplicate { + return repository.ErrConflict + } + seen[mode] = struct{}{} + } + err := r.saveQuotaWindows(ctx, accountID, "", syncedAt, values, false, cleanModes) + if err == nil { + r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountQuotaChanged, AccountID: accountID}) + } + return err +} + +func (r *AccountRepository) saveQuotaWindows(ctx context.Context, accountID uint64, tier account.WebTier, syncedAt time.Time, values []account.QuotaWindow, replace bool, replaceModes []string) error { return r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { if tier != "" { profile := webAccountProfileModel{AccountID: accountID, Tier: string(tier), SyncedAt: &syncedAt} @@ -2332,6 +2369,10 @@ func (r *AccountRepository) saveQuotaWindows(ctx context.Context, accountID uint if err := tx.Where("account_id = ?", accountID).Delete("aWindowModel{}).Error; err != nil { return err } + } else if len(replaceModes) > 0 { + if err := tx.Where("account_id = ? AND mode IN ?", accountID, replaceModes).Delete("aWindowModel{}).Error; err != nil { + return err + } } for _, value := range values { serializedBreakdown := make([]quotaBreakdownJSON, 0, len(value.Breakdown)) diff --git a/backend/internal/infra/persistence/relational/audit_repository.go b/backend/internal/infra/persistence/relational/audit_repository.go index 820824e3..79fafeaf 100644 --- a/backend/internal/infra/persistence/relational/audit_repository.go +++ b/backend/internal/infra/persistence/relational/audit_repository.go @@ -101,7 +101,7 @@ func validatePreparedAudit(value preparedAudit) error { if !auditStringAllowed(row.Provider, "grok_build", "grok_web", "grok_console") { return errors.New("provider is invalid") } - if !auditStringAllowed(row.Operation, "responses", "compaction", "chat", "messages", "image", "image_edit", "video") { + if !auditStringAllowed(row.Operation, "responses", "compaction", "chat", "messages", "image", "image_edit", "video", "tts", "stt", "realtime", "voice") { return errors.New("operation is invalid") } if !auditStringAllowed(row.UsageSource, "upstream", "estimated", "none") { diff --git a/backend/internal/infra/persistence/relational/egress_operations_test.go b/backend/internal/infra/persistence/relational/egress_operations_test.go index 634a04fb..3fbdc593 100644 --- a/backend/internal/infra/persistence/relational/egress_operations_test.go +++ b/backend/internal/infra/persistence/relational/egress_operations_test.go @@ -790,16 +790,17 @@ func TestEgressOperationsStoresSubscriptionURLEncrypted(t *testing.T) { cipher := egressOperationsCipher(t) service := egressapp.NewService(nodes, cipher, "test-browser", accounts) url := "https://subscription.example/proxies?token=subscription-token" + proxyURL := "socks5h://proxy-user:proxy-secret@proxy.example:1080" interval := 900 capacity := 3 created, err := service.CreateSource(ctx, egressapp.SubscriptionSourceInput{ - Name: "source", Scope: egress.ScopeBuild, Enabled: true, URL: &url, + Name: "source", Scope: egress.ScopeBuild, Enabled: true, URL: &url, ProxyURL: &proxyURL, RefreshIntervalSeconds: &interval, DefaultAccountCapacity: &capacity, }) if err != nil { t.Fatal(err) } - if !created.URLConfigured || created.DefaultAccountCapacity != capacity { + if !created.URLConfigured || !created.ProxyConfigured || created.DefaultAccountCapacity != capacity { t.Fatalf("public source = %#v", created) } stored, err := nodes.GetEgressSource(ctx, created.ID) @@ -809,6 +810,79 @@ func TestEgressOperationsStoresSubscriptionURLEncrypted(t *testing.T) { if stored.EncryptedURL == url || strings.Contains(stored.EncryptedURL, "subscription-token") { t.Fatalf("subscription URL stored in plaintext: %q", stored.EncryptedURL) } + if stored.EncryptedProxyURL == proxyURL || strings.Contains(stored.EncryptedProxyURL, "proxy-secret") { + t.Fatalf("subscription proxy URL stored in plaintext: %q", stored.EncryptedProxyURL) + } + originalEncryptedProxyURL := stored.EncryptedProxyURL + + updated, err := service.UpdateSource(ctx, created.ID, egressapp.SubscriptionSourceInput{ + Name: created.Name, Scope: created.Scope, Enabled: created.Enabled, + }) + if err != nil { + t.Fatal(err) + } + if !updated.ProxyConfigured { + t.Fatal("omitted proxy update cleared the configured proxy") + } + stored, err = nodes.GetEgressSource(ctx, created.ID) + if err != nil { + t.Fatal(err) + } + if stored.EncryptedProxyURL != originalEncryptedProxyURL { + t.Fatal("omitted proxy update replaced the encrypted proxy") + } + + replacementProxyURL := "http://replacement-user:replacement-secret@proxy.example:8080" + updated, err = service.UpdateSource(ctx, created.ID, egressapp.SubscriptionSourceInput{ + Name: created.Name, Scope: created.Scope, Enabled: created.Enabled, ProxyURL: &replacementProxyURL, + }) + if err != nil { + t.Fatal(err) + } + stored, err = nodes.GetEgressSource(ctx, created.ID) + if err != nil { + t.Fatal(err) + } + decryptedProxyURL, err := cipher.Decrypt(stored.EncryptedProxyURL) + if err != nil { + t.Fatal(err) + } + if decryptedProxyURL != replacementProxyURL || !updated.ProxyConfigured { + t.Fatalf("replacement proxy = %q, public source = %#v", decryptedProxyURL, updated) + } + + for _, invalidProxyURL := range []string{"", "socks5h://Default.{account}:secret@proxy.example:1080"} { + _, updateErr := service.UpdateSource(ctx, created.ID, egressapp.SubscriptionSourceInput{ + Name: created.Name, Scope: created.Scope, Enabled: created.Enabled, ProxyURL: &invalidProxyURL, + }) + if !errors.Is(updateErr, egressapp.ErrInvalidInput) { + t.Fatalf("invalid proxy %q error = %v", invalidProxyURL, updateErr) + } + } + stored, err = nodes.GetEgressSource(ctx, created.ID) + if err != nil { + t.Fatal(err) + } + if stored.EncryptedProxyURL == "" { + t.Fatal("invalid proxy update modified the configured proxy") + } + + updated, err = service.UpdateSource(ctx, created.ID, egressapp.SubscriptionSourceInput{ + Name: created.Name, Scope: created.Scope, Enabled: created.Enabled, ClearProxyURL: true, + }) + if err != nil { + t.Fatal(err) + } + if updated.ProxyConfigured { + t.Fatal("cleared subscription proxy remains publicly configured") + } + stored, err = nodes.GetEgressSource(ctx, created.ID) + if err != nil { + t.Fatal(err) + } + if stored.EncryptedProxyURL != "" { + t.Fatal("cleared subscription proxy remains encrypted at rest") + } } func TestEgressOperationsSubscriptionImportCountsOnlyNewNodes(t *testing.T) { diff --git a/backend/internal/infra/persistence/relational/egress_repository.go b/backend/internal/infra/persistence/relational/egress_repository.go index 22650af2..254f6336 100644 --- a/backend/internal/infra/persistence/relational/egress_repository.go +++ b/backend/internal/infra/persistence/relational/egress_repository.go @@ -468,9 +468,14 @@ func (r *EgressRepository) SaveEgressOperationsConfig(ctx context.Context, value row := fromEgressOperationsConfigDomain(value) row.ID = 1 err := r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { - if _, err := lockEgressOperationsConfig(tx); err != nil { + locked, err := lockEgressOperationsConfig(tx) + if err != nil { return err } + // This schema-only marker is deliberately outside the domain settings. + // Preserve it across ordinary configuration updates so the legacy proxy + // migration cannot run again and overwrite an intentionally direct source. + row.SubscriptionProxyMigrationCompleted = locked.SubscriptionProxyMigrationCompleted if err := validateLockedEgressFallbackNodes(tx, row); err != nil { return err } @@ -823,7 +828,7 @@ func probeFamilyFromRow(status string, testedAt *time.Time, latencyMS int, exitI func toEgressSubscriptionSourceDomain(row egressSubscriptionSourceModel) egress.SubscriptionSource { return egress.SubscriptionSource{ - ID: row.ID, Name: row.Name, Scope: egress.Scope(row.Scope), Enabled: row.Enabled, EncryptedURL: row.EncryptedURL, + ID: row.ID, Name: row.Name, Scope: egress.Scope(row.Scope), Enabled: row.Enabled, EncryptedURL: row.EncryptedURL, EncryptedProxyURL: row.EncryptedProxyURL, RefreshIntervalSeconds: row.RefreshIntervalSeconds, DefaultAccountCapacity: row.DefaultAccountCapacity, LastSyncedAt: row.LastSyncedAt, NextSyncAt: row.NextSyncAt, LastSyncImported: row.LastSyncImported, LastSyncError: row.LastSyncError, CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt, @@ -832,7 +837,7 @@ func toEgressSubscriptionSourceDomain(row egressSubscriptionSourceModel) egress. func fromEgressSubscriptionSourceDomain(value egress.SubscriptionSource) egressSubscriptionSourceModel { return egressSubscriptionSourceModel{ - ID: value.ID, Name: value.Name, Scope: string(value.Scope), Enabled: value.Enabled, EncryptedURL: value.EncryptedURL, + ID: value.ID, Name: value.Name, Scope: string(value.Scope), Enabled: value.Enabled, EncryptedURL: value.EncryptedURL, EncryptedProxyURL: value.EncryptedProxyURL, RefreshIntervalSeconds: value.RefreshIntervalSeconds, DefaultAccountCapacity: value.DefaultAccountCapacity, LastSyncedAt: value.LastSyncedAt, NextSyncAt: value.NextSyncAt, LastSyncImported: value.LastSyncImported, LastSyncError: value.LastSyncError, CreatedAt: value.CreatedAt, UpdatedAt: value.UpdatedAt, @@ -843,8 +848,7 @@ func toEgressOperationsConfigDomain(row egressOperationsConfigModel) egress.Oper return egress.OperationsConfig{ ProbeProvider: egress.ProbeProvider(row.ProbeProvider).Normalized(), ProbeIntervalSeconds: row.ProbeIntervalSeconds, AutoAssignEnabled: row.AutoAssignEnabled, AutoBalanceEnabled: row.AutoBalanceEnabled, - AssignmentIntervalSeconds: row.AssignmentIntervalSeconds, - EncryptedSubscriptionProxyURL: row.EncryptedSubscriptionProxyURL, + AssignmentIntervalSeconds: row.AssignmentIntervalSeconds, Fallbacks: map[egress.Scope]egress.FallbackConfig{ egress.ScopeBuild: {Mode: egress.FallbackMode(row.BuildFallbackMode).Normalized(), NodeID: row.BuildFallbackNodeID}, egress.ScopeWeb: {Mode: egress.FallbackMode(row.WebFallbackMode).Normalized(), NodeID: row.WebFallbackNodeID}, @@ -865,8 +869,7 @@ func fromEgressOperationsConfigDomain(value egress.OperationsConfig) egressOpera return egressOperationsConfigModel{ ID: 1, ProbeProvider: string(value.ProbeProvider.Normalized()), ProbeIntervalSeconds: value.ProbeIntervalSeconds, AutoAssignEnabled: value.AutoAssignEnabled, AutoBalanceEnabled: value.AutoBalanceEnabled, AssignmentIntervalSeconds: value.AssignmentIntervalSeconds, - EncryptedSubscriptionProxyURL: value.EncryptedSubscriptionProxyURL, - BuildFallbackMode: string(buildFallback.Mode), BuildFallbackNodeID: buildFallback.NodeID, + BuildFallbackMode: string(buildFallback.Mode), BuildFallbackNodeID: buildFallback.NodeID, WebFallbackMode: string(webFallback.Mode), WebFallbackNodeID: webFallback.NodeID, ConsoleFallbackMode: string(consoleFallback.Mode), ConsoleFallbackNodeID: consoleFallback.NodeID, WebAssetFallbackMode: string(webAssetFallback.Mode), WebAssetFallbackNodeID: webAssetFallback.NodeID, diff --git a/backend/internal/infra/persistence/relational/media_repository.go b/backend/internal/infra/persistence/relational/media_repository.go index 44f458d4..48e1db2d 100644 --- a/backend/internal/infra/persistence/relational/media_repository.go +++ b/backend/internal/infra/persistence/relational/media_repository.go @@ -129,7 +129,7 @@ func (r *MediaAssetRepository) ExpireMediaInputIfUnreferenced(ctx context.Contex activeReference := r.db.db.Model(&mediaJobModel{}).Select("1"). Where("status IN ? AND input_json LIKE ?", []string{string(media.StatusQueued), string(media.StatusInProgress)}, referencePattern) result := r.db.db.WithContext(ctx).Model(&mediaAssetModel{}). - Where("id = ? AND kind = ? AND expires_at IS NOT NULL", id, "image"). + Where("id = ? AND kind IN ? AND expires_at IS NOT NULL", id, []string{"image", "video"}). Where("NOT EXISTS (?)", activeReference). Update("expires_at", expiresAt) return result.RowsAffected > 0, result.Error @@ -483,12 +483,16 @@ func (r *MediaJobRepository) TryClaimMediaJob(ctx context.Context, id string, no } func mediaJobFromDomain(value media.Job) *mediaJobModel { + operation := value.Operation + if operation == "" { + operation = media.VideoOperationGenerate + } return &mediaJobModel{ ID: value.ID, RequestID: value.RequestID, ClientKeyID: value.ClientKeyID, ClientKeyName: value.ClientKeyName, AccountID: mediaJobAccountID(value.AccountID), AccountName: value.AccountName, EgressNodeID: value.EgressNodeID, EgressNodeName: value.EgressNodeName, EgressScope: value.EgressScope, EgressMode: value.EgressMode, Provider: value.Provider, - Model: value.Model, ModelRouteID: value.ModelRouteID, UpstreamModel: value.UpstreamModel, + Model: value.Model, ModelRouteID: value.ModelRouteID, UpstreamModel: value.UpstreamModel, Operation: string(operation), Prompt: value.Prompt, Seconds: value.Seconds, Size: value.Size, Quality: value.Quality, Status: string(value.Status), Progress: value.Progress, InputJSON: value.InputJSON, InputImageCount: mediaJobInputImageCount(value.InputImageCount), UpstreamURL: value.UpstreamURL, ResultAssetID: value.ResultAssetID, ContentType: value.ContentType, ErrorCode: value.ErrorCode, ErrorMessage: value.ErrorMessage, @@ -506,12 +510,16 @@ func mediaJobToDomain(row mediaJobModel) media.Job { if row.InputImageCount != nil { inputImageCount = *row.InputImageCount } + operation := media.VideoOperation(row.Operation) + if operation == "" { + operation = media.VideoOperationGenerate + } return media.Job{ ID: row.ID, RequestID: row.RequestID, ClientKeyID: row.ClientKeyID, ClientKeyName: row.ClientKeyName, AccountID: accountID, AccountName: row.AccountName, EgressNodeID: row.EgressNodeID, EgressNodeName: row.EgressNodeName, EgressScope: row.EgressScope, EgressMode: row.EgressMode, Provider: row.Provider, - Model: row.Model, ModelRouteID: row.ModelRouteID, UpstreamModel: row.UpstreamModel, + Model: row.Model, ModelRouteID: row.ModelRouteID, UpstreamModel: row.UpstreamModel, Operation: operation, Prompt: row.Prompt, Seconds: row.Seconds, Size: row.Size, Quality: row.Quality, Status: media.Status(row.Status), Progress: row.Progress, InputJSON: row.InputJSON, InputImageCount: inputImageCount, UpstreamURL: row.UpstreamURL, ResultAssetID: row.ResultAssetID, ContentType: row.ContentType, ErrorCode: row.ErrorCode, ErrorMessage: row.ErrorMessage, diff --git a/backend/internal/infra/persistence/relational/model_capability_repository_test.go b/backend/internal/infra/persistence/relational/model_capability_repository_test.go index 5e1d4e9a..bfbf7f5b 100644 --- a/backend/internal/infra/persistence/relational/model_capability_repository_test.go +++ b/backend/internal/infra/persistence/relational/model_capability_repository_test.go @@ -556,13 +556,15 @@ func TestReplaceProviderRoutesCanRenameUpstreamModels(t *testing.T) { } } -func TestReplaceProviderRoutesRenamesWebImagePublicIDs(t *testing.T) { +func TestReplaceProviderRoutesRestoresWebImageLitePublicIDs(t *testing.T) { ctx := context.Background() database := openTestDatabase(t) repo := NewModelRepository(database) if err := repo.UpsertRoutes(ctx, []model.Route{ - {PublicID: "grok-imagine-image", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImage, Enabled: true}, - {PublicID: "grok-imagine-image-quality", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image-quality", Capability: model.CapabilityImage, Enabled: true}, + {PublicID: "grok-imagine-image-2.0", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImage, Enabled: true}, + {PublicID: "grok-imagine-image-2.0", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImageEdit, Enabled: true}, + {PublicID: "grok-imagine-image-quality-2.0", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image-quality", Capability: model.CapabilityImage, Enabled: true}, + {PublicID: "grok-imagine-image-quality-2.0", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image-quality", Capability: model.CapabilityImageEdit, Enabled: true}, }); err != nil { t.Fatal(err) } @@ -570,6 +572,18 @@ func TestReplaceProviderRoutesRenamesWebImagePublicIDs(t *testing.T) { if err := database.db.WithContext(ctx).Where("provider = ?", account.ProviderWeb).Order("upstream_model ASC").Find(&before).Error; err != nil { t.Fatal(err) } + for _, route := range before { + if route.Capability != string(model.CapabilityImage) { + continue + } + alias := "Web/grok-imagine-image-lite" + if route.UpstreamModel == "grok-imagine-image-quality" { + alias = "Web/grok-imagine-image-quality-lite" + } + if err := database.db.WithContext(ctx).Create(&modelRouteAliasModel{Alias: alias, ModelRouteID: route.ID}).Error; err != nil { + t.Fatal(err) + } + } if err := repo.ReplaceProviderRoutes(ctx, account.ProviderWeb, []model.Route{ {PublicID: "grok-imagine-image-lite", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImage, Enabled: true}, {PublicID: "grok-imagine-image-quality-lite", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image-quality", Capability: model.CapabilityImage, Enabled: true}, @@ -580,25 +594,99 @@ func TestReplaceProviderRoutesRenamesWebImagePublicIDs(t *testing.T) { if err := database.db.WithContext(ctx).Where("provider = ?", account.ProviderWeb).Order("upstream_model ASC").Find(&after).Error; err != nil { t.Fatal(err) } - if len(after) != 2 || after[0].PublicID != "Web/grok-imagine-image-lite" || after[1].PublicID != "Web/grok-imagine-image-quality-lite" { + if len(after) != 2 { t.Fatalf("renamed routes = %#v", after) } beforeIDs := make(map[string]uint64, len(before)) for _, route := range before { - beforeIDs[route.UpstreamModel] = route.ID + beforeIDs[route.UpstreamModel+"|"+route.Capability] = route.ID } for _, route := range after { - if beforeIDs[route.UpstreamModel] != route.ID { + wantPublicID := "Web/grok-imagine-image-lite" + if route.UpstreamModel == "grok-imagine-image-quality" { + wantPublicID = "Web/grok-imagine-image-quality-lite" + } + if route.Capability != string(model.CapabilityImage) || route.PublicID != wantPublicID || beforeIDs[route.UpstreamModel+"|"+route.Capability] != route.ID { t.Fatalf("route ID changed for %s: before=%#v after=%#v", route.UpstreamModel, before, after) } } - for oldPublicID, upstreamModel := range map[string]string{ - "grok-imagine-image": "grok-imagine-image", - "grok-imagine-image-quality": "grok-imagine-image-quality", - } { + compatibilityAliases := map[string]string{ + "grok-imagine-image-2.0": "Web/grok-imagine-image-lite", + "grok-imagine-image-quality-2.0": "Web/grok-imagine-image-quality-lite", + } + for oldPublicID, wantPublicID := range compatibilityAliases { route, err := repo.GetByPublicIDIncludingDisabled(ctx, oldPublicID) - if err != nil || route.UpstreamModel != upstreamModel || route.ID != beforeIDs[upstreamModel] { - t.Fatalf("legacy alias %s resolved as %#v, err=%v", oldPublicID, route, err) + if err != nil || route.PublicID != wantPublicID || route.Capability != model.CapabilityImage { + t.Fatalf("Web compatibility alias %s resolved as %#v, err=%v", oldPublicID, route, err) + } + } + var promotedAliasCount int64 + if err := database.db.WithContext(ctx).Model(&modelRouteAliasModel{}). + Where("alias IN ?", []string{"Web/grok-imagine-image-lite", "Web/grok-imagine-image-quality-lite"}). + Count(&promotedAliasCount).Error; err != nil { + t.Fatal(err) + } + if promotedAliasCount != 0 { + t.Fatalf("promoted aliases remain: %d", promotedAliasCount) + } +} + +func TestReplaceProviderRoutesRestoresThreeConsoleImageModels(t *testing.T) { + ctx := context.Background() + database := openTestDatabase(t) + repo := NewModelRepository(database) + legacyCatalog := []model.Route{ + {PublicID: "grok-imagine-image-quality-2.0", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image-quality", Capability: model.CapabilityImage, Enabled: true}, + {PublicID: "grok-imagine-image-quality-2.0", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image-quality", Capability: model.CapabilityImageEdit, Enabled: true}, + {PublicID: "grok-imagine-image-2.0", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImage, Enabled: true}, + {PublicID: "grok-imagine-image-2.0", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImageEdit, Enabled: true}, + } + if err := repo.UpsertRoutes(ctx, legacyCatalog); err != nil { + t.Fatal(err) + } + var before []modelRouteModel + if err := database.db.WithContext(ctx).Where("provider = ?", account.ProviderConsole).Find(&before).Error; err != nil { + t.Fatal(err) + } + beforeIDs := make(map[string]uint64, len(before)) + for _, route := range before { + beforeIDs[route.UpstreamModel+"|"+route.Capability] = route.ID + } + desiredCatalog := []model.Route{ + // Legacy and quality must be reconciled before the new 2.0 route so the + // rows created by the temporary two-model catalog retain their IDs. + {PublicID: "grok-imagine-image", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImage, Enabled: true}, + {PublicID: "grok-imagine-image", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImageEdit, Enabled: true}, + {PublicID: "grok-imagine-image-quality", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image-quality", Capability: model.CapabilityImage, Enabled: true}, + {PublicID: "grok-imagine-image-quality", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image-quality", Capability: model.CapabilityImageEdit, Enabled: true}, + {PublicID: "grok-imagine-image-2.0", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image-2.0", Capability: model.CapabilityImage, Enabled: true}, + {PublicID: "grok-imagine-image-2.0", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-image-2.0", Capability: model.CapabilityImageEdit, Enabled: true}, + } + for range 2 { + if err := repo.ReplaceProviderRoutes(ctx, account.ProviderConsole, desiredCatalog); err != nil { + t.Fatal(err) + } + } + var after []modelRouteModel + if err := database.db.WithContext(ctx).Where("provider = ? AND upstream_model LIKE ?", account.ProviderConsole, "grok-imagine-image%").Order("id ASC").Find(&after).Error; err != nil { + t.Fatal(err) + } + if len(after) != 6 { + t.Fatalf("Console image routes = %#v", after) + } + seen := make(map[string]map[string]bool) + for _, route := range after { + if seen[route.PublicID] == nil { + seen[route.PublicID] = make(map[string]bool) + } + seen[route.PublicID][route.Capability] = true + if route.UpstreamModel != "grok-imagine-image-2.0" && beforeIDs[route.UpstreamModel+"|"+route.Capability] != route.ID { + t.Fatalf("existing Console route ID changed: before=%#v after=%#v", before, after) + } + } + for _, publicID := range []string{"Console/grok-imagine-image", "Console/grok-imagine-image-quality", "Console/grok-imagine-image-2.0"} { + if !seen[publicID][string(model.CapabilityImage)] || !seen[publicID][string(model.CapabilityImageEdit)] { + t.Fatalf("Console image capabilities for %s = %#v", publicID, seen[publicID]) } } } diff --git a/backend/internal/infra/persistence/relational/model_repository.go b/backend/internal/infra/persistence/relational/model_repository.go index 2809acf3..f13327cc 100644 --- a/backend/internal/infra/persistence/relational/model_repository.go +++ b/backend/internal/infra/persistence/relational/model_repository.go @@ -747,13 +747,17 @@ func discoveredRouteDefaults(provider account.Provider, upstreamModel string) (s return upstreamModel, model.CapabilityResponses case account.ProviderConsole: switch upstreamModel { - case "grok-imagine-image", "grok-imagine-image-quality": + case "grok-imagine-image", "grok-imagine-image-quality", "grok-imagine-image-2.0": // The catalog also registers image_edit for the same public model. // Discovery only needs one existing managed capability to remain // idempotent and must never synthesize a Responses route. return upstreamModel, model.CapabilityImage - case "grok-imagine-video": + case "grok-imagine-video", "grok-imagine-video-1.5": return upstreamModel, model.CapabilityVideo + case "grok-voice-latest", "grok-voice-think-fast-2.0", "grok-voice-think-fast-1.0": + return upstreamModel, model.CapabilityRealtime + case "grok-stt": + return upstreamModel, model.CapabilitySTT default: return upstreamModel, model.CapabilityResponses } @@ -882,6 +886,40 @@ func (r *ModelRepository) ReplaceProviderRoutes(ctx context.Context, provider ac return err } } + // A catalog name may have multiple capability rows. When a previous + // catalog rename preserved that name as an alias to one member, restoring + // it must promote the alias back to the formal group name before every + // matched capability row is validated. Aliases owned by another group + // remain conflicts and are never reclaimed. + matchedIDsByPublicID := make(map[string]map[uint64]struct{}, len(values)) + for index, value := range values { + row, ok := matched[index] + if !ok { + continue + } + ids := matchedIDsByPublicID[value.PublicID] + if ids == nil { + ids = make(map[uint64]struct{}) + matchedIDsByPublicID[value.PublicID] = ids + } + ids[row.ID] = struct{}{} + } + for publicID, routeIDs := range matchedIDsByPublicID { + var alias modelRouteAliasModel + err := tx.Where("alias = ?", publicID).First(&alias).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + continue + } + if err != nil { + return err + } + if _, owned := routeIDs[alias.ModelRouteID]; !owned { + return fmt.Errorf("%w: 模型公开 ID %q 已被路由 %d 保留为兼容名称", repository.ErrConflict, publicID, alias.ModelRouteID) + } + if err := tx.Delete(&modelRouteAliasModel{}, "alias = ?", publicID).Error; err != nil { + return err + } + } for index, value := range values { routeID := uint64(0) if row, ok := matched[index]; ok { diff --git a/backend/internal/infra/persistence/relational/models.go b/backend/internal/infra/persistence/relational/models.go index 2a594014..966fd6e4 100644 --- a/backend/internal/infra/persistence/relational/models.go +++ b/backend/internal/infra/persistence/relational/models.go @@ -185,7 +185,7 @@ type modelRouteModel struct { PublicID string `gorm:"size:255;index:idx_model_routes_public_id_lookup;not null;check:chk_model_routes_public_id,length(trim(public_id)) BETWEEN 1 AND 255"` Provider string `gorm:"size:32;index:idx_model_routes_provider_upstream;not null;check:chk_model_routes_provider,provider IN ('grok_build','grok_web','grok_console')"` UpstreamModel string `gorm:"size:255;index:idx_model_routes_provider_upstream;not null;check:chk_model_routes_upstream_model,length(trim(upstream_model)) BETWEEN 1 AND 255"` - Capability string `gorm:"size:32;not null;check:chk_model_routes_capability,capability IN ('responses','chat','image','image_edit','video')"` + Capability string `gorm:"size:32;not null;check:chk_model_routes_capability,capability IN ('responses','chat','image','image_edit','video','tts','stt','realtime')"` Origin string `gorm:"size:32;not null;default:discovered;check:chk_model_routes_origin,origin IN ('catalog','discovered','manual')"` Enabled bool `gorm:"not null"` CreatedAt time.Time `gorm:"not null"` @@ -297,7 +297,7 @@ type requestAuditModel struct { ModelPublicID string `gorm:"size:255;check:chk_request_audits_model_public_id,length(model_public_id) <= 255"` ModelUpstreamModel string `gorm:"size:255;check:chk_request_audits_model_upstream_model,length(model_upstream_model) <= 255"` Provider string `gorm:"size:32;not null;check:chk_request_audits_provider,provider IN ('grok_build','grok_web','grok_console')"` - Operation string `gorm:"size:32;not null;check:chk_request_audits_operation,operation IN ('responses','compaction','chat','messages','image','image_edit','video')"` + Operation string `gorm:"size:32;not null;check:chk_request_audits_operation,operation IN ('responses','compaction','chat','messages','image','image_edit','video','tts','stt','realtime','voice')"` UsageSource string `gorm:"size:16;not null;check:chk_request_audits_usage_source,usage_source IN ('upstream','estimated','none')"` AccountID *uint64 `gorm:"check:chk_request_audits_account_id,account_id IS NULL OR account_id > 0"` AccountName string `gorm:"size:160;check:chk_request_audits_account_name,length(account_name) <= 160"` @@ -404,10 +404,11 @@ type mediaJobModel struct { Model string `gorm:"size:255;not null;check:chk_media_jobs_model,length(trim(model)) BETWEEN 1 AND 255"` ModelRouteID uint64 `gorm:"not null;check:chk_media_jobs_model_route_id,model_route_id > 0"` UpstreamModel string `gorm:"size:255;not null;check:chk_media_jobs_upstream_model,length(trim(upstream_model)) BETWEEN 1 AND 255"` + Operation string `gorm:"size:16;not null;default:'generate';check:chk_media_jobs_operation,operation IN ('generate','edit','extend')"` Prompt string `gorm:"type:text;not null;check:chk_media_jobs_prompt,length(prompt) BETWEEN 0 AND 100000"` - Seconds int `gorm:"not null;check:chk_media_jobs_seconds,seconds BETWEEN 1 AND 15"` - Size string `gorm:"size:32;not null;check:chk_media_jobs_size,length(trim(size)) BETWEEN 1 AND 32"` - Quality string `gorm:"size:32;not null;check:chk_media_jobs_quality,length(trim(quality)) BETWEEN 1 AND 32"` + Seconds int `gorm:"not null;check:chk_media_jobs_seconds,seconds BETWEEN 0 AND 15"` + Size string `gorm:"size:32;not null;default:'';check:chk_media_jobs_size,length(trim(size)) BETWEEN 0 AND 32"` + Quality string `gorm:"size:32;not null;default:'';check:chk_media_jobs_quality,length(trim(quality)) BETWEEN 0 AND 32"` Status string `gorm:"size:32;not null;check:chk_media_jobs_status,status IN ('queued','in_progress','completed','failed')"` Progress int `gorm:"not null;check:chk_media_jobs_progress,progress BETWEEN 0 AND 100"` // InputJSON limit 33554432 must stay equal to media.MaxInputJSONBytes (GORM tags require literals). @@ -477,6 +478,7 @@ type egressSubscriptionSourceModel struct { Scope string `gorm:"size:32;not null;check:chk_egress_subscription_sources_scope,scope IN ('grok_build','grok_web','grok_console','grok_web_asset','grok_console_asset')"` Enabled bool `gorm:"not null;default:true"` EncryptedURL string `gorm:"type:text;not null;default:'';check:chk_egress_subscription_sources_url,length(encrypted_url) <= 65536"` + EncryptedProxyURL string `gorm:"type:text;not null;default:'';check:chk_egress_subscription_sources_proxy_url,length(encrypted_proxy_url) <= 65536"` RefreshIntervalSeconds int `gorm:"not null;default:900;check:chk_egress_subscription_sources_refresh,refresh_interval_seconds BETWEEN 60 AND 86400"` DefaultAccountCapacity int `gorm:"not null;default:0;check:chk_egress_subscription_sources_capacity,default_account_capacity BETWEEN 0 AND 100000"` LastSyncedAt *time.Time @@ -532,24 +534,24 @@ type egressNodeModel struct { func (egressNodeModel) TableName() string { return "egress_nodes" } type egressOperationsConfigModel struct { - ID uint64 `gorm:"primaryKey;check:chk_egress_operations_config_id,id = 1"` - ProbeProvider string `gorm:"size:16;not null;default:cloudflare;check:chk_egress_operations_config_probe_provider,probe_provider IN ('ipinfo','cloudflare')"` - ProbeIntervalSeconds int `gorm:"not null;default:900;check:chk_egress_operations_config_probe_interval,probe_interval_seconds BETWEEN 60 AND 86400"` - AutoAssignEnabled bool `gorm:"not null;default:false"` - AutoBalanceEnabled bool `gorm:"not null;default:false"` - AssignmentIntervalSeconds int `gorm:"not null;default:300;check:chk_egress_operations_config_assignment_interval,assignment_interval_seconds BETWEEN 60 AND 86400"` - EncryptedSubscriptionProxyURL string `gorm:"type:text;not null;default:'';check:chk_egress_operations_config_subscription_proxy,length(encrypted_subscription_proxy_url) <= 65536"` - BuildFallbackMode string `gorm:"size:16;not null;default:none"` - BuildFallbackNodeID uint64 `gorm:"not null;default:0"` - WebFallbackMode string `gorm:"size:16;not null;default:none"` - WebFallbackNodeID uint64 `gorm:"not null;default:0"` - ConsoleFallbackMode string `gorm:"size:16;not null;default:none"` - ConsoleFallbackNodeID uint64 `gorm:"not null;default:0"` - WebAssetFallbackMode string `gorm:"size:16;not null;default:none"` - WebAssetFallbackNodeID uint64 `gorm:"not null;default:0"` - ConsoleAssetFallbackMode string `gorm:"size:16;not null;default:none"` - ConsoleAssetFallbackNodeID uint64 `gorm:"not null;default:0"` - UpdatedAt time.Time `gorm:"not null"` + ID uint64 `gorm:"primaryKey;check:chk_egress_operations_config_id,id = 1"` + ProbeProvider string `gorm:"size:16;not null;default:cloudflare;check:chk_egress_operations_config_probe_provider,probe_provider IN ('ipinfo','cloudflare')"` + ProbeIntervalSeconds int `gorm:"not null;default:900;check:chk_egress_operations_config_probe_interval,probe_interval_seconds BETWEEN 60 AND 86400"` + AutoAssignEnabled bool `gorm:"not null;default:false"` + AutoBalanceEnabled bool `gorm:"not null;default:false"` + AssignmentIntervalSeconds int `gorm:"not null;default:300;check:chk_egress_operations_config_assignment_interval,assignment_interval_seconds BETWEEN 60 AND 86400"` + SubscriptionProxyMigrationCompleted bool `gorm:"not null;default:false"` + BuildFallbackMode string `gorm:"size:16;not null;default:none"` + BuildFallbackNodeID uint64 `gorm:"not null;default:0"` + WebFallbackMode string `gorm:"size:16;not null;default:none"` + WebFallbackNodeID uint64 `gorm:"not null;default:0"` + ConsoleFallbackMode string `gorm:"size:16;not null;default:none"` + ConsoleFallbackNodeID uint64 `gorm:"not null;default:0"` + WebAssetFallbackMode string `gorm:"size:16;not null;default:none"` + WebAssetFallbackNodeID uint64 `gorm:"not null;default:0"` + ConsoleAssetFallbackMode string `gorm:"size:16;not null;default:none"` + ConsoleAssetFallbackNodeID uint64 `gorm:"not null;default:0"` + UpdatedAt time.Time `gorm:"not null"` } func (egressOperationsConfigModel) TableName() string { return "egress_operations_config" } diff --git a/backend/internal/infra/persistence/relational/repository_test.go b/backend/internal/infra/persistence/relational/repository_test.go index bde32048..532ce331 100644 --- a/backend/internal/infra/persistence/relational/repository_test.go +++ b/backend/internal/infra/persistence/relational/repository_test.go @@ -256,6 +256,47 @@ func TestAccountRepositoryDecrementsQuotaByAmountAtomically(t *testing.T) { } } +func TestAccountRepositoryReplacesQuotaGroupWithoutTouchingOtherModes(t *testing.T) { + ctx := context.Background() + repo := NewAccountRepository(openTestDatabase(t)) + value, _, err := repo.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderWeb, AuthType: account.AuthTypeSSO, Name: "quota-group", SourceKey: "quota-group", + EncryptedAccessToken: testEncryptedToken, AuthStatus: account.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + initial := []account.QuotaWindow{ + {AccountID: value.ID, Mode: "weekly", Remaining: 90, Total: 100, UpdatedAt: now}, + {AccountID: value.ID, Mode: account.QuotaModeWebImagePro, Remaining: 4, UpdatedAt: now}, + {AccountID: value.ID, Mode: account.QuotaModeWebVideo720p, Remaining: 1, UpdatedAt: now}, + } + if err := repo.SaveQuotaWindows(ctx, value.ID, account.WebTierSuper, now, initial); err != nil { + t.Fatal(err) + } + updatedAt := now.Add(time.Minute) + if err := repo.ReplaceQuotaWindowGroup(ctx, value.ID, updatedAt, account.WebImagineQuotaModes(), []account.QuotaWindow{ + {AccountID: value.ID, Mode: account.QuotaModeWebImagePro, Remaining: 3, UpdatedAt: updatedAt}, + }); err != nil { + t.Fatal(err) + } + windows, err := repo.GetQuotaWindows(ctx, []uint64{value.ID}) + if err != nil { + t.Fatal(err) + } + byMode := make(map[string]account.QuotaWindow) + for _, window := range windows[value.ID] { + byMode[window.Mode] = window + } + if byMode["weekly"].Remaining != 90 || byMode[account.QuotaModeWebImagePro].Remaining != 3 { + t.Fatalf("windows = %#v", windows[value.ID]) + } + if _, exists := byMode[account.QuotaModeWebVideo720p]; exists { + t.Fatalf("explicitly unavailable group mode was preserved: %#v", windows[value.ID]) + } +} + func TestAccountRepositorySummarizesOperationalStates(t *testing.T) { ctx := context.Background() now := time.Now().UTC() diff --git a/backend/internal/infra/persistence/relational/routing_projection_test.go b/backend/internal/infra/persistence/relational/routing_projection_test.go index 3d90cdd7..a211a249 100644 --- a/backend/internal/infra/persistence/relational/routing_projection_test.go +++ b/backend/internal/infra/persistence/relational/routing_projection_test.go @@ -44,6 +44,9 @@ func TestRoutingProjectionLeavesSecretsAndLargeJSONOutOfCandidateLoad(t *testing AccountID: created.ID, Mode: "weekly", Remaining: 10, Total: 20, UsagePercent: 50, Breakdown: []account.QuotaBreakdown{{ProductCode: account.QuotaProductChat, UsagePercent: 50}}, WindowSeconds: 3600, ResetAt: &resetAt, SyncedAt: &now, Source: account.QuotaSourceUpstream, + }, { + AccountID: created.ID, Mode: account.QuotaModeWebImagePro, Remaining: 3, + WindowSeconds: 86400, SyncedAt: &now, Source: account.QuotaSourceUpstream, }}); err != nil { t.Fatal(err) } @@ -62,6 +65,13 @@ func TestRoutingProjectionLeavesSecretsAndLargeJSONOutOfCandidateLoad(t *testing if bases[0].QuotaWindow == nil || bases[0].QuotaWindow.Remaining != 10 || len(bases[0].QuotaWindow.Breakdown) != 0 { t.Fatalf("routing quota = %#v, want scalar quota without breakdown", bases[0].QuotaWindow) } + imagineBases, err := accounts.ListRoutingAccountBases(ctx, account.ProviderWeb, account.QuotaModeWebImagePro) + if err != nil { + t.Fatal(err) + } + if len(imagineBases) != 1 || imagineBases[0].QuotaWindow == nil || imagineBases[0].QuotaWindow.Mode != account.QuotaModeWebImagePro || imagineBases[0].QuotaWindow.Remaining != 3 { + t.Fatalf("Imagine routing quota = %#v", imagineBases) + } candidates, err := accounts.ListRoutingCandidates(ctx, account.ProviderWeb, 0, "grok-test", "") if err != nil { @@ -94,8 +104,8 @@ func TestRoutingProjectionLeavesSecretsAndLargeJSONOutOfCandidateLoad(t *testing if err != nil { t.Fatal(err) } - if len(windows[created.ID]) != 1 || len(windows[created.ID][0].Breakdown) != 1 { - t.Fatalf("management quota windows = %#v, want breakdown", windows) + if len(windows[created.ID]) != 2 { + t.Fatalf("management quota windows = %#v, want two modes", windows) } } diff --git a/backend/internal/infra/persistence/relational/schema.go b/backend/internal/infra/persistence/relational/schema.go index dab56f5a..c5c7b96e 100644 --- a/backend/internal/infra/persistence/relational/schema.go +++ b/backend/internal/infra/persistence/relational/schema.go @@ -12,6 +12,7 @@ import ( "github.com/chenyme/grok2api/backend/internal/domain/media" settingsdomain "github.com/chenyme/grok2api/backend/internal/domain/settings" "gorm.io/gorm" + "gorm.io/gorm/clause" ) const mediaJobInputMetadataPendingIndex = "CREATE INDEX IF NOT EXISTS idx_media_jobs_input_metadata_pending ON media_jobs(id) WHERE input_image_count IS NULL" @@ -129,6 +130,7 @@ func (d *Database) initializeSchema(ctx context.Context) error { hadProviderScope := hadClientKeys && db.Migrator().HasColumn(&clientKeyModel{}, "ProviderScopeMask") hadTierScope := hadClientKeys && db.Migrator().HasColumn(&clientKeyModel{}, "TierScopeMask") hadLegacyAccountPool := hadClientKeys && db.Migrator().HasColumn("client_keys", "account_pool") + hadGlobalSubscriptionProxy := db.Migrator().HasTable("egress_operations_config") && db.Migrator().HasColumn("egress_operations_config", "encrypted_subscription_proxy_url") // all 作用域会让 Build 与 Web 共用 UA、健康度和冷却状态,升级时直接移除旧节点。 if db.Migrator().HasTable(&egressNodeModel{}) { if err := db.Where("scope = ?", "all").Delete(&egressNodeModel{}).Error; err != nil { @@ -149,6 +151,11 @@ func (d *Database) initializeSchema(ctx context.Context) error { if migrateErr != nil { return fmt.Errorf("初始化数据库表: %w", migrateErr) } + if hadGlobalSubscriptionProxy { + if err := d.migratePerSourceSubscriptionProxy(ctx); err != nil { + return fmt.Errorf("迁移代理订阅拉取代理: %w", err) + } + } if err := d.migrateClientKeyAccountScopes(ctx, hadLegacyAccountPool, !hadProviderScope, !hadTierScope); err != nil { return fmt.Errorf("迁移客户端 Key 调用范围: %w", err) } @@ -167,9 +174,15 @@ func (d *Database) initializeSchema(ctx context.Context) error { if err := d.ensureAuditOperationConstraints(ctx); err != nil { return fmt.Errorf("迁移请求审计操作约束: %w", err) } + if err := d.ensureModelRouteCapabilityConstraints(ctx); err != nil { + return fmt.Errorf("迁移模型路由能力约束: %w", err) + } if err := d.ensureMediaJobConstraints(ctx); err != nil { return fmt.Errorf("迁移 media job 数据库约束: %w", err) } + if err := d.migrateMediaJobOperations(ctx); err != nil { + return fmt.Errorf("迁移 media job 操作类型: %w", err) + } if err := d.ensureMediaJobInputConstraint(ctx); err != nil { return fmt.Errorf("迁移 media job 输入长度约束: %w", err) } @@ -216,6 +229,43 @@ func (d *Database) initializeSchema(ctx context.Context) error { return nil } +func (d *Database) migratePerSourceSubscriptionProxy(ctx context.Context) error { + return d.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + var legacy struct { + EncryptedProxyURL string `gorm:"column:encrypted_subscription_proxy_url"` + MigrationCompleted bool `gorm:"column:subscription_proxy_migration_completed"` + } + err := tx.Table("egress_operations_config"). + Select("encrypted_subscription_proxy_url", "subscription_proxy_migration_completed"). + Where("id = ?", 1). + Clauses(clause.Locking{Strength: "UPDATE"}). + Take(&legacy).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil + } + if err != nil { + return err + } + if legacy.MigrationCompleted { + return nil + } + if strings.TrimSpace(legacy.EncryptedProxyURL) != "" { + if err := tx.Model(&egressSubscriptionSourceModel{}).Where("encrypted_proxy_url = ''").Updates(map[string]any{ + "encrypted_proxy_url": legacy.EncryptedProxyURL, + "next_sync_at": nil, + "last_sync_error": "", + }).Error; err != nil { + return err + } + } + // Keep the encrypted legacy value for still-running old replicas and a + // rollback window. The marker prevents subsequent startups from applying + // it to sources that were later configured for direct fetching. + return tx.Table("egress_operations_config").Where("id = ?", 1). + Update("subscription_proxy_migration_completed", true).Error + }) +} + // migrateClientKeyAccountScopes translates the short-lived account_pool // representation only when the corresponding scope columns are first added. func (d *Database) migrateClientKeyAccountScopes(ctx context.Context, hadLegacyAccountPool, providerScopeAdded, tierScopeAdded bool) error { @@ -386,11 +436,19 @@ func (d *Database) ensureEgressAssetScopeConstraints(ctx context.Context) error } // ensureAuditOperationConstraints upgrades existing databases so Codex remote -// compaction can be recorded separately from ordinary Responses requests. +// compaction and Console voice operations can be recorded separately. func (d *Database) ensureAuditOperationConstraints(ctx context.Context) error { return d.ensureNamedConstraints(ctx, []consoleConstraint{ {model: &requestAuditModel{}, table: "request_audits", name: "chk_request_audits_operation"}, - }, "compaction") + }, "tts") +} + +// ensureModelRouteCapabilityConstraints upgrades existing databases so Console +// TTS/STT/Realtime routes can be managed alongside image and video. +func (d *Database) ensureModelRouteCapabilityConstraints(ctx context.Context) error { + return d.ensureNamedConstraints(ctx, []consoleConstraint{ + {model: &modelRouteModel{}, table: "model_routes", name: "chk_model_routes_capability"}, + }, "tts") } // ensureMediaJobConstraints 将历史仅允许 grok_web 的 media job CHECK 升级到支持 Build 与 Console 视频。 @@ -401,9 +459,43 @@ func (d *Database) ensureMediaJobConstraints(ctx context.Context) error { }, "grok_console"); err != nil { return err } - return d.ensureNamedConstraints(ctx, []consoleConstraint{ + if err := d.ensureNamedConstraints(ctx, []consoleConstraint{ {model: &mediaJobModel{}, table: "media_jobs", name: "chk_media_jobs_egress_scope"}, - }, "grok_console") + }, "grok_console"); err != nil { + return err + } + for _, constraint := range []consoleConstraint{ + {model: &mediaJobModel{}, table: "media_jobs", name: "chk_media_jobs_operation"}, + {model: &mediaJobModel{}, table: "media_jobs", name: "chk_media_jobs_seconds"}, + {model: &mediaJobModel{}, table: "media_jobs", name: "chk_media_jobs_size"}, + {model: &mediaJobModel{}, table: "media_jobs", name: "chk_media_jobs_quality"}, + } { + marker := "0" + if constraint.name == "chk_media_jobs_operation" { + marker = "extend" + } + if err := d.ensureNamedConstraints(ctx, []consoleConstraint{constraint}, marker); err != nil { + return err + } + } + return nil +} + +// migrateMediaJobOperations preserves queued and in-progress edit/extension +// jobs created before media_jobs.operation existed. Those releases persisted +// the operation only in the compact JSON metadata; AutoMigrate necessarily +// fills the new non-null column with "generate", which must not change the +// request semantics when a job is recovered after an upgrade. +func (d *Database) migrateMediaJobOperations(ctx context.Context) error { + editPattern := `%"operation":"edit"%` + extendPattern := `%"operation":"extend"%` + return d.db.WithContext(ctx).Exec( + `UPDATE media_jobs + SET operation = CASE WHEN input_json LIKE ? THEN ? ELSE ? END + WHERE operation = ? AND (input_json LIKE ? OR input_json LIKE ?)`, + editPattern, media.VideoOperationEdit, media.VideoOperationExtend, + media.VideoOperationGenerate, editPattern, extendPattern, + ).Error } // ensureMediaJobInputConstraint 允许异步视频任务持久化 Base64 首图。 diff --git a/backend/internal/infra/persistence/relational/schema_media_job_upgrade_test.go b/backend/internal/infra/persistence/relational/schema_media_job_upgrade_test.go index 9609dd4e..638be3da 100644 --- a/backend/internal/infra/persistence/relational/schema_media_job_upgrade_test.go +++ b/backend/internal/infra/persistence/relational/schema_media_job_upgrade_test.go @@ -61,6 +61,28 @@ func TestMediaJobModelTagsAllowAllVideoProvidersAndPrimaryScopes(t *testing.T) { !strings.Contains(countTag, "IS NULL OR input_image_count BETWEEN 0 AND "+maxImages) { t.Fatalf("input_image_count tag = %q, want max %s", countTag, maxImages) } + operationField, ok := modelType.FieldByName("Operation") + if !ok { + t.Fatal("Operation field missing") + } + operationTag := operationField.Tag.Get("gorm") + if !strings.Contains(operationTag, "chk_media_jobs_operation") || + !strings.Contains(operationTag, "'generate','edit','extend'") { + t.Fatalf("operation tag = %q", operationTag) + } + for fieldName, expected := range map[string]string{ + "Seconds": "seconds BETWEEN 0 AND 15", + "Size": "length(trim(size)) BETWEEN 0 AND 32", + "Quality": "length(trim(quality)) BETWEEN 0 AND 32", + } { + field, exists := modelType.FieldByName(fieldName) + if !exists { + t.Fatalf("%s field missing", fieldName) + } + if tag := field.Tag.Get("gorm"); !strings.Contains(tag, expected) { + t.Fatalf("%s tag = %q, want %q", fieldName, tag, expected) + } + } } func TestMediaJobInputMetadataPendingIndexExists(t *testing.T) { @@ -95,6 +117,61 @@ func TestMediaJobInputMetadataPendingIndexExists(t *testing.T) { } } +func TestInitializeSchemaBackfillsLegacyMediaJobOperations(t *testing.T) { + ctx := context.Background() + database := openTestDatabase(t) + accountValue, _, err := NewAccountRepository(database).UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderConsole, AuthType: accountdomain.AuthTypeSSO, + Name: "legacy-video-operation", SourceKey: "legacy-video-operation", + EncryptedAccessToken: testEncryptedToken, AuthStatus: accountdomain.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + key := clientKeyModel{Name: "legacy-video-operation", Prefix: "legacy-video-operation", SecretHash: testSecretHash, EncryptedSecret: testEncryptedToken, Enabled: true, RPMLimit: 60, MaxConcurrent: 4} + if err := database.db.WithContext(ctx).Create(&key).Error; err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + jobs := NewMediaJobRepository(database) + for index, operation := range []mediadomain.VideoOperation{mediadomain.VideoOperationEdit, mediadomain.VideoOperationExtend} { + job := testMediaJob(fmt.Sprintf("video_legacy_operation_%d", index), accountValue.ID, key.ID, mediadomain.StatusQueued, now) + job.Operation = mediadomain.VideoOperationGenerate + job.InputJSON = fmt.Sprintf(`{"operation":%q,"video_url":"https://example.com/source.mp4"}`, operation) + if err := jobs.CreateMediaJob(ctx, job); err != nil { + t.Fatal(err) + } + } + generate := testMediaJob("video_legitimate_generate", accountValue.ID, key.ID, mediadomain.StatusQueued, now) + generate.InputJSON = `{}` + if err := jobs.CreateMediaJob(ctx, generate); err != nil { + t.Fatal(err) + } + + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + for index, want := range []string{"edit", "extend"} { + var row mediaJobModel + if err := database.db.WithContext(ctx).Where("id = ?", fmt.Sprintf("video_legacy_operation_%d", index)).First(&row).Error; err != nil { + t.Fatal(err) + } + if row.Operation != want { + t.Fatalf("legacy operation = %q, want %q", row.Operation, want) + } + } + var generateRow mediaJobModel + if err := database.db.WithContext(ctx).Where("id = ?", generate.ID).First(&generateRow).Error; err != nil { + t.Fatal(err) + } + if generateRow.Operation != "generate" { + t.Fatalf("generate operation = %q", generateRow.Operation) + } +} + func TestInitializeSchemaUpgradesOnlyPreviousMediaJobInputConstraint(t *testing.T) { ctx := context.Background() database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "previous-media-input.db")) diff --git a/backend/internal/infra/persistence/relational/schema_subscription_proxy_upgrade_test.go b/backend/internal/infra/persistence/relational/schema_subscription_proxy_upgrade_test.go new file mode 100644 index 00000000..94b94856 --- /dev/null +++ b/backend/internal/infra/persistence/relational/schema_subscription_proxy_upgrade_test.go @@ -0,0 +1,137 @@ +package relational + +import ( + "context" + "path/filepath" + "testing" + "time" + + egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress" +) + +type legacyOperationsConfigWithSubscriptionProxy struct { + ID uint64 `gorm:"primaryKey"` + ProbeProvider string `gorm:"size:16;not null;default:cloudflare"` + ProbeIntervalSeconds int `gorm:"not null;default:900"` + AutoAssignEnabled bool `gorm:"not null;default:false"` + AutoBalanceEnabled bool `gorm:"not null;default:false"` + AssignmentIntervalSeconds int `gorm:"not null;default:300"` + EncryptedSubscriptionProxyURL string `gorm:"type:text;not null;default:''"` + BuildFallbackMode string `gorm:"size:16;not null;default:none"` + BuildFallbackNodeID uint64 `gorm:"not null;default:0"` + WebFallbackMode string `gorm:"size:16;not null;default:none"` + WebFallbackNodeID uint64 `gorm:"not null;default:0"` + ConsoleFallbackMode string `gorm:"size:16;not null;default:none"` + ConsoleFallbackNodeID uint64 `gorm:"not null;default:0"` + WebAssetFallbackMode string `gorm:"size:16;not null;default:none"` + WebAssetFallbackNodeID uint64 `gorm:"not null;default:0"` + ConsoleAssetFallbackMode string `gorm:"size:16;not null;default:none"` + ConsoleAssetFallbackNodeID uint64 `gorm:"not null;default:0"` + UpdatedAt time.Time `gorm:"not null"` +} + +func (legacyOperationsConfigWithSubscriptionProxy) TableName() string { + return "egress_operations_config" +} + +type legacySubscriptionSourceWithoutProxy struct { + ID uint64 `gorm:"primaryKey"` + Name string `gorm:"size:160;not null"` + Scope string `gorm:"size:32;not null"` + Enabled bool `gorm:"not null;default:true"` + EncryptedURL string `gorm:"type:text;not null;default:''"` + RefreshIntervalSeconds int `gorm:"not null;default:900"` + DefaultAccountCapacity int `gorm:"not null;default:0"` + LastSyncedAt *time.Time + NextSyncAt *time.Time + LastSyncImported int `gorm:"not null;default:0"` + LastSyncError string `gorm:"size:512;not null;default:''"` + CreatedAt time.Time `gorm:"not null"` + UpdatedAt time.Time `gorm:"not null"` +} + +func (legacySubscriptionSourceWithoutProxy) TableName() string { + return "egress_subscription_sources" +} + +func TestSchemaMigratesGlobalSubscriptionProxyToEverySource(t *testing.T) { + ctx := context.Background() + database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "subscription-proxy-upgrade.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = database.Close() }) + + if err := database.db.AutoMigrate(&legacyOperationsConfigWithSubscriptionProxy{}, &legacySubscriptionSourceWithoutProxy{}); err != nil { + t.Fatal(err) + } + const encryptedProxy = "encrypted-global-subscription-proxy" + if err := database.db.Create(&legacyOperationsConfigWithSubscriptionProxy{ID: 1, EncryptedSubscriptionProxyURL: encryptedProxy}).Error; err != nil { + t.Fatal(err) + } + for _, source := range []legacySubscriptionSourceWithoutProxy{ + {ID: 1, Name: "domestic", Scope: "grok_build", Enabled: true}, + {ID: 2, Name: "overseas", Scope: "grok_web", Enabled: true}, + } { + if err := database.db.Create(&source).Error; err != nil { + t.Fatal(err) + } + } + + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + var sources []egressSubscriptionSourceModel + if err := database.db.Order("id").Find(&sources).Error; err != nil { + t.Fatal(err) + } + if len(sources) != 2 { + t.Fatalf("migrated sources = %d", len(sources)) + } + for _, source := range sources { + if source.EncryptedProxyURL != encryptedProxy || source.NextSyncAt != nil { + t.Fatalf("migrated source = %#v", source) + } + } + var current egressOperationsConfigModel + if err := database.db.First(¤t, 1).Error; err != nil { + t.Fatal(err) + } + if !current.SubscriptionProxyMigrationCompleted { + t.Fatal("subscription proxy migration was not marked complete") + } + repository := NewEgressRepository(database) + if _, err := repository.SaveEgressOperationsConfig(ctx, egressdomain.DefaultOperationsConfig()); err != nil { + t.Fatal(err) + } + if err := database.db.First(¤t, 1).Error; err != nil { + t.Fatal(err) + } + if !current.SubscriptionProxyMigrationCompleted { + t.Fatal("ordinary operations update reset the subscription proxy migration marker") + } + var legacy legacyOperationsConfigWithSubscriptionProxy + if err := database.db.First(&legacy, 1).Error; err != nil { + t.Fatal(err) + } + if legacy.EncryptedSubscriptionProxyURL != encryptedProxy { + t.Fatal("legacy global subscription proxy was not retained for rollback") + } + + // Sources created after the one-time migration must remain direct. Keeping + // the legacy ciphertext for rollback must not cause it to be copied again. + direct := legacySubscriptionSourceWithoutProxy{ID: 3, Name: "direct", Scope: "grok_console", Enabled: true} + if err := database.db.Create(&direct).Error; err != nil { + t.Fatal(err) + } + if err := database.InitializeSchema(ctx); err != nil { + t.Fatalf("repeated migration failed: %v", err) + } + var directAfterRestart egressSubscriptionSourceModel + if err := database.db.First(&directAfterRestart, direct.ID).Error; err != nil { + t.Fatal(err) + } + if directAfterRestart.EncryptedProxyURL != "" { + t.Fatal("repeated migration applied the legacy proxy to a new direct source") + } +} diff --git a/backend/internal/infra/provider/cli/fallback_test.go b/backend/internal/infra/provider/cli/fallback_test.go index 8bec0564..f58d5557 100644 --- a/backend/internal/infra/provider/cli/fallback_test.go +++ b/backend/internal/infra/provider/cli/fallback_test.go @@ -669,7 +669,7 @@ func TestGenerateVideoFallbackInjectsUploadURL(t *testing.T) { }) result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ Credential: account.Credential{ID: 15, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted, BuildSuperEntitled: true}, - JobID: "video_job_1", Prompt: "waves", Duration: 6, Resolution: "720p", ReferenceURLs: []string{"https://cdn.example.com/first.png"}, + JobID: "video_job_1", Prompt: "waves", Duration: 6, Resolution: "720p", ImageURL: "https://cdn.example.com/first.png", }) if err != nil { t.Fatal(err) @@ -750,7 +750,7 @@ func TestGenerateVideoAutoBotFlaggedUsesXAIDirectly(t *testing.T) { }) result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ Credential: account.Credential{ID: 116, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted, BuildRouteMode: account.BuildRouteAuto, BuildSuperEntitled: true}, - JobID: "video_bot", Prompt: "waves", Duration: 6, Resolution: "720p", ReferenceURLs: []string{"https://cdn.example.com/bot.png"}, + JobID: "video_bot", Prompt: "waves", Duration: 6, Resolution: "720p", ImageURL: "https://cdn.example.com/bot.png", }) if err != nil { t.Fatal(err) diff --git a/backend/internal/infra/provider/cli/video.go b/backend/internal/infra/provider/cli/video.go index 672e0a6d..5f771ef3 100644 --- a/backend/internal/infra/provider/cli/video.go +++ b/backend/internal/infra/provider/cli/video.go @@ -14,6 +14,7 @@ import ( "unicode/utf8" "github.com/chenyme/grok2api/backend/internal/domain/account" + mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media" infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" "github.com/chenyme/grok2api/backend/internal/infra/provider" ) @@ -21,7 +22,9 @@ import ( const ( buildVideoModel = "grok-imagine-video-1.5" xaiVideoModel = "grok-imagine-video-1.5-preview" - buildVideoMaxImages = 1 + // Align with the gateway ceiling and official xAI video inputs: + // image = first frame; reference_images = style/content references (may be length 1). + buildVideoMaxImages = mediadomain.MaxInputImages buildVideoPollEvery = 2 * time.Second buildVideoMaxBodySize = 2 << 20 buildVideoErrorSummaryLimit = 256 @@ -148,13 +151,13 @@ func boundDiagnosticText(value string, limit int) string { } // GenerateVideo 通过 Build OAuth 创建并轮询视频任务;对外仍使用 grok-imagine-video-1.5, -// 发往 XAI 时仅在出站协议层转换为官方 preview 模型与 image.url 结构。 -// 最多 1 张首图;多于 1 张在调用上游前失败,不静默截断。 +// 发往 XAI 时仅在出站协议层转换为官方 preview 模型与 image/reference_images 结构。 +// image = 首帧;reference_images = 参考图(即使只有 1 张也不升格为 image)。超过网关上限时失败,不静默截断。 // 显式模式优先;auto 下仅已确认 Super 且 bot_flag_source/bfs 为 1 或 2 默认使用 XAI。 // 其他 auto Super 账号仅在当次 Build 创建返回 403 后探测 XAI。 func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoRequest) (provider.VideoResult, error) { - if len(request.ReferenceURLs) > buildVideoMaxImages { - return provider.VideoResult{}, fmt.Errorf("Build grok-imagine-video-1.5 最多支持 1 张首图,当前为 %d 张", len(request.ReferenceURLs)) + if total := buildVideoImageCount(request); total > buildVideoMaxImages { + return provider.VideoResult{}, fmt.Errorf("Build grok-imagine-video-1.5 最多支持 %d 张输入图,当前为 %d 张", buildVideoMaxImages, total) } accessToken, err := a.cipher.Decrypt(request.Credential.EncryptedAccessToken) if err != nil { @@ -291,16 +294,52 @@ func videoCreatePayload(request provider.VideoRequest, uploadURL string, profile if resolution := strings.TrimSpace(request.Resolution); resolution != "" { payload["resolution"] = resolution } - if len(request.ReferenceURLs) == 1 { - imageURL := strings.TrimSpace(request.ReferenceURLs[0]) - if imageURL == "" { - return nil, fmt.Errorf("视频首图 URL 不能为空") - } + if imageURL := strings.TrimSpace(request.ImageURL); imageURL != "" { payload["image"] = map[string]any{profile.imageURLField: imageURL} } + if strings.TrimSpace(request.ImageURL) != "" && (len(request.ReferenceURLs) > 0 || len(request.ReferenceAudios) > 0) { + return nil, fmt.Errorf("image 不能与 reference_images/reference_audios 同时使用") + } + if len(request.ReferenceURLs) > 0 { + references := make([]map[string]any, 0, len(request.ReferenceURLs)) + for _, rawURL := range request.ReferenceURLs { + refURL := strings.TrimSpace(rawURL) + if refURL == "" { + return nil, fmt.Errorf("视频参考图 URL 不能为空") + } + references = append(references, map[string]any{profile.imageURLField: refURL}) + } + // A single reference must stay in reference_images; do not coerce to image. + payload["reference_images"] = references + } + if len(request.ReferenceAudios) > 0 { + if len(request.ReferenceAudios) > 3 { + return nil, fmt.Errorf("reference_audios 最多 3 个") + } + audios := make([]map[string]any, 0, len(request.ReferenceAudios)) + for _, raw := range request.ReferenceAudios { + voiceID := strings.TrimSpace(raw) + if voiceID == "" { + return nil, fmt.Errorf("reference_audios.voice_id 不能为空") + } + audios = append(audios, map[string]any{"voice_id": voiceID}) + } + payload["reference_audios"] = audios + } + hasReferenceMode := len(request.ReferenceURLs) > 0 || len(request.ReferenceAudios) > 0 + if hasReferenceMode { + if strings.TrimSpace(request.Prompt) == "" { + return nil, fmt.Errorf("参考图/参考音频视频必须提供 prompt") + } + if strings.EqualFold(strings.TrimSpace(request.Resolution), "1080p") { + return nil, fmt.Errorf("参考图视频 resolution 最高 720p") + } + } if _, hasPrompt := payload["prompt"]; !hasPrompt { if _, hasImage := payload["image"]; !hasImage { - return nil, fmt.Errorf("文本生视频必须提供 prompt;图片生视频可以省略 prompt") + if !hasReferenceMode { + return nil, fmt.Errorf("文本生视频必须提供 prompt;图片生视频可以省略 prompt") + } } } if uploadURL = strings.TrimSpace(uploadURL); uploadURL != "" { @@ -555,3 +594,16 @@ func numberAsInt(value any) (int, bool) { return 0, false } } + +func buildVideoImageCount(request provider.VideoRequest) int { + count := 0 + if strings.TrimSpace(request.ImageURL) != "" { + count++ + } + for _, raw := range request.ReferenceURLs { + if strings.TrimSpace(raw) != "" { + count++ + } + } + return count +} diff --git a/backend/internal/infra/provider/cli/video_test.go b/backend/internal/infra/provider/cli/video_test.go index ebd2f822..b24c935a 100644 --- a/backend/internal/infra/provider/cli/video_test.go +++ b/backend/internal/infra/provider/cli/video_test.go @@ -38,7 +38,7 @@ func TestBuildVideoCreatePayloadNoImageAndSingleR2URL(t *testing.T) { withImage, err := videoCreatePayload(provider.VideoRequest{ Prompt: "animate", Duration: 6, AspectRatio: "16:9", Resolution: "720p", - ReferenceURLs: []string{"https://cdn.example.com/r2/first.png"}, + ImageURL: "https://cdn.example.com/r2/first.png", }, "", buildVideoRequestProfile) if err != nil { t.Fatal(err) @@ -47,10 +47,28 @@ func TestBuildVideoCreatePayloadNoImageAndSingleR2URL(t *testing.T) { if !ok || image["image_url"] != "https://cdn.example.com/r2/first.png" { t.Fatalf("image payload = %#v", withImage) } + if _, exists := withImage["reference_images"]; exists { + t.Fatalf("first-frame payload must not include reference_images: %#v", withImage) + } if withImage["model"] != buildVideoModel || withImage["resolution"] != "720p" || withImage["aspect_ratio"] != "16:9" { t.Fatalf("single-image payload = %#v", withImage) } + withSingleReference, err := videoCreatePayload(provider.VideoRequest{ + Prompt: "animate", Duration: 6, AspectRatio: "16:9", Resolution: "720p", + ReferenceURLs: []string{"https://cdn.example.com/r2/ref-only.png"}, + }, "", buildVideoRequestProfile) + if err != nil { + t.Fatal(err) + } + if _, exists := withSingleReference["image"]; exists { + t.Fatalf("single reference must not coerce to image: %#v", withSingleReference) + } + singleRefs, ok := withSingleReference["reference_images"].([]map[string]any) + if !ok || len(singleRefs) != 1 || singleRefs[0]["image_url"] != "https://cdn.example.com/r2/ref-only.png" { + t.Fatalf("single reference payload = %#v", withSingleReference) + } + withUpload, err := videoCreatePayload(provider.VideoRequest{Prompt: "x", Duration: 6}, "https://api.example/v1/media/uploads/tok", buildVideoRequestProfile) if err != nil { t.Fatal(err) @@ -63,11 +81,11 @@ func TestBuildVideoCreatePayloadNoImageAndSingleR2URL(t *testing.T) { func TestBuildVideoCreatePayloadImageOnlyEmptyPrompt(t *testing.T) { payload, err := videoCreatePayload(provider.VideoRequest{ - Prompt: " ", - Duration: 6, - AspectRatio: "16:9", - Resolution: "720p", - ReferenceURLs: []string{"https://r2.example.com/first.png"}, + Prompt: " ", + Duration: 6, + AspectRatio: "16:9", + Resolution: "720p", + ImageURL: "https://r2.example.com/first.png", }, "", buildVideoRequestProfile) if err != nil { t.Fatal(err) @@ -83,11 +101,11 @@ func TestBuildVideoCreatePayloadImageOnlyEmptyPrompt(t *testing.T) { func TestXAIVideoCreatePayloadMatchesOfficialSchema(t *testing.T) { payload, err := videoCreatePayload(provider.VideoRequest{ - Prompt: "animate", - Duration: 6, - AspectRatio: "16:9", - Resolution: "720p", - ReferenceURLs: []string{"https://cdn.example.com/r2/first.png"}, + Prompt: "animate", + Duration: 6, + AspectRatio: "16:9", + Resolution: "720p", + ImageURL: "https://cdn.example.com/r2/first.png", }, "https://api.example/v1/media/uploads/tok", xaiVideoRequestProfile) if err != nil { t.Fatal(err) @@ -108,23 +126,109 @@ func TestXAIVideoCreatePayloadMatchesOfficialSchema(t *testing.T) { } } -func TestGenerateVideoRejectsTwoImagesBeforeUpstream(t *testing.T) { - adapter, encrypted := newTestBuildVideoAdapter(t) - var hits atomic.Int32 - adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { - hits.Add(1) - t.Fatalf("two-image request must not reach upstream: %s %s", request.Method, request.URL) - return nil, nil - }) - _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ - Credential: account.Credential{ID: 1, EncryptedAccessToken: encrypted}, - Prompt: "animate", +func TestBuildVideoCreatePayloadMapsMultipleReferences(t *testing.T) { + payload, err := videoCreatePayload(provider.VideoRequest{ + Prompt: "animate", + Duration: 6, + AspectRatio: "16:9", + Resolution: "720p", + ReferenceURLs: []string{ + "https://cdn.example.com/one.png", + "https://cdn.example.com/two.png", + "https://cdn.example.com/three.png", + }, + }, "", buildVideoRequestProfile) + if err != nil { + t.Fatal(err) + } + if _, exists := payload["image"]; exists { + t.Fatalf("multi-reference payload must not include image: %#v", payload) + } + references, ok := payload["reference_images"].([]map[string]any) + if !ok || len(references) != 3 { + t.Fatalf("reference_images = %#v", payload["reference_images"]) + } + if references[0]["image_url"] != "https://cdn.example.com/one.png" || references[2]["image_url"] != "https://cdn.example.com/three.png" { + t.Fatalf("reference_images = %#v", references) + } + + xaiPayload, err := videoCreatePayload(provider.VideoRequest{ + Prompt: "animate", ReferenceURLs: []string{ "https://cdn.example.com/one.png", "https://cdn.example.com/two.png", }, + }, "https://api.example/v1/media/uploads/tok", xaiVideoRequestProfile) + if err != nil { + t.Fatal(err) + } + xaiReferences, ok := xaiPayload["reference_images"].([]map[string]any) + if !ok || len(xaiReferences) != 2 || xaiReferences[0]["url"] != "https://cdn.example.com/one.png" { + t.Fatalf("xai reference_images = %#v", xaiPayload["reference_images"]) + } + if _, exists := xaiPayload["image"]; exists { + t.Fatalf("xai multi-reference payload must not include image: %#v", xaiPayload) + } +} + +func TestBuildVideoCreatePayloadRejectsImageWithReferences(t *testing.T) { + _, err := videoCreatePayload(provider.VideoRequest{ + Prompt: "animate", + Duration: 6, + AspectRatio: "16:9", + Resolution: "720p", + ImageURL: "https://cdn.example.com/first-frame.png", + ReferenceURLs: []string{"https://cdn.example.com/ref.png"}, + }, "", buildVideoRequestProfile) + if err == nil { + t.Fatal("expected image+reference_images combination to fail") + } +} + +func TestBuildVideoCreatePayloadReferenceAudios(t *testing.T) { + payload, err := videoCreatePayload(provider.VideoRequest{ + Prompt: "speak", + Duration: 8, + AspectRatio: "9:16", + Resolution: "720p", + ReferenceURLs: []string{"https://cdn.example.com/person.png"}, + ReferenceAudios: []string{"eve"}, + }, "", buildVideoRequestProfile) + if err != nil { + t.Fatal(err) + } + if _, exists := payload["image"]; exists { + t.Fatalf("image = %#v", payload["image"]) + } + references, ok := payload["reference_images"].([]map[string]any) + if !ok || len(references) != 1 || references[0]["image_url"] != "https://cdn.example.com/person.png" { + t.Fatalf("reference_images = %#v", payload["reference_images"]) + } + audios, ok := payload["reference_audios"].([]map[string]any) + if !ok || len(audios) != 1 || audios[0]["voice_id"] != "eve" { + t.Fatalf("reference_audios = %#v", payload["reference_audios"]) + } +} + + +func TestGenerateVideoRejectsTooManyImagesBeforeUpstream(t *testing.T) { + adapter, encrypted := newTestBuildVideoAdapter(t) + var hits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + hits.Add(1) + t.Fatalf("oversized reference request must not reach upstream: %s %s", request.Method, request.URL) + return nil, nil }) - if err == nil || !strings.Contains(err.Error(), "最多支持 1 张首图") { + references := make([]string, buildVideoMaxImages+1) + for i := range references { + references[i] = "https://cdn.example.com/" + strings.Repeat("x", i+1) + ".png" + } + _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: account.Credential{ID: 1, EncryptedAccessToken: encrypted}, + Prompt: "animate", + ReferenceURLs: references, + }) + if err == nil || !strings.Contains(err.Error(), "最多支持") { t.Fatalf("error = %v", err) } if hits.Load() != 0 { @@ -132,6 +236,66 @@ func TestGenerateVideoRejectsTwoImagesBeforeUpstream(t *testing.T) { } } +func TestGenerateVideoPostsReferenceImagesAndPollsUntilReady(t *testing.T) { + adapter, encrypted := newTestBuildVideoAdapter(t) + var createBody map[string]any + var pollCount atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + if identity := infraegress.AccountFromContext(request.Context()); identity != "grok_build_9" { + t.Fatalf("egress account identity = %q", identity) + } + switch { + case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations": + if request.Header.Get("Authorization") != "Bearer access-token" { + t.Fatalf("missing auth header: %#v", request.Header) + } + if err := json.NewDecoder(request.Body).Decode(&createBody); err != nil { + t.Fatal(err) + } + return jsonResponse(http.StatusOK, `{"request_id":"vid_ref_123","status":"queued"}`, request), nil + case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/vid_ref_123": + count := pollCount.Add(1) + if count == 1 { + return jsonResponse(http.StatusOK, `{"status":"processing","progress":40}`, request), nil + } + return jsonResponse(http.StatusOK, `{"status":"completed","progress":100,"video":{"url":"https://assets.grok.com/videos/ref.mp4"}}`, request), nil + default: + t.Fatalf("unexpected request %s %s", request.Method, request.URL) + return nil, nil + } + }) + + result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: account.Credential{ID: 9, UserID: "user-1", EncryptedAccessToken: encrypted}, + Prompt: "animate knife", + Duration: 6, + AspectRatio: "16:9", + Resolution: "720p", + ReferenceURLs: []string{ + "https://r2.example.com/first.png", + "https://r2.example.com/second.png", + }, + }) + if err != nil { + t.Fatal(err) + } + if result.URL != "https://assets.grok.com/videos/ref.mp4" || result.ContentType != "video/mp4" { + t.Fatalf("result = %#v", result) + } + if _, exists := createBody["image"]; exists { + t.Fatalf("create body unexpectedly includes image: %#v", createBody) + } + references, ok := createBody["reference_images"].([]any) + if !ok || len(references) != 2 { + t.Fatalf("create body reference_images = %#v", createBody["reference_images"]) + } + first, _ := references[0].(map[string]any) + second, _ := references[1].(map[string]any) + if first["image_url"] != "https://r2.example.com/first.png" || second["image_url"] != "https://r2.example.com/second.png" { + t.Fatalf("create body = %#v", createBody) + } +} + func TestGenerateVideoPostsSingleImageAndPollsUntilReady(t *testing.T) { adapter, encrypted := newTestBuildVideoAdapter(t) var createBody map[string]any @@ -169,12 +333,12 @@ func TestGenerateVideoPostsSingleImageAndPollsUntilReady(t *testing.T) { var progressValues []int result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ - Credential: account.Credential{ID: 9, UserID: "user-1", EncryptedAccessToken: encrypted}, - Prompt: "animate knife", - Duration: 6, - AspectRatio: "16:9", - Resolution: "720p", - ReferenceURLs: []string{"https://r2.example.com/first.png"}, + Credential: account.Credential{ID: 9, UserID: "user-1", EncryptedAccessToken: encrypted}, + Prompt: "animate knife", + Duration: 6, + AspectRatio: "16:9", + Resolution: "720p", + ImageURL: "https://r2.example.com/first.png", Progress: func(value int) { progressValues = append(progressValues, value) }, diff --git a/backend/internal/infra/provider/console/adapter.go b/backend/internal/infra/provider/console/adapter.go index b6ef8d2d..6c399053 100644 --- a/backend/internal/infra/provider/console/adapter.go +++ b/backend/internal/infra/provider/console/adapter.go @@ -78,6 +78,9 @@ func (a *Adapter) QuotaMode(upstreamModel string) string { if ResolveMedia(upstreamModel, modeldomain.CapabilityVideo) { return QuotaModeVideo } + if ResolveMedia(upstreamModel, modeldomain.CapabilityTTS) || ResolveMedia(upstreamModel, modeldomain.CapabilitySTT) || ResolveMedia(upstreamModel, modeldomain.CapabilityRealtime) { + return QuotaMode + } return "" } diff --git a/backend/internal/infra/provider/console/catalog.go b/backend/internal/infra/provider/console/catalog.go index 3715bd1b..da8262a7 100644 --- a/backend/internal/infra/provider/console/catalog.go +++ b/backend/internal/infra/provider/console/catalog.go @@ -35,15 +35,28 @@ var mediaCatalog = []struct { UpstreamModel string Capabilities []modeldomain.Capability }{ - {PublicID: "grok-imagine-image-quality", UpstreamModel: "grok-imagine-image-quality", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}}, + // Keep the three official Console image products distinct. The legacy and + // quality routes intentionally precede 2.0 so catalog reconciliation can + // restore stable route IDs created before 2.0 was introduced. {PublicID: "grok-imagine-image", UpstreamModel: "grok-imagine-image", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}}, + {PublicID: "grok-imagine-image-quality", UpstreamModel: "grok-imagine-image-quality", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}}, + {PublicID: "grok-imagine-image-2.0", UpstreamModel: "grok-imagine-image-2.0", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}}, {PublicID: "grok-imagine-video", UpstreamModel: "grok-imagine-video", Capabilities: []modeldomain.Capability{modeldomain.CapabilityVideo}}, + // Free Console accounts can use the 1.5 video model on the official Console media API. + {PublicID: "grok-imagine-video-1.5", UpstreamModel: "grok-imagine-video-1.5", Capabilities: []modeldomain.Capability{modeldomain.CapabilityVideo}}, + {PublicID: "grok-voice-latest", UpstreamModel: "grok-voice-latest", Capabilities: []modeldomain.Capability{modeldomain.CapabilityRealtime, modeldomain.CapabilityTTS}}, + {PublicID: "grok-voice-think-fast-2.0", UpstreamModel: "grok-voice-think-fast-2.0", Capabilities: []modeldomain.Capability{modeldomain.CapabilityRealtime, modeldomain.CapabilityTTS}}, + {PublicID: "grok-voice-think-fast-1.0", UpstreamModel: "grok-voice-think-fast-1.0", Capabilities: []modeldomain.Capability{modeldomain.CapabilityRealtime, modeldomain.CapabilityTTS}}, + {PublicID: "grok-stt", UpstreamModel: "grok-stt", Capabilities: []modeldomain.Capability{modeldomain.CapabilitySTT}}, } // Effort-suffixed aliases only include levels each Provider/model combination // actually supports (see domain/model.SupportedReasoningEffortsForProvider). // No blanket none/low/medium/high/xhigh/max template. var aliases = []provider.ModelAlias{ + // Compatibility for the temporary PR catalog name. The official quality + // model itself remains a first-class route. + consoleAlias("grok-imagine-image-quality-2.0", "grok-imagine-image-quality", "grok-imagine-image-quality", ""), consoleAlias("grok-4.3-console", "grok-4.3", "grok-4.3", ""), consoleAlias("grok-4.20-0309-reasoning-console", "grok-4.20-0309-reasoning", "grok-4.20-0309-reasoning", ""), consoleAlias("grok-4.20-0309-non-reasoning-console", "grok-4.20-0309-non-reasoning", "grok-4.20-0309-non-reasoning", ""), diff --git a/backend/internal/infra/provider/console/console_test.go b/backend/internal/infra/provider/console/console_test.go index bb88af56..22658cfe 100644 --- a/backend/internal/infra/provider/console/console_test.go +++ b/backend/internal/infra/provider/console/console_test.go @@ -21,6 +21,9 @@ import ( "testing" "time" + fhttp "github.com/bogdanfinn/fhttp" + fhttptest "github.com/bogdanfinn/fhttp/httptest" + "github.com/bogdanfinn/websocket" "github.com/chenyme/grok2api/backend/internal/domain/account" egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress" mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media" @@ -47,11 +50,21 @@ func TestCatalogContainsAllConsoleModelsAndAliases(t *testing.T) { {publicID: "Console/grok-4.20-multi-agent-0309", capability: modeldomain.CapabilityResponses}: "grok-4.20-multi-agent-0309", {publicID: "Console/grok-4.5", capability: modeldomain.CapabilityResponses}: "grok-4.5", {publicID: "Console/grok-build-0.1", capability: modeldomain.CapabilityResponses}: "grok-build-0.1", - {publicID: "Console/grok-imagine-image-quality", capability: modeldomain.CapabilityImage}: "grok-imagine-image-quality", - {publicID: "Console/grok-imagine-image-quality", capability: modeldomain.CapabilityImageEdit}: "grok-imagine-image-quality", {publicID: "Console/grok-imagine-image", capability: modeldomain.CapabilityImage}: "grok-imagine-image", {publicID: "Console/grok-imagine-image", capability: modeldomain.CapabilityImageEdit}: "grok-imagine-image", + {publicID: "Console/grok-imagine-image-quality", capability: modeldomain.CapabilityImage}: "grok-imagine-image-quality", + {publicID: "Console/grok-imagine-image-quality", capability: modeldomain.CapabilityImageEdit}: "grok-imagine-image-quality", + {publicID: "Console/grok-imagine-image-2.0", capability: modeldomain.CapabilityImage}: "grok-imagine-image-2.0", + {publicID: "Console/grok-imagine-image-2.0", capability: modeldomain.CapabilityImageEdit}: "grok-imagine-image-2.0", {publicID: "Console/grok-imagine-video", capability: modeldomain.CapabilityVideo}: "grok-imagine-video", + {publicID: "Console/grok-imagine-video-1.5", capability: modeldomain.CapabilityVideo}: "grok-imagine-video-1.5", + {publicID: "Console/grok-voice-latest", capability: modeldomain.CapabilityRealtime}: "grok-voice-latest", + {publicID: "Console/grok-voice-latest", capability: modeldomain.CapabilityTTS}: "grok-voice-latest", + {publicID: "Console/grok-voice-think-fast-2.0", capability: modeldomain.CapabilityRealtime}: "grok-voice-think-fast-2.0", + {publicID: "Console/grok-voice-think-fast-2.0", capability: modeldomain.CapabilityTTS}: "grok-voice-think-fast-2.0", + {publicID: "Console/grok-voice-think-fast-1.0", capability: modeldomain.CapabilityRealtime}: "grok-voice-think-fast-1.0", + {publicID: "Console/grok-voice-think-fast-1.0", capability: modeldomain.CapabilityTTS}: "grok-voice-think-fast-1.0", + {publicID: "Console/grok-stt", capability: modeldomain.CapabilitySTT}: "grok-stt", } routes := Routes() if len(routes) != len(expected) { @@ -66,14 +79,15 @@ func TestCatalogContainsAllConsoleModelsAndAliases(t *testing.T) { } } aliases := Aliases() - if len(aliases) != 13 { - t.Fatalf("aliases = %d, want 13", len(aliases)) + if len(aliases) != 14 { + t.Fatalf("aliases = %d, want 14", len(aliases)) } registry := provider.NewRegistry(NewAdapter(Config{}, nil, nil, nil)) if registry.SupportsStoredResponses(account.ProviderConsole) { t.Fatal("console must not advertise stored Responses support") } for _, name := range []string{ + "grok-imagine-image-quality-2.0", "grok-4.3-console", "grok-4.20-0309-reasoning-console", "grok-4.20-0309-non-reasoning-console", "grok-4.20-multi-agent-console", "grok-build-console", "grok-4.3-low", "grok-4.3-medium", "grok-4.3-high", @@ -90,8 +104,9 @@ func TestCatalogContainsAllConsoleModelsAndAliases(t *testing.T) { } adapter := NewAdapter(Config{}, nil, nil, nil) for model, want := range map[string]string{ - "grok-4.5": QuotaMode, "grok-imagine-image-quality": QuotaModeImage, - "grok-imagine-image": QuotaModeImage, "grok-imagine-video": QuotaModeVideo, + "grok-4.5": QuotaMode, "grok-imagine-image-quality": QuotaModeImage, "grok-imagine-image-2.0": QuotaModeImage, + "grok-imagine-image": QuotaModeImage, "grok-imagine-video": QuotaModeVideo, "grok-imagine-video-1.5": QuotaModeVideo, + "grok-voice-latest": QuotaMode, "grok-voice-think-fast-2.0": QuotaMode, "grok-voice-think-fast-1.0": QuotaMode, "grok-stt": QuotaMode, } { if got := adapter.QuotaMode(model); got != want { t.Fatalf("QuotaMode(%q) = %q, want %q", model, got, want) @@ -99,6 +114,142 @@ func TestCatalogContainsAllConsoleModelsAndAliases(t *testing.T) { } } +func TestConsoleVoiceErrorIsSanitizedAndPreservesRetryMetadata(t *testing.T) { + response := &http.Response{ + StatusCode: http.StatusTooManyRequests, + Header: http.Header{"Retry-After": {"17"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"Authorization: Bearer secret-token"}}`)), + } + err := consoleVoiceResponseError(response) + if err == nil { + t.Fatal("expected voice upstream error") + } + if strings.Contains(strings.ToLower(err.Error()), "authorization") || strings.Contains(err.Error(), "secret-token") { + t.Fatalf("voice error exposed sensitive upstream body: %q", err) + } + if status, ok := provider.ErrorHTTPStatus(err); !ok || status != http.StatusTooManyRequests { + t.Fatalf("status = %d, ok = %v", status, ok) + } + if retryAfter := provider.ErrorRetryAfter(err); retryAfter != 17*time.Second { + t.Fatalf("retry after = %s", retryAfter) + } + if message, ok := provider.ErrorPublicMessage(err); !ok || strings.Contains(message, "secret-token") { + t.Fatalf("public message = %q, ok = %v", message, ok) + } +} + +func TestConsoleVoiceErrorSanitizesCredentialAliases(t *testing.T) { + for _, body := range []string{ + `{"error":{"message":"access_token=secret"}}`, + `{"error":{"message":"refresh-token=secret"}}`, + `{"error":{"message":"api_key=secret"}}`, + `{"error":{"message":"Bearer secret"}}`, + `{"error":{"message":"cf_clearance=secret"}}`, + } { + err := newConsoleMediaUpstreamError(http.StatusBadGateway, []byte(body), 0) + message, ok := provider.ErrorPublicMessage(err) + if !ok || message == "" || strings.Contains(strings.ToLower(message), "secret") { + t.Fatalf("body %q produced public message %q, ok = %v", body, message, ok) + } + } +} + +func TestConsoleVoiceDPoPRejectionIsRequestScoped(t *testing.T) { + err := newConsoleMediaUpstreamError(http.StatusForbidden, []byte(`{"error":{"code":"unauthorized:dpop-required"}}`), 0) + if !provider.IsRequestScopedError(err) { + t.Fatalf("DPoP rejection was not request-scoped: %v", err) + } + if strings.Contains(strings.ToLower(err.Error()), "authorization") { + t.Fatalf("DPoP error exposed authorization details: %q", err) + } +} + +func TestVoiceWebSocketProofEndpointUsesHTTPUpgradeURI(t *testing.T) { + got, err := voiceWebSocketProofEndpoint("wss://console.x.ai/v1/realtime?model=grok-voice-latest") + if err != nil { + t.Fatal(err) + } + if got != "https://console.x.ai/v1/realtime?model=grok-voice-latest" { + t.Fatalf("proof endpoint = %q", got) + } +} + +func TestVoiceWebSocketRefreshesDPoPOnceAfterUnauthorized(t *testing.T) { + var tokenRequests atomic.Int32 + var websocketRequests atomic.Int32 + server := fhttptest.NewServer(fhttp.HandlerFunc(func(writer fhttp.ResponseWriter, request *fhttp.Request) { + switch request.URL.Path { + case "/v1/dpop/token": + tokenRequests.Add(1) + var payload struct { + JWK dpopJWK `json:"jwk"` + } + if err := json.NewDecoder(request.Body).Decode(&payload); err != nil { + t.Errorf("decode DPoP token request: %v", err) + writer.WriteHeader(http.StatusBadRequest) + return + } + thumbprint, err := dpopJWKThumbprint(payload.JWK) + if err != nil { + t.Errorf("DPoP thumbprint: %v", err) + writer.WriteHeader(http.StatusBadRequest) + return + } + header, _ := json.Marshal(map[string]any{"alg": "HS256", "typ": "JWT"}) + claims, _ := json.Marshal(map[string]any{ + "sub": "test-user", "iat": time.Now().UTC().Unix(), "exp": time.Now().UTC().Add(5 * time.Minute).Unix(), + "cnf": map[string]any{"jkt": thumbprint}, "token_use": "dpop-bound", + }) + accessToken := base64.RawURLEncoding.EncodeToString(header) + "." + base64.RawURLEncoding.EncodeToString(claims) + ".dGVzdA" + writer.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(writer).Encode(map[string]any{"access_token": accessToken, "token_type": "DPoP", "expires_in": 300}) + case "/v1/realtime": + current := websocketRequests.Add(1) + proof, _, err := jwt.NewParser().ParseUnverified(request.Header.Get("DPoP"), jwt.MapClaims{}) + if err != nil { + t.Errorf("parse DPoP proof: %v", err) + writer.WriteHeader(http.StatusBadRequest) + return + } + claims := proof.Claims.(jwt.MapClaims) + wantHTU := "http://" + request.Host + request.URL.EscapedPath() + if claims["htu"] != wantHTU || claims["htm"] != http.MethodGet { + t.Errorf("websocket DPoP binding = %#v, want htu=%q", claims, wantHTU) + } + if current == 1 { + writer.WriteHeader(http.StatusUnauthorized) + return + } + connection, err := (&websocket.Upgrader{CheckOrigin: func(*fhttp.Request) bool { return true }}).Upgrade(writer, request, nil) + if err != nil { + t.Errorf("upgrade voice websocket: %v", err) + return + } + _ = connection.Close() + default: + fhttp.NotFound(writer, request) + } + })) + defer server.Close() + + adapter, credential := newConsoleTestAdapter(t, server.URL) + connection, cleanup, err := adapter.DialVoiceWebSocket(context.Background(), provider.VoiceWebSocketRequest{ + Credential: credential, Path: "/realtime", Model: "grok-voice-latest", + }) + if err != nil { + t.Fatal(err) + } + if connection != nil { + _ = connection.Close() + } + if cleanup != nil { + cleanup() + } + if tokenRequests.Load() != 2 || websocketRequests.Load() != 2 { + t.Fatalf("requests token=%d websocket=%d", tokenRequests.Load(), websocketRequests.Load()) + } +} + func TestSyncAccountIdentityUsesWebSessionWithConsoleCredential(t *testing.T) { t.Parallel() server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { @@ -185,6 +336,140 @@ func TestNormalizeRequestAppliesConsoleContract(t *testing.T) { } } +func TestNormalizeRequestForwardsXSearchTimeRangeAndImageSearch(t *testing.T) { + spec, ok := Resolve("grok-4.3") + if !ok { + t.Fatal("grok-4.3 missing") + } + + t.Run("forwards enable_image_search on web_search", func(t *testing.T) { + body, err := normalizeRequest([]byte(`{ + "model":"grok-4.3", + "tools":[{"type":"web_search","enable_image_search":true,"custom":true}] + }`), spec) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(body, &payload); err != nil { + t.Fatal(err) + } + tools, _ := payload["tools"].([]any) + if len(tools) != 1 { + t.Fatalf("tools = %#v", tools) + } + webSearch, _ := tools[0].(map[string]any) + if webSearch["type"] != "web_search" || webSearch["enable_image_understanding"] != true { + t.Fatalf("web_search defaults = %#v", webSearch) + } + if webSearch["enable_image_search"] != true { + t.Fatalf("enable_image_search not forwarded: %#v", webSearch) + } + if webSearch["custom"] != nil { + t.Fatalf("unknown field custom should be stripped: %#v", webSearch) + } + }) + + t.Run("omits enable_image_search when client does not set it", func(t *testing.T) { + body, err := normalizeRequest([]byte(`{ + "model":"grok-4.3", + "tools":[{"type":"web_search"}] + }`), spec) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(body, &payload); err != nil { + t.Fatal(err) + } + webSearch, _ := payload["tools"].([]any)[0].(map[string]any) + if _, exists := webSearch["enable_image_search"]; exists { + t.Fatalf("enable_image_search should be absent by default: %#v", webSearch) + } + }) + + t.Run("forwards valid x_search from_date and to_date", func(t *testing.T) { + body, err := normalizeRequest([]byte(`{ + "model":"grok-4.3", + "tools":[{"type":"x_search","from_date":"2026-07-01","to_date":"2026-07-23","noise":1}] + }`), spec) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(body, &payload); err != nil { + t.Fatal(err) + } + xSearch, _ := payload["tools"].([]any)[0].(map[string]any) + if xSearch["type"] != "x_search" || xSearch["enable_video_understanding"] != true { + t.Fatalf("x_search defaults = %#v", xSearch) + } + if xSearch["from_date"] != "2026-07-01" || xSearch["to_date"] != "2026-07-23" { + t.Fatalf("date bounds not forwarded: %#v", xSearch) + } + if xSearch["noise"] != nil { + t.Fatalf("unknown field noise should be stripped: %#v", xSearch) + } + }) + + t.Run("drops invalid date formats", func(t *testing.T) { + body, err := normalizeRequest([]byte(`{ + "model":"grok-4.3", + "tools":[{"type":"x_search","from_date":"2026-7-01","to_date":"2026-02-30"}] + }`), spec) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(body, &payload); err != nil { + t.Fatal(err) + } + xSearch, _ := payload["tools"].([]any)[0].(map[string]any) + if xSearch["from_date"] != nil || xSearch["to_date"] != nil { + t.Fatalf("invalid dates should be dropped: %#v", xSearch) + } + if xSearch["type"] != "x_search" || xSearch["enable_video_understanding"] != true { + t.Fatalf("x_search defaults should remain: %#v", xSearch) + } + }) + + t.Run("drops inverted date range", func(t *testing.T) { + body, err := normalizeRequest([]byte(`{ + "model":"grok-4.3", + "tools":[{"type":"x_search","from_date":"2026-07-24","to_date":"2026-07-23"}] + }`), spec) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(body, &payload); err != nil { + t.Fatal(err) + } + xSearch, _ := payload["tools"].([]any)[0].(map[string]any) + if xSearch["from_date"] != nil || xSearch["to_date"] != nil { + t.Fatalf("inverted range should drop both bounds: %#v", xSearch) + } + }) + + t.Run("keeps only from_date when to_date absent", func(t *testing.T) { + body, err := normalizeRequest([]byte(`{ + "model":"grok-4.3", + "tools":[{"type":"x_search","from_date":"2026-08-01"}] + }`), spec) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(body, &payload); err != nil { + t.Fatal(err) + } + xSearch, _ := payload["tools"].([]any)[0].(map[string]any) + if xSearch["from_date"] != "2026-08-01" || xSearch["to_date"] != nil { + t.Fatalf("single bound = %#v", xSearch) + } + }) +} + func TestNormalizeRequestDoesNotInjectToolsForConsoleCatalog(t *testing.T) { for _, spec := range catalog { t.Run(spec.PublicID, func(t *testing.T) { @@ -1228,6 +1513,43 @@ func TestConsoleImageEditForwardsMultipleImages(t *testing.T) { } } +func TestConsoleImage20ForwardsQualityAndRejectsItForLegacyModels(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if serveTestDPoPToken(t, writer, request) { + return + } + var payload map[string]any + if err := json.NewDecoder(request.Body).Decode(&payload); err != nil { + t.Error(err) + } + if payload["model"] != "grok-imagine-image-2.0" || payload["quality"] != "low" || payload["resolution"] != "2k" { + t.Errorf("Image 2.0 payload = %#v", payload) + } + writer.Header().Set("Content-Type", "application/json") + _, _ = writer.Write([]byte(`{"data":[{"b64_json":"aW1hZ2U="}]}`)) + })) + t.Cleanup(server.Close) + adapter, credential := newConsoleTestAdapter(t, server.URL) + response, err := adapter.GenerateImage(context.Background(), provider.ImageGenerationRequest{ + Credential: credential, Model: "grok-imagine-image-2.0", Prompt: "draw", Count: 1, + Resolution: "2k", Quality: "low", ResponseFormat: "b64_json", + }) + if err != nil { + t.Fatal(err) + } + _ = response.Body.Close() + legacy, err := adapter.GenerateImage(context.Background(), provider.ImageGenerationRequest{ + Credential: credential, Model: "grok-imagine-image", Prompt: "draw", Count: 1, Quality: "low", + }) + if err != nil { + t.Fatal(err) + } + defer legacy.Body.Close() + if legacy.StatusCode != http.StatusBadRequest { + t.Fatalf("legacy quality response = %#v", legacy) + } +} + func TestConsoleVideoCreatesAndPollsStandardResources(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { if serveTestDPoPToken(t, writer, request) { @@ -1266,6 +1588,291 @@ func TestConsoleVideoCreatesAndPollsStandardResources(t *testing.T) { } } +func TestConsoleVideoPostsReferenceImages(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if serveTestDPoPToken(t, writer, request) { + return + } + verifyTestDPoPProof(t, request) + writer.Header().Set("Content-Type", "application/json") + switch { + case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations": + var payload map[string]any + if err := json.NewDecoder(request.Body).Decode(&payload); err != nil { + t.Error(err) + } + if _, exists := payload["image"]; exists { + t.Errorf("multi-reference payload must not include image: %#v", payload) + } + references, ok := payload["reference_images"].([]any) + if !ok || len(references) != 3 { + t.Errorf("reference_images = %#v", payload["reference_images"]) + } else { + first, _ := references[0].(map[string]any) + third, _ := references[2].(map[string]any) + if first["url"] != "https://example.com/a.png" || third["url"] != "https://example.com/c.png" { + t.Errorf("reference_images = %#v", references) + } + } + _, _ = writer.Write([]byte(`{"request_id":"upstream-video-ref-1"}`)) + case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-ref-1": + _, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-ref.mp4"}}`)) + default: + http.NotFound(writer, request) + } + })) + t.Cleanup(server.Close) + adapter, credential := newConsoleTestAdapter(t, server.URL) + result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Prompt: "animate", Duration: 6, AspectRatio: "16:9", Resolution: "720p", + ReferenceURLs: []string{ + "https://example.com/a.png", + "https://example.com/b.png", + "https://example.com/c.png", + }, + }) + if err != nil { + t.Fatal(err) + } + if result.URL != "https://vidgen.x.ai/result-ref.mp4" || result.ContentType != "video/mp4" { + t.Fatalf("video result = %#v", result) + } +} + +func TestConsoleVideoPostsSingleReferenceImage(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if serveTestDPoPToken(t, writer, request) { + return + } + verifyTestDPoPProof(t, request) + writer.Header().Set("Content-Type", "application/json") + switch { + case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations": + var payload map[string]any + if err := json.NewDecoder(request.Body).Decode(&payload); err != nil { + t.Error(err) + } + if _, exists := payload["image"]; exists { + t.Errorf("single reference must not coerce to image: %#v", payload) + } + references, ok := payload["reference_images"].([]any) + if !ok || len(references) != 1 { + t.Errorf("reference_images = %#v", payload["reference_images"]) + } else { + first, _ := references[0].(map[string]any) + if first["url"] != "https://example.com/ref-only.png" { + t.Errorf("reference_images = %#v", references) + } + } + _, _ = writer.Write([]byte(`{"request_id":"upstream-video-ref-single"}`)) + case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-ref-single": + _, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-ref-single.mp4"}}`)) + default: + http.NotFound(writer, request) + } + })) + t.Cleanup(server.Close) + adapter, credential := newConsoleTestAdapter(t, server.URL) + result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Prompt: "animate", Duration: 6, AspectRatio: "16:9", Resolution: "720p", + ReferenceURLs: []string{"https://example.com/ref-only.png"}, + }) + if err != nil { + t.Fatal(err) + } + if result.URL != "https://vidgen.x.ai/result-ref-single.mp4" { + t.Fatalf("video result = %#v", result) + } +} + +func TestConsoleVideoRejectsImageWithReferences(t *testing.T) { + adapter, credential := newConsoleTestAdapter(t, "https://console.example") + _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Prompt: "animate", Duration: 6, AspectRatio: "16:9", Resolution: "720p", + ImageURL: "https://example.com/first.png", + ReferenceURLs: []string{"https://example.com/ref.png"}, + }) + if err == nil || !strings.Contains(err.Error(), "不能与") { + t.Fatalf("error = %v", err) + } +} + +func TestConsoleVideoPostsReferenceAudios(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if serveTestDPoPToken(t, writer, request) { + return + } + verifyTestDPoPProof(t, request) + writer.Header().Set("Content-Type", "application/json") + switch { + case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations": + var payload map[string]any + if err := json.NewDecoder(request.Body).Decode(&payload); err != nil { + t.Error(err) + } + if _, exists := payload["image"]; exists { + t.Errorf("image = %#v", payload["image"]) + } + references, ok := payload["reference_images"].([]any) + if !ok || len(references) != 1 { + t.Errorf("reference_images = %#v", payload["reference_images"]) + } else { + first, _ := references[0].(map[string]any) + if first["url"] != "https://example.com/person.png" { + t.Errorf("reference_images = %#v", references) + } + } + audios, ok := payload["reference_audios"].([]any) + if !ok || len(audios) != 1 { + t.Errorf("reference_audios = %#v", payload["reference_audios"]) + } else if first, _ := audios[0].(map[string]any); first["voice_id"] != "eve" { + t.Errorf("reference_audios = %#v", audios) + } + _, _ = writer.Write([]byte(`{"request_id":"upstream-video-ref-audio"}`)) + case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-ref-audio": + _, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-ref-audio.mp4","duration":8}}`)) + default: + http.NotFound(writer, request) + } + })) + t.Cleanup(server.Close) + adapter, credential := newConsoleTestAdapter(t, server.URL) + result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Prompt: "speak", Duration: 8, AspectRatio: "9:16", Resolution: "720p", + ReferenceURLs: []string{"https://example.com/person.png"}, + ReferenceAudios: []string{"eve"}, + }) + if err != nil { + t.Fatal(err) + } + if result.URL != "https://vidgen.x.ai/result-ref-audio.mp4" { + t.Fatalf("video result = %#v", result) + } +} + +// Measured upstream ceiling: 8 references answer 400 "Too many reference images: +// 8. Maximum allowed is 7." on both grok-imagine-video and grok-imagine-video-1.5. +func TestConsoleVideoRejectsTooManyReferenceImages(t *testing.T) { + adapter, credential := newConsoleTestAdapter(t, "https://console.example") + references := make([]string, consoleMaxVideoReferenceImages+1) + for i := range references { + references[i] = "https://example.com/" + strings.Repeat("x", i+1) + ".png" + } + _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Prompt: "animate", Duration: 6, ReferenceURLs: references, + }) + if err == nil || !strings.Contains(err.Error(), "最多支持") { + t.Fatalf("error = %v", err) + } +} + +func TestConsoleVideoRejectsTooManyCombinedImages(t *testing.T) { + adapter, credential := newConsoleTestAdapter(t, "https://console.example") + references := make([]string, consoleMaxVideoReferenceImages) + for i := range references { + references[i] = "https://example.com/" + strings.Repeat("y", i+1) + ".png" + } + _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Prompt: "animate", Duration: 6, + ImageURL: "https://example.com/first.png", ReferenceURLs: references, + }) + if err == nil || !(strings.Contains(err.Error(), "不能与") || strings.Contains(err.Error(), "最多支持")) { + t.Fatalf("error = %v", err) + } +} + +// Measured: grok-imagine-video with reference_images and duration=15 answers +// 400 "Duration 15s exceeds the maximum allowed for reference-to-video, which is +// 10s." The image field (image-to-video) and grok-imagine-video-1.5 both keep 15s. +func TestConsoleVideoRejectsLongReferenceDurationOnBaseModel(t *testing.T) { + adapter, credential := newConsoleTestAdapter(t, "https://console.example") + _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Prompt: "animate", Duration: 15, + ReferenceURLs: []string{"https://example.com/ref.png"}, + }) + if err == nil || !strings.Contains(err.Error(), "最长 10 秒") { + t.Fatalf("error = %v", err) + } +} + +// The same 15s request must stay allowed for grok-imagine-video-1.5. +func TestConsoleVideo15AllowsLongReferenceDuration(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if serveTestDPoPToken(t, writer, request) { + return + } + verifyTestDPoPProof(t, request) + writer.Header().Set("Content-Type", "application/json") + switch { + case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations": + _, _ = writer.Write([]byte(`{"request_id":"upstream-video-15s"}`)) + case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-15s": + _, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-15s.mp4"}}`)) + default: + http.NotFound(writer, request) + } + })) + t.Cleanup(server.Close) + adapter, credential := newConsoleTestAdapter(t, server.URL) + result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Model: "grok-imagine-video-1.5", Prompt: "animate", Duration: 15, + ReferenceURLs: []string{"https://example.com/ref.png"}, + }) + if err != nil { + t.Fatal(err) + } + if result.URL != "https://vidgen.x.ai/result-15s.mp4" { + t.Fatalf("video result = %#v", result) + } +} + +func TestConsoleVideoUsesImagineVideo15Model(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if serveTestDPoPToken(t, writer, request) { + return + } + verifyTestDPoPProof(t, request) + writer.Header().Set("Content-Type", "application/json") + switch { + case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations": + var payload map[string]any + if err := json.NewDecoder(request.Body).Decode(&payload); err != nil { + t.Error(err) + } + if payload["model"] != "grok-imagine-video-1.5" || payload["resolution"] != "1080p" { + t.Errorf("video payload = %#v", payload) + } + _, _ = writer.Write([]byte(`{"request_id":"upstream-video-15"}`)) + case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-15": + _, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-15.mp4"}}`)) + default: + http.NotFound(writer, request) + } + })) + t.Cleanup(server.Close) + adapter, credential := newConsoleTestAdapter(t, server.URL) + result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Model: "grok-imagine-video-1.5", Prompt: "animate", Duration: 6, AspectRatio: "16:9", Resolution: "1080p", + }) + if err != nil { + t.Fatal(err) + } + if result.URL != "https://vidgen.x.ai/result-15.mp4" { + t.Fatalf("video result = %#v", result) + } +} + +func TestConsoleVideo15Rejects1080pReferenceMode(t *testing.T) { + adapter, credential := newConsoleTestAdapter(t, "https://console.example") + _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Model: "grok-imagine-video-1.5", Prompt: "animate", Duration: 6, Resolution: "1080p", + ReferenceURLs: []string{"https://example.com/reference.png"}, + }) + if err == nil || !strings.Contains(err.Error(), "最高支持 720p") { + t.Fatalf("error = %v", err) + } +} + func TestParseConsoleVideoStatusRejectsUnknownState(t *testing.T) { if _, _, err := parseConsoleVideoStatus([]byte(`{"status":"mystery"}`), nil); err == nil || !strings.Contains(err.Error(), "状态无效") { t.Fatalf("unknown status error = %v", err) @@ -1477,3 +2084,99 @@ func (r *recordingConsoleEgressRepository) UpdateCount() int { defer r.mu.Unlock() return r.updates } + +func TestConsoleVideoEditPostsVideoAndPolls(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if serveTestDPoPToken(t, writer, request) { + return + } + verifyTestDPoPProof(t, request) + writer.Header().Set("Content-Type", "application/json") + switch { + case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/edits": + var payload map[string]any + if err := json.NewDecoder(request.Body).Decode(&payload); err != nil { + t.Error(err) + } + if payload["model"] != "grok-imagine-video" || payload["prompt"] != "add necklace" { + t.Errorf("edit payload = %#v", payload) + } + if _, exists := payload["duration"]; exists { + t.Errorf("edit payload must not include duration: %#v", payload) + } + video, ok := payload["video"].(map[string]any) + if !ok || video["url"] != "https://example.com/source.mp4" { + t.Errorf("edit video = %#v", payload["video"]) + } + _, _ = writer.Write([]byte(`{"request_id":"upstream-video-edit-1"}`)) + case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-edit-1": + _, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-edit.mp4"}}`)) + default: + http.NotFound(writer, request) + } + })) + t.Cleanup(server.Close) + adapter, credential := newConsoleTestAdapter(t, server.URL) + result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Model: "grok-imagine-video", Operation: provider.VideoOperationEdit, + Prompt: "add necklace", VideoURL: "https://example.com/source.mp4", + }) + if err != nil { + t.Fatal(err) + } + if result.URL != "https://vidgen.x.ai/result-edit.mp4" { + t.Fatalf("edit result = %#v", result) + } +} + +func TestConsoleVideoExtendPostsVideoAndPolls(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if serveTestDPoPToken(t, writer, request) { + return + } + verifyTestDPoPProof(t, request) + writer.Header().Set("Content-Type", "application/json") + switch { + case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/extensions": + var payload map[string]any + if err := json.NewDecoder(request.Body).Decode(&payload); err != nil { + t.Error(err) + } + if payload["model"] != "grok-imagine-video" || payload["duration"] != float64(4) || payload["prompt"] != "pan left" { + t.Errorf("extend payload = %#v", payload) + } + video, ok := payload["video"].(map[string]any) + if !ok || video["url"] != "https://example.com/source.mp4" { + t.Errorf("extend video = %#v", payload["video"]) + } + _, _ = writer.Write([]byte(`{"request_id":"upstream-video-extend-1"}`)) + case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-extend-1": + _, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-extend.mp4"}}`)) + default: + http.NotFound(writer, request) + } + })) + t.Cleanup(server.Close) + adapter, credential := newConsoleTestAdapter(t, server.URL) + result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Model: "grok-imagine-video", Operation: provider.VideoOperationExtend, + Prompt: "pan left", Duration: 4, VideoURL: "https://example.com/source.mp4", + }) + if err != nil { + t.Fatal(err) + } + if result.URL != "https://vidgen.x.ai/result-extend.mp4" { + t.Fatalf("extend result = %#v", result) + } +} + +func TestConsoleVideoEditRejectsNonImagineVideoModel(t *testing.T) { + adapter, credential := newConsoleTestAdapter(t, "http://127.0.0.1") + _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Model: "grok-imagine-video-1.5", Operation: provider.VideoOperationEdit, + Prompt: "x", VideoURL: "https://example.com/source.mp4", + }) + if err == nil || !strings.Contains(err.Error(), "grok-imagine-video") { + t.Fatalf("err = %v", err) + } +} diff --git a/backend/internal/infra/provider/console/definition.go b/backend/internal/infra/provider/console/definition.go index 94eb6e57..59cb4a18 100644 --- a/backend/internal/infra/provider/console/definition.go +++ b/backend/internal/infra/provider/console/definition.go @@ -18,6 +18,9 @@ func (a *Adapter) Definition() provider.Definition { modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit, modeldomain.CapabilityVideo, + modeldomain.CapabilityTTS, + modeldomain.CapabilitySTT, + modeldomain.CapabilityRealtime, }, Quota: provider.QuotaRemoteWindow, Credential: provider.CredentialSurface{ @@ -28,6 +31,7 @@ func (a *Adapter) Definition() provider.Definition { }, Media: provider.MediaSurface{ ImageGeneration: true, ImageEdit: true, VideoGeneration: true, + TTS: true, STT: true, Realtime: true, }, // Console shares the browser/clearance surface with Web. A 403 is // therefore normally an egress challenge, not proof that the SSO diff --git a/backend/internal/infra/provider/console/dpop.go b/backend/internal/infra/provider/console/dpop.go index fb6c6d2c..ffc50411 100644 --- a/backend/internal/infra/provider/console/dpop.go +++ b/backend/internal/infra/provider/console/dpop.go @@ -292,6 +292,23 @@ func (a *Adapter) doDPoPRequest( method, endpoint string, body []byte, accept string, +) (*http.Response, error) { + contentType := "" + if len(body) > 0 { + contentType = "application/json" + } + return a.doDPoPRequestWithContentType(ctx, credential, ssoToken, lease, method, endpoint, body, contentType, accept) +} + +func (a *Adapter) doDPoPRequestWithContentType( + ctx context.Context, + credential account.Credential, + ssoToken string, + lease *infraegress.Lease, + method, endpoint string, + body []byte, + contentType string, + accept string, ) (*http.Response, error) { for attempt := 0; attempt < 2; attempt++ { session, cacheKey, err := a.dpop.get(ctx, a, credential, ssoToken, lease) @@ -308,7 +325,10 @@ func (a *Adapter) doDPoPRequest( } applyBrowserHeaders(request, ssoToken, lease) if len(body) > 0 { - request.Header.Set("Content-Type", "application/json") + if strings.TrimSpace(contentType) == "" { + contentType = "application/json" + } + request.Header.Set("Content-Type", contentType) } if strings.TrimSpace(accept) != "" { request.Header.Set("Accept", accept) diff --git a/backend/internal/infra/provider/console/media.go b/backend/internal/infra/provider/console/media.go index 21d358a5..b0f04a2a 100644 --- a/backend/internal/infra/provider/console/media.go +++ b/backend/internal/infra/provider/console/media.go @@ -29,14 +29,31 @@ const ( consoleMediaOutputAttempts = 3 consoleVideoPollEvery = 2 * time.Second consoleMaxEditImages = 3 - consoleMaxVideoImages = 1 + // Upstream enforces the two video image inputs separately (measured against + // console.x.ai on both grok-imagine-video and grok-imagine-video-1.5): + // image = first frame, image-to-video, at most 1 + // reference_images = style/content references, reference-to-video, at most 7 + // 8 references answer 400 "Too many reference images: 8. Maximum allowed is 7." + // The two are mutually exclusive below and their limits are never summed, so a + // combined ceiling would accept payloads that upstream then rejects. + consoleMaxVideoFirstFrames = 1 + consoleMaxVideoReferenceImages = 7 ) type consoleMediaUpstreamError struct { - status int - summary string + status int + summary string + retryAfter time.Duration + requestScoped bool } +var ( + _ provider.HTTPStatusError = (*consoleMediaUpstreamError)(nil) + _ provider.RetryAfterError = (*consoleMediaUpstreamError)(nil) + _ provider.RequestScopedError = (*consoleMediaUpstreamError)(nil) + _ provider.PublicMessageError = (*consoleMediaUpstreamError)(nil) +) + func (e *consoleMediaUpstreamError) Error() string { if e == nil { return "" @@ -51,6 +68,24 @@ func (e *consoleMediaUpstreamError) HTTPStatusCode() int { return e.status } +func (e *consoleMediaUpstreamError) RetryAfterDuration() time.Duration { + if e == nil { + return 0 + } + return e.retryAfter +} + +func (e *consoleMediaUpstreamError) RequestScopedFailure() bool { + return e != nil && e.requestScoped +} + +func (e *consoleMediaUpstreamError) PublicErrorMessage() string { + if e == nil { + return "" + } + return e.summary +} + func (a *Adapter) GenerateImage(ctx context.Context, request provider.ImageGenerationRequest) (*provider.Response, error) { if !ResolveMedia(request.Model, modeldomain.CapabilityImage) { return invalidConsoleMediaRequest("模型不支持 Console 图片生成"), nil @@ -77,6 +112,10 @@ func (a *Adapter) GenerateImage(ctx context.Context, request provider.ImageGener if err != nil { return invalidConsoleMediaRequest(err.Error()), nil } + quality, err := normalizeConsoleImageQuality(request.Model, request.Quality) + if err != nil { + return invalidConsoleMediaRequest(err.Error()), nil + } payload := map[string]any{"model": request.Model, "prompt": request.Prompt, "n": count, "response_format": format} if ratio != "" { payload["aspect_ratio"] = ratio @@ -84,6 +123,9 @@ func (a *Adapter) GenerateImage(ctx context.Context, request provider.ImageGener if resolution != "" { payload["resolution"] = resolution } + if quality != "" { + payload["quality"] = quality + } return a.forwardConsoleMedia(ctx, request.Credential, "/images/generations", payload, format, count) } @@ -116,6 +158,10 @@ func (a *Adapter) EditImage(ctx context.Context, request provider.ImageEditReque if err != nil { return invalidConsoleMediaRequest(err.Error()), nil } + quality, err := normalizeConsoleImageQuality(request.Model, request.Quality) + if err != nil { + return invalidConsoleMediaRequest(err.Error()), nil + } images := make([]map[string]any, 0, len(request.ImageURLs)) for _, rawURL := range request.ImageURLs { value := strings.TrimSpace(rawURL) @@ -136,6 +182,9 @@ func (a *Adapter) EditImage(ctx context.Context, request provider.ImageEditReque if resolution != "" { payload["resolution"] = resolution } + if quality != "" { + payload["quality"] = quality + } return a.forwardConsoleMedia(ctx, request.Credential, "/images/edits", payload, format, count) } @@ -394,40 +443,148 @@ func trustedConsoleImageHost(host string) bool { } func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoRequest) (provider.VideoResult, error) { - if !ResolveMedia("grok-imagine-video", modeldomain.CapabilityVideo) { - return provider.VideoResult{}, errors.New("Console 视频模型未注册") + modelName := strings.TrimSpace(request.Model) + if modelName == "" { + modelName = "grok-imagine-video" } - if len(request.ReferenceURLs) > consoleMaxVideoImages { - return provider.VideoResult{}, fmt.Errorf("Console grok-imagine-video 最多支持 1 张首图,当前为 %d 张", len(request.ReferenceURLs)) + if !ResolveMedia(modelName, modeldomain.CapabilityVideo) { + return provider.VideoResult{}, fmt.Errorf("Console 视频模型未注册: %s", modelName) } - if request.Duration < 1 || request.Duration > 15 { - return provider.VideoResult{}, errors.New("duration 必须在 1 到 15 秒之间") + operation := request.Operation + if operation == "" { + operation = provider.VideoOperationGenerate } - if request.Resolution != "" && request.Resolution != "480p" && request.Resolution != "720p" { - return provider.VideoResult{}, errors.New("grok-imagine-video 仅支持 480p 或 720p") + switch operation { + case provider.VideoOperationGenerate, provider.VideoOperationEdit, provider.VideoOperationExtend: + default: + return provider.VideoResult{}, fmt.Errorf("不支持的视频操作: %s", operation) } - payload := map[string]any{ - "model": "grok-imagine-video", "duration": request.Duration, + // Official video edit/extension docs and model catalog only expose VIDEO input on + // grok-imagine-video. 1.5 is generation-oriented (TEXT/IMAGE/AUDIO) and is rejected here. + if operation != provider.VideoOperationGenerate && modelName != "grok-imagine-video" { + return provider.VideoResult{}, fmt.Errorf("%s 仅支持 grok-imagine-video", operation) + } + firstFrames, referenceImages := consoleVideoImageCounts(request) + if firstFrames > consoleMaxVideoFirstFrames { + return provider.VideoResult{}, fmt.Errorf("Console %s 最多支持 %d 张首帧图,当前为 %d 张", modelName, consoleMaxVideoFirstFrames, firstFrames) + } + if referenceImages > consoleMaxVideoReferenceImages { + return provider.VideoResult{}, fmt.Errorf("Console %s 最多支持 %d 张参考图,当前为 %d 张", modelName, consoleMaxVideoReferenceImages, referenceImages) + } + if operation == provider.VideoOperationGenerate { + if request.Duration < 1 || request.Duration > 15 { + return provider.VideoResult{}, errors.New("duration 必须在 1 到 15 秒之间") + } + // reference-to-video on the base model caps at 10s upstream; measured: + // grok-imagine-video + reference_images + duration=15 + // -> 400 "Duration 15s exceeds the maximum allowed for reference-to-video, which is 10s." + // image-to-video (the image field) and grok-imagine-video-1.5 both keep 15s, + // so the cap keys on reference_images plus the base model, not on duration alone. + if modelName == "grok-imagine-video" && referenceImages > 0 && request.Duration > 10 { + return provider.VideoResult{}, fmt.Errorf("%s 的参考图生视频最长 10 秒,当前为 %d 秒", modelName, request.Duration) + } + } else if operation == provider.VideoOperationExtend { + // Official /v1/videos/extensions defaults to 6s and accepts 2-10s. + if request.Duration == 0 { + request.Duration = 6 + } + if request.Duration < 2 || request.Duration > 10 { + return provider.VideoResult{}, errors.New("视频延长 duration 必须在 2 到 10 秒之间") + } + } else if request.Duration != 0 { + return provider.VideoResult{}, errors.New("视频编辑不支持 duration") + } + if request.Resolution == "1080p" { + if modelName != "grok-imagine-video-1.5" { + return provider.VideoResult{}, fmt.Errorf("%s 不支持 1080p", modelName) + } + if len(request.ReferenceURLs) > 0 { + return provider.VideoResult{}, errors.New("reference_images 模式最高支持 720p") + } + } else if request.Resolution != "" && request.Resolution != "480p" && request.Resolution != "720p" { + return provider.VideoResult{}, fmt.Errorf("%s 仅支持 480p、720p 或 1080p", modelName) + } + payload := map[string]any{"model": modelName} + if operation == provider.VideoOperationGenerate || operation == provider.VideoOperationExtend { + payload["duration"] = request.Duration } if prompt := strings.TrimSpace(request.Prompt); prompt != "" { payload["prompt"] = prompt } - if ratio := strings.TrimSpace(request.AspectRatio); ratio != "" { - payload["aspect_ratio"] = ratio - } - if resolution := strings.TrimSpace(request.Resolution); resolution != "" { - payload["resolution"] = resolution - } - if len(request.ReferenceURLs) == 1 { - value := strings.TrimSpace(request.ReferenceURLs[0]) - if !validConsoleMediaInputURL(value, "image") { - return provider.VideoResult{}, errors.New("视频首图必须是 HTTPS URL 或 image data URL") + if operation == provider.VideoOperationGenerate { + if ratio := strings.TrimSpace(request.AspectRatio); ratio != "" { + payload["aspect_ratio"] = ratio } - payload["image"] = map[string]any{"url": value} - } - if _, hasPrompt := payload["prompt"]; !hasPrompt { - if _, hasImage := payload["image"]; !hasImage { - return provider.VideoResult{}, errors.New("文本生视频必须提供 prompt;图片生视频可以省略 prompt") + if resolution := strings.TrimSpace(request.Resolution); resolution != "" { + payload["resolution"] = resolution + } + if imageURL := strings.TrimSpace(request.ImageURL); imageURL != "" { + if !validConsoleMediaInputURL(imageURL, "image") { + return provider.VideoResult{}, errors.New("视频首图必须是 HTTPS URL 或 image data URL") + } + payload["image"] = map[string]any{"url": imageURL} + } + if strings.TrimSpace(request.ImageURL) != "" && (len(request.ReferenceURLs) > 0 || len(request.ReferenceAudios) > 0) { + return provider.VideoResult{}, errors.New("image 不能与 reference_images/reference_audios 同时使用") + } + if len(request.ReferenceURLs) > 0 { + references := make([]map[string]any, 0, len(request.ReferenceURLs)) + for _, rawURL := range request.ReferenceURLs { + value := strings.TrimSpace(rawURL) + if !validConsoleMediaInputURL(value, "image") { + return provider.VideoResult{}, errors.New("每张视频参考图都必须是 HTTPS URL 或 image data URL") + } + references = append(references, map[string]any{"url": value}) + } + // A single reference must stay in reference_images; do not coerce to image. + payload["reference_images"] = references + } + if len(request.ReferenceAudios) > 0 { + if len(request.ReferenceAudios) > 3 { + return provider.VideoResult{}, errors.New("reference_audios 最多 3 个") + } + audios := make([]map[string]any, 0, len(request.ReferenceAudios)) + for _, raw := range request.ReferenceAudios { + voiceID := strings.TrimSpace(raw) + if voiceID == "" { + return provider.VideoResult{}, errors.New("reference_audios.voice_id 不能为空") + } + audios = append(audios, map[string]any{"voice_id": voiceID}) + } + payload["reference_audios"] = audios + } + hasReferenceMode := len(request.ReferenceURLs) > 0 || len(request.ReferenceAudios) > 0 + if hasReferenceMode { + if strings.TrimSpace(request.Prompt) == "" { + return provider.VideoResult{}, errors.New("参考图/参考音频视频必须提供 prompt") + } + if strings.EqualFold(strings.TrimSpace(request.Resolution), "1080p") { + return provider.VideoResult{}, errors.New("参考图视频 resolution 最高 720p") + } + } + if _, hasPrompt := payload["prompt"]; !hasPrompt { + if _, hasImage := payload["image"]; !hasImage { + if !hasReferenceMode { + return provider.VideoResult{}, errors.New("文本生视频必须提供 prompt;图片生视频可以省略 prompt") + } + } + } + } else { + prompt := strings.TrimSpace(request.Prompt) + if prompt == "" { + return provider.VideoResult{}, errors.New("视频编辑/延长必须提供 prompt") + } + videoURL := strings.TrimSpace(request.VideoURL) + if !validConsoleMediaInputURL(videoURL, "video") { + return provider.VideoResult{}, errors.New("输入视频必须是 HTTPS URL 或 video data URL") + } + payload["prompt"] = prompt + payload["video"] = map[string]any{"url": videoURL} + if strings.TrimSpace(request.ImageURL) != "" || len(request.ReferenceURLs) > 0 || len(request.ReferenceAudios) > 0 { + return provider.VideoResult{}, errors.New("视频编辑/延长不支持 image、reference_images 或 reference_audios") + } + if strings.TrimSpace(request.AspectRatio) != "" || strings.TrimSpace(request.Resolution) != "" { + return provider.VideoResult{}, errors.New("视频编辑/延长不支持 aspect_ratio 或 resolution") } } @@ -445,7 +602,14 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque return provider.VideoResult{}, err } baseURL := a.config().BaseURL - created, err := a.doConsoleVideoJSON(ctx, request.Credential, token, lease, http.MethodPost, consoleV1Endpoint(baseURL, "/videos/generations"), body) + createPath := "/videos/generations" + switch operation { + case provider.VideoOperationEdit: + createPath = "/videos/edits" + case provider.VideoOperationExtend: + createPath = "/videos/extensions" + } + created, err := a.doConsoleVideoJSON(ctx, request.Credential, token, lease, http.MethodPost, consoleV1Endpoint(baseURL, createPath), body) if err != nil { return provider.VideoResult{}, err } @@ -509,7 +673,7 @@ func (a *Adapter) doConsoleVideoJSON(ctx context.Context, credential account.Cre if !dpopRequired { a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, nil) } - return nil, newConsoleMediaUpstreamError(response.StatusCode, data) + return nil, newConsoleMediaUpstreamError(response.StatusCode, data, parseConsoleRetryAfterHeader(response.Header.Get("Retry-After"), time.Now().UTC())) } a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, nil) return data, nil @@ -603,6 +767,20 @@ func normalizeConsoleImageResolution(value string) (string, error) { return value, nil } +func normalizeConsoleImageQuality(model, value string) (string, error) { + value = strings.ToLower(strings.TrimSpace(value)) + if value == "" { + return "", nil + } + if strings.TrimSpace(model) != "grok-imagine-image-2.0" { + return "", errors.New("quality 仅支持 grok-imagine-image-2.0") + } + if value != "low" && value != "medium" { + return "", errors.New("quality 必须是 low 或 medium") + } + return value, nil +} + func resolveConsoleImageAspectRatio(aspectRatio, size string) (string, error) { value := strings.ToLower(strings.TrimSpace(aspectRatio)) if value == "" { @@ -677,7 +855,7 @@ func parseConsoleVideoStatus(body []byte, progress func(int)) (provider.VideoRes } } -func newConsoleMediaUpstreamError(status int, body []byte) error { +func newConsoleMediaUpstreamError(status int, body []byte, retryAfter time.Duration) error { message := "" var payload map[string]any if json.Unmarshal(body, &payload) == nil { @@ -685,22 +863,38 @@ func newConsoleMediaUpstreamError(status int, body []byte) error { if message == "" { message = safeConsoleMediaErrorValue(payload["message"]) } + if message == "" { + message = safeConsoleMediaErrorValue(payload["detail"]) + } } summary := fmt.Sprintf("Console 媒体上游返回 %d", status) if message != "" { summary += ": " + message } - return &consoleMediaUpstreamError{status: status, summary: summary} + if retryAfter <= 0 { + retryAfter = consoleRetryAfter(body) + } + return &consoleMediaUpstreamError{ + status: status, summary: summary, retryAfter: retryAfter, + requestScoped: status == http.StatusForbidden && provider.IsDPoPProofRequiredBody(body), + } } func safeConsoleMediaErrorValue(value any) string { if object, ok := value.(map[string]any); ok { - for _, key := range []string{"message", "code", "type"} { + for _, key := range []string{"message", "msg", "code", "type", "detail", "error_description"} { raw, exists := object[key] if !exists || raw == nil { continue } - if text := safeConsoleMediaText(fmt.Sprint(raw)); text != "" { + if text := safeConsoleMediaErrorValue(raw); text != "" { + return text + } + } + } + if values, ok := value.([]any); ok { + for _, item := range values { + if text := safeConsoleMediaErrorValue(item); text != "" { return text } } @@ -708,13 +902,24 @@ func safeConsoleMediaErrorValue(value any) string { if text, ok := value.(string); ok { return safeConsoleMediaText(text) } + switch value.(type) { + case json.Number, float64, float32, int, int64, int32, uint, uint64, uint32, bool: + return safeConsoleMediaText(fmt.Sprint(value)) + } return "" } func safeConsoleMediaText(value string) string { value = strings.Join(strings.Fields(value), " ") - if strings.Contains(strings.ToLower(value), "authorization") || strings.Contains(strings.ToLower(value), "cookie") { - return "上游拒绝请求" + lower := strings.ToLower(value) + for _, sensitive := range []string{ + "authorization", "cookie", "bearer ", + "access_token", "access-token", "refresh_token", "refresh-token", + "api_key", "api-key", "sso-rw", "cf_clearance", + } { + if strings.Contains(lower, sensitive) { + return "上游拒绝请求" + } } const limit = 160 if len(value) <= limit { @@ -731,3 +936,15 @@ func trustedConsoleVideoHost(host string) bool { host = strings.ToLower(strings.TrimSpace(host)) return host == "vidgen.x.ai" || strings.HasSuffix(host, ".vidgen.x.ai") } + +func consoleVideoImageCounts(request provider.VideoRequest) (firstFrames int, referenceImages int) { + if strings.TrimSpace(request.ImageURL) != "" { + firstFrames++ + } + for _, raw := range request.ReferenceURLs { + if strings.TrimSpace(raw) != "" { + referenceImages++ + } + } + return firstFrames, referenceImages +} diff --git a/backend/internal/infra/provider/console/normalize.go b/backend/internal/infra/provider/console/normalize.go index d6143594..2505ea97 100644 --- a/backend/internal/infra/provider/console/normalize.go +++ b/backend/internal/infra/provider/console/normalize.go @@ -229,12 +229,39 @@ func normalizeConsoleTools(payload map[string]any) bool { if enabled, ok := tool["enable_image_understanding"].(bool); ok { clean["enable_image_understanding"] = enabled } + // Forward the image-search toggle (enable_image_search) so clients + // can explicitly enable/disable it; absent when not requested. + if enabled, ok := tool["enable_image_search"].(bool); ok { + clean["enable_image_search"] = enabled + } result = append(result, clean) case "x_search": clean := map[string]any{"type": "x_search", "enable_video_understanding": true} if enabled, ok := tool["enable_video_understanding"].(bool); ok { clean["enable_video_understanding"] = enabled } + // Forward the X-search time bounds (from_date/to_date, YYYY-MM-DD). + // Invalid formats and empty strings are dropped; if from_date is + // later than to_date both are dropped to avoid an upstream 400. + for _, field := range []string{"from_date", "to_date"} { + text, ok := tool[field].(string) + if !ok || text == "" { + continue + } + if date, err := time.Parse("2006-01-02", text); err == nil && date.Format("2006-01-02") == text { + clean[field] = text + } + } + from, hasFrom := clean["from_date"].(string) + to, hasTo := clean["to_date"].(string) + if hasFrom && hasTo { + fromDate, _ := time.Parse("2006-01-02", from) + toDate, _ := time.Parse("2006-01-02", to) + if fromDate.After(toDate) { + delete(clean, "from_date") + delete(clean, "to_date") + } + } result = append(result, clean) case "function": name, _ := tool["name"].(string) diff --git a/backend/internal/infra/provider/console/voice.go b/backend/internal/infra/provider/console/voice.go new file mode 100644 index 00000000..f9b10898 --- /dev/null +++ b/backend/internal/infra/provider/console/voice.go @@ -0,0 +1,412 @@ +package console + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "mime/multipart" + "net/http" + "net/url" + "path" + "strconv" + "strings" + "time" + "unicode/utf8" + + "github.com/chenyme/grok2api/backend/internal/domain/account" + egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress" + "github.com/chenyme/grok2api/backend/internal/infra/provider" +) + +const ( + consoleVoiceBodyLimit = 64 << 20 + consoleVoiceAudioLimit = 128 << 20 +) + +func (a *Adapter) SynthesizeSpeech(ctx context.Context, request provider.TTSRequest) (provider.TTSResult, error) { + text := strings.TrimSpace(request.Text) + if text == "" { + return provider.TTSResult{}, invalidConsoleVoiceError("text 不能为空") + } + if utf8.RuneCountInString(text) > 15000 { + return provider.TTSResult{}, invalidConsoleVoiceError("text 最多 15000 个字符") + } + language := strings.TrimSpace(request.Language) + if language == "" { + return provider.TTSResult{}, invalidConsoleVoiceError("language 不能为空") + } + payload := map[string]any{"text": text, "language": language} + if voiceID := strings.TrimSpace(request.VoiceID); voiceID != "" { + payload["voice_id"] = voiceID + } + if format := normalizeTTSOutputFormat(request.OutputFormat); format != nil { + payload["output_format"] = format + } + if request.Speed > 0 { + payload["speed"] = request.Speed + } + if request.OptimizeStreamingLatency > 0 { + payload["optimize_streaming_latency"] = strconv.Itoa(request.OptimizeStreamingLatency) + } + if request.TextNormalization { + payload["text_normalization"] = true + } + if request.WithTimestamps { + payload["with_timestamps"] = true + } + response, err := a.forwardConsoleVoice(ctx, request.Credential, http.MethodPost, "/tts", payload, "application/json", "*/*") + if err != nil { + return provider.TTSResult{}, err + } + defer response.Body.Close() + if response.StatusCode < 200 || response.StatusCode >= 300 { + return provider.TTSResult{}, consoleVoiceResponseError(response) + } + contentType := strings.ToLower(strings.TrimSpace(response.Header.Get("Content-Type"))) + data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceAudioLimit+1)) + if err != nil { + return provider.TTSResult{}, err + } + if len(data) > consoleVoiceAudioLimit { + return provider.TTSResult{}, errors.New("Console TTS 响应超过安全上限") + } + if strings.Contains(contentType, "application/json") || request.WithTimestamps { + var envelope struct { + Audio string `json:"audio"` + ContentType string `json:"content_type"` + Duration float64 `json:"duration"` + AudioTimestamps *struct { + GraphChars []string `json:"graph_chars"` + GraphTimes []struct { + Start float64 `json:"start"` + End float64 `json:"end"` + } `json:"graph_times"` + } `json:"audio_timestamps"` + } + if err := json.Unmarshal(data, &envelope); err != nil { + if !strings.Contains(contentType, "application/json") { + return provider.TTSResult{Audio: data, ContentType: firstNonEmpty(contentType, "audio/mpeg")}, nil + } + return provider.TTSResult{}, fmt.Errorf("解析 Console TTS JSON 响应失败: %w", err) + } + audio, err := base64.StdEncoding.DecodeString(strings.TrimSpace(envelope.Audio)) + if err != nil { + return provider.TTSResult{}, fmt.Errorf("解码 Console TTS audio 失败: %w", err) + } + result := provider.TTSResult{ + Audio: audio, ContentType: firstNonEmpty(envelope.ContentType, contentType, "audio/mpeg"), + Duration: envelope.Duration, Base64Audio: envelope.Audio, JSONEnvelope: true, + } + if envelope.AudioTimestamps != nil { + times := make([]provider.TTSTimestampSpan, 0, len(envelope.AudioTimestamps.GraphTimes)) + for _, item := range envelope.AudioTimestamps.GraphTimes { + times = append(times, provider.TTSTimestampSpan{Start: item.Start, End: item.End}) + } + result.Timestamps = &provider.TTSTimestamps{ + GraphChars: append([]string(nil), envelope.AudioTimestamps.GraphChars...), + GraphTimes: times, + } + } + return result, nil + } + return provider.TTSResult{Audio: data, ContentType: firstNonEmpty(contentType, "audio/mpeg")}, nil +} + +func (a *Adapter) ListTTSVoices(ctx context.Context, credential account.Credential) ([]provider.VoiceInfo, error) { + response, err := a.forwardConsoleVoice(ctx, credential, http.MethodGet, "/tts/voices", nil, "", "application/json") + if err != nil { + return nil, err + } + defer response.Body.Close() + if response.StatusCode < 200 || response.StatusCode >= 300 { + return nil, consoleVoiceResponseError(response) + } + data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1)) + if err != nil { + return nil, err + } + var payload struct { + Voices []struct { + VoiceID string `json:"voice_id"` + Name string `json:"name"` + Language *string `json:"language"` + } `json:"voices"` + } + if err := json.Unmarshal(data, &payload); err != nil { + return nil, fmt.Errorf("解析 Console TTS voices 失败: %w", err) + } + result := make([]provider.VoiceInfo, 0, len(payload.Voices)) + for _, item := range payload.Voices { + language := "" + if item.Language != nil { + language = strings.TrimSpace(*item.Language) + } + result = append(result, provider.VoiceInfo{VoiceID: strings.TrimSpace(item.VoiceID), Name: strings.TrimSpace(item.Name), Language: language}) + } + return result, nil +} + +func (a *Adapter) GetTTSVoice(ctx context.Context, credential account.Credential, voiceID string) (provider.VoiceInfo, error) { + voiceID = strings.TrimSpace(voiceID) + if voiceID == "" { + return provider.VoiceInfo{}, invalidConsoleVoiceError("voice_id 不能为空") + } + response, err := a.forwardConsoleVoice(ctx, credential, http.MethodGet, "/tts/voices/"+url.PathEscape(voiceID), nil, "", "application/json") + if err != nil { + return provider.VoiceInfo{}, err + } + defer response.Body.Close() + if response.StatusCode < 200 || response.StatusCode >= 300 { + return provider.VoiceInfo{}, consoleVoiceResponseError(response) + } + data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1)) + if err != nil { + return provider.VoiceInfo{}, err + } + var payload struct { + VoiceID string `json:"voice_id"` + Name string `json:"name"` + Language *string `json:"language"` + } + if err := json.Unmarshal(data, &payload); err != nil { + return provider.VoiceInfo{}, fmt.Errorf("解析 Console TTS voice 失败: %w", err) + } + language := "" + if payload.Language != nil { + language = strings.TrimSpace(*payload.Language) + } + return provider.VoiceInfo{VoiceID: strings.TrimSpace(payload.VoiceID), Name: strings.TrimSpace(payload.Name), Language: language}, nil +} + +func (a *Adapter) TranscribeSpeech(ctx context.Context, request provider.STTRequest) (provider.STTResult, error) { + hasFile := len(request.FileData) > 0 + hasURL := strings.TrimSpace(request.URL) != "" + if hasFile == hasURL { + return provider.STTResult{}, invalidConsoleVoiceError("STT 必须提供 file 或 url 其中之一") + } + var body bytes.Buffer + writer := multipart.NewWriter(&body) + writeField := func(name, value string) error { + value = strings.TrimSpace(value) + if value == "" { + return nil + } + return writer.WriteField(name, value) + } + _ = writeField("audio_format", request.AudioFormat) + _ = writeField("sample_rate", request.SampleRate) + _ = writeField("language", request.Language) + if request.Format { + _ = writer.WriteField("format", "true") + } + if request.Multichannel { + _ = writer.WriteField("multichannel", "true") + } + if request.Channels > 0 { + _ = writer.WriteField("channels", strconv.Itoa(request.Channels)) + } + if request.Diarize { + _ = writer.WriteField("diarize", "true") + } + for _, term := range request.KeyTerms { + _ = writeField("keyterm", term) + } + if request.FillerWords { + _ = writer.WriteField("filler_words", "true") + } + if request.VADThreshold != nil { + _ = writer.WriteField("vad_threshold", strconv.FormatFloat(*request.VADThreshold, 'f', -1, 64)) + } + if modelName := strings.TrimSpace(request.Model); modelName != "" { + _ = writer.WriteField("model", modelName) + } + if hasURL { + _ = writer.WriteField("url", strings.TrimSpace(request.URL)) + } + if hasFile { + fileName := strings.TrimSpace(request.FileName) + if fileName == "" { + fileName = "audio.bin" + } + part, err := writer.CreateFormFile("file", path.Base(fileName)) + if err != nil { + return provider.STTResult{}, err + } + if _, err := part.Write(request.FileData); err != nil { + return provider.STTResult{}, err + } + } + if err := writer.Close(); err != nil { + return provider.STTResult{}, err + } + response, err := a.forwardConsoleVoiceBytes(ctx, request.Credential, http.MethodPost, "/stt", body.Bytes(), writer.FormDataContentType(), "application/json") + if err != nil { + return provider.STTResult{}, err + } + defer response.Body.Close() + if response.StatusCode < 200 || response.StatusCode >= 300 { + return provider.STTResult{}, consoleVoiceResponseError(response) + } + data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1)) + if err != nil { + return provider.STTResult{}, err + } + result, err := parseSTTResult(data) + if err != nil { + return provider.STTResult{}, err + } + result.RawJSON = append([]byte(nil), data...) + return result, nil +} + +func (a *Adapter) forwardConsoleVoice(ctx context.Context, credential account.Credential, method, pathValue string, payload any, contentType, accept string) (*http.Response, error) { + var body []byte + var err error + if payload != nil { + body, err = json.Marshal(payload) + if err != nil { + return nil, err + } + if contentType == "" { + contentType = "application/json" + } + } + return a.forwardConsoleVoiceBytes(ctx, credential, method, pathValue, body, contentType, accept) +} + +func (a *Adapter) forwardConsoleVoiceBytes(ctx context.Context, credential account.Credential, method, pathValue string, body []byte, contentType, accept string) (*http.Response, error) { + if strings.HasPrefix(strings.ToLower(strings.TrimSpace(contentType)), "multipart/") { + return a.forwardConsoleVoiceMultipart(ctx, credential, method, pathValue, body, contentType, accept) + } + token, err := a.cipher.Decrypt(credential.EncryptedAccessToken) + if err != nil { + return nil, err + } + cfg := a.config() + requestCtx, cancel := context.WithTimeout(ctx, time.Duration(cfg.TimeoutSeconds)*time.Second) + lease, err := a.egress.AcquireCredential(requestCtx, egressdomain.ScopeConsole, credential) + if err != nil { + cancel() + return nil, err + } + if accept == "" { + accept = "*/*" + } + response, err := a.doDPoPRequestWithContentType(requestCtx, credential, token, lease, method, consoleV1Endpoint(cfg.BaseURL, pathValue), body, contentType, accept) + if err != nil { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, 0, err) + lease.Release() + cancel() + return nil, err + } + response.Body = &releaseBody{ReadCloser: response.Body, release: func() { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, nil) + lease.Release() + cancel() + }} + return response, nil +} + +func (a *Adapter) forwardConsoleVoiceMultipart(ctx context.Context, credential account.Credential, method, pathValue string, body []byte, contentType, accept string) (*http.Response, error) { + token, err := a.cipher.Decrypt(credential.EncryptedAccessToken) + if err != nil { + return nil, err + } + cfg := a.config() + requestCtx, cancel := context.WithTimeout(ctx, time.Duration(cfg.TimeoutSeconds)*time.Second) + lease, err := a.egress.AcquireCredential(requestCtx, egressdomain.ScopeConsole, credential) + if err != nil { + cancel() + return nil, err + } + if accept == "" { + accept = "*/*" + } + response, err := a.doDPoPRequestWithContentType(requestCtx, credential, token, lease, method, consoleV1Endpoint(cfg.BaseURL, pathValue), body, contentType, accept) + if err != nil { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, 0, err) + lease.Release() + cancel() + return nil, err + } + response.Body = &releaseBody{ReadCloser: response.Body, release: func() { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, nil) + lease.Release() + cancel() + }} + return response, nil +} + +func normalizeTTSOutputFormat(format provider.TTSOutputFormat) map[string]any { + codec := strings.ToLower(strings.TrimSpace(format.Codec)) + if codec == "" && format.SampleRate == 0 && format.BitRate == 0 { + return nil + } + if codec == "" { + codec = "mp3" + } + result := map[string]any{"codec": codec} + if format.SampleRate > 0 { + result["sample_rate"] = format.SampleRate + } + if format.BitRate > 0 { + result["bit_rate"] = format.BitRate + } + return result +} + +func parseSTTResult(data []byte) (provider.STTResult, error) { + var payload struct { + Text string `json:"text"` + Language string `json:"language"` + Duration float64 `json:"duration"` + Words []struct { + Text string `json:"text"` + Start float64 `json:"start"` + End float64 `json:"end"` + Speaker *int `json:"speaker"` + } `json:"words"` + Channels []struct { + Index int `json:"index"` + Text string `json:"text"` + Words []struct { + Text string `json:"text"` + Start float64 `json:"start"` + End float64 `json:"end"` + Speaker *int `json:"speaker"` + } `json:"words"` + } `json:"channels"` + } + if err := json.Unmarshal(data, &payload); err != nil { + return provider.STTResult{}, fmt.Errorf("解析 Console STT 响应失败: %w", err) + } + result := provider.STTResult{Text: payload.Text, Language: payload.Language, Duration: payload.Duration} + for _, word := range payload.Words { + result.Words = append(result.Words, provider.STTWord{Text: word.Text, Start: word.Start, End: word.End, Speaker: word.Speaker}) + } + for _, channel := range payload.Channels { + item := provider.STTChannel{Index: channel.Index, Text: channel.Text} + for _, word := range channel.Words { + item.Words = append(item.Words, provider.STTWord{Text: word.Text, Start: word.Start, End: word.End, Speaker: word.Speaker}) + } + result.Channels = append(result.Channels, item) + } + return result, nil +} + +func consoleVoiceResponseError(response *http.Response) error { + data, _, err := provider.ReadDiagnosticBody(response.Body) + if err != nil { + return err + } + retryAfter := parseConsoleRetryAfterHeader(response.Header.Get("Retry-After"), time.Now().UTC()) + return newConsoleMediaUpstreamError(response.StatusCode, data, retryAfter) +} + +func invalidConsoleVoiceError(message string) error { + return &consoleMediaUpstreamError{status: http.StatusBadRequest, summary: message} +} diff --git a/backend/internal/infra/provider/console/voice_ws.go b/backend/internal/infra/provider/console/voice_ws.go new file mode 100644 index 00000000..dd9b029a --- /dev/null +++ b/backend/internal/infra/provider/console/voice_ws.go @@ -0,0 +1,184 @@ +package console + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + "time" + + fhttp "github.com/bogdanfinn/fhttp" + "github.com/bogdanfinn/websocket" + + egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress" + "github.com/chenyme/grok2api/backend/internal/infra/provider" +) + +// DialVoiceWebSocket opens an authenticated Console websocket for realtime or STT streaming. +func (a *Adapter) DialVoiceWebSocket(ctx context.Context, request provider.VoiceWebSocketRequest) (provider.VoiceWebSocketConn, func(), error) { + pathValue := strings.TrimSpace(request.Path) + if pathValue == "" || strings.Contains(pathValue, "://") || strings.Contains(pathValue, "..") { + return nil, nil, invalidConsoleVoiceError("voice websocket path 无效") + } + if !strings.HasPrefix(pathValue, "/") { + pathValue = "/" + pathValue + } + switch pathValue { + case "/realtime", "/stt": + default: + return nil, nil, invalidConsoleVoiceError("不支持的 voice websocket path") + } + + token, err := a.cipher.Decrypt(request.Credential.EncryptedAccessToken) + if err != nil { + return nil, nil, err + } + requestCtx, cancel := context.WithCancel(ctx) + lease, err := a.egress.AcquireCredential(requestCtx, egressdomain.ScopeConsole, request.Credential) + if err != nil { + cancel() + return nil, nil, err + } + + cleanup := func() { + lease.Release() + cancel() + } + + endpoint, err := a.voiceWebSocketEndpoint(pathValue, request.Model) + if err != nil { + cleanup() + return nil, nil, err + } + + proofEndpoint, err := voiceWebSocketProofEndpoint(endpoint) + if err != nil { + cleanup() + return nil, nil, err + } + for attempt := 0; attempt < 2; attempt++ { + session, cacheKey, sessionErr := a.dpop.get(requestCtx, a, request.Credential, token, lease) + if sessionErr != nil { + cleanup() + return nil, nil, sessionErr + } + + // The websocket dialer needs wss://, while DPoP protects the underlying + // HTTP Upgrade request and Console validates htu against https://. Signing + // the websocket URI itself produces a valid JWT with the wrong htu and the + // server rejects an otherwise healthy session with 401. + httpReq, requestErr := http.NewRequestWithContext(requestCtx, http.MethodGet, proofEndpoint, nil) + if requestErr != nil { + cleanup() + return nil, nil, requestErr + } + applyBrowserHeaders(httpReq, token, lease) + httpReq.Header.Set("Accept", "*/*") + httpReq.Header.Set("Sec-Fetch-Mode", "websocket") + httpReq.Header.Set("Sec-Fetch-Dest", "empty") + httpReq.Header.Set("Sec-Fetch-Site", "same-origin") + httpReq.Header.Set("Cache-Control", "no-cache") + httpReq.Header.Set("Pragma", "no-cache") + if requestErr := applyDPoPAuthorization(httpReq, session); requestErr != nil { + cleanup() + return nil, nil, requestErr + } + + headers := fhttp.Header{} + for key, values := range httpReq.Header { + for _, value := range values { + headers.Add(key, value) + } + } + + connection, response, dialErr := lease.DialWebSocket(requestCtx, endpoint, headers, 30*time.Second) + if dialErr == nil { + if response != nil && response.Body != nil { + _ = response.Body.Close() + } + if connection == nil { + cleanup() + return nil, nil, errors.New("Console voice websocket 连接为空") + } + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, http.StatusSwitchingProtocols, nil) + return connection, cleanup, nil + } + if response == nil { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, 0, dialErr) + cleanup() + return nil, nil, fmt.Errorf("拨号 Console voice websocket 失败: %w", dialErr) + } + status := response.StatusCode + var body []byte + if response.Body != nil { + body, _, _ = provider.ReadDiagnosticBody(response.Body) + _ = response.Body.Close() + } + if status == http.StatusUnauthorized { + a.dpop.invalidate(cacheKey, session.accessToken) + if attempt == 0 { + continue + } + } + dpopRequired := status == http.StatusForbidden && provider.IsDPoPProofRequiredBody(body) + if status == http.StatusForbidden && shouldInvalidateConsoleClearance(body) { + lease.InvalidateClearance() + } + if !dpopRequired { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, status, nil) + } + cleanup() + retryAfter := parseConsoleRetryAfterHeader(response.Header.Get("Retry-After"), time.Now().UTC()) + return nil, nil, newConsoleMediaUpstreamError(status, body, retryAfter) + } + cleanup() + return nil, nil, errors.New("Console voice websocket DPoP 重试状态无效") +} + +func (a *Adapter) voiceWebSocketEndpoint(pathValue, modelName string) (string, error) { + base := strings.TrimRight(strings.TrimSpace(a.config().BaseURL), "/") + if base == "" { + return "", errors.New("Console BaseURL 未配置") + } + endpoint, err := url.Parse(consoleV1Endpoint(base, pathValue)) + if err != nil { + return "", err + } + switch strings.ToLower(endpoint.Scheme) { + case "https": + endpoint.Scheme = "wss" + case "http": + endpoint.Scheme = "ws" + case "wss", "ws": + default: + return "", fmt.Errorf("不支持的 Console voice websocket scheme: %s", endpoint.Scheme) + } + values := endpoint.Query() + if modelName = strings.TrimSpace(modelName); modelName != "" { + values.Set("model", modelName) + } + endpoint.RawQuery = values.Encode() + return endpoint.String(), nil +} + +func voiceWebSocketProofEndpoint(endpoint string) (string, error) { + parsed, err := url.Parse(strings.TrimSpace(endpoint)) + if err != nil || parsed.Host == "" { + return "", errors.New("Console voice websocket endpoint 无效") + } + switch strings.ToLower(parsed.Scheme) { + case "wss": + parsed.Scheme = "https" + case "ws": + parsed.Scheme = "http" + case "https", "http": + default: + return "", fmt.Errorf("不支持的 Console voice websocket scheme: %s", parsed.Scheme) + } + return parsed.String(), nil +} + +// Ensure bogdanfinn websocket.Conn satisfies the provider contract at compile time. +var _ provider.VoiceWebSocketConn = (*websocket.Conn)(nil) diff --git a/backend/internal/infra/provider/definition.go b/backend/internal/infra/provider/definition.go index e68d30f0..fdd606b8 100644 --- a/backend/internal/infra/provider/definition.go +++ b/backend/internal/infra/provider/definition.go @@ -55,6 +55,9 @@ type MediaSurface struct { ImageGeneration bool ImageEdit bool VideoGeneration bool + TTS bool + STT bool + Realtime bool } // CredentialSurface 描述号池凭据的接入和维护方式。 @@ -131,7 +134,7 @@ func (d Definition) Validate() error { capabilities := make(map[modeldomain.Capability]struct{}, len(d.ModelCapabilities)) for _, capability := range d.ModelCapabilities { switch capability { - case modeldomain.CapabilityResponses, modeldomain.CapabilityChat, modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit, modeldomain.CapabilityVideo: + case modeldomain.CapabilityResponses, modeldomain.CapabilityChat, modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit, modeldomain.CapabilityVideo, modeldomain.CapabilityTTS, modeldomain.CapabilitySTT, modeldomain.CapabilityRealtime: default: return fmt.Errorf("Provider %s 声明了无效模型能力 %q", d.Provider, capability) } @@ -163,6 +166,9 @@ func (d Definition) Validate() error { {enabled: d.Media.ImageGeneration, capability: modeldomain.CapabilityImage, name: "图像生成"}, {enabled: d.Media.ImageEdit, capability: modeldomain.CapabilityImageEdit, name: "图像编辑"}, {enabled: d.Media.VideoGeneration, capability: modeldomain.CapabilityVideo, name: "视频生成"}, + {enabled: d.Media.TTS, capability: modeldomain.CapabilityTTS, name: "语音合成"}, + {enabled: d.Media.STT, capability: modeldomain.CapabilitySTT, name: "语音识别"}, + {enabled: d.Media.Realtime, capability: modeldomain.CapabilityRealtime, name: "实时语音"}, } for _, item := range mediaCapabilities { _, declared := capabilities[item.capability] diff --git a/backend/internal/infra/provider/definition_contract_test.go b/backend/internal/infra/provider/definition_contract_test.go index d9e79abc..a5431360 100644 --- a/backend/internal/infra/provider/definition_contract_test.go +++ b/backend/internal/infra/provider/definition_contract_test.go @@ -62,10 +62,10 @@ func TestProductionProviderDefinitionsMatchImplementedCapabilities(t *testing.T) }, { provider: account.ProviderConsole, catalog: provider.ModelCatalogStatic, quota: provider.QuotaRemoteWindow, - capabilities: []modeldomain.Capability{modeldomain.CapabilityResponses, modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit, modeldomain.CapabilityVideo}, + capabilities: []modeldomain.Capability{modeldomain.CapabilityResponses, modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit, modeldomain.CapabilityVideo, modeldomain.CapabilityTTS, modeldomain.CapabilitySTT, modeldomain.CapabilityRealtime}, credential: provider.CredentialSurface{AuthType: account.AuthTypeSSO, Import: true}, conversation: provider.ConversationSurface{Responses: true, ChatCompletions: true, Messages: true}, - media: provider.MediaSurface{ImageGeneration: true, ImageEdit: true, VideoGeneration: true}, + media: provider.MediaSurface{ImageGeneration: true, ImageEdit: true, VideoGeneration: true, TTS: true, STT: true, Realtime: true}, inference: provider.InferencePolicy{Usage: provider.UsageUpstream, RetryForbiddenAsEgress: true}, }, } diff --git a/backend/internal/infra/provider/provider.go b/backend/internal/infra/provider/provider.go index 358927b8..1ed13440 100644 --- a/backend/internal/infra/provider/provider.go +++ b/backend/internal/infra/provider/provider.go @@ -30,6 +30,29 @@ type HTTPStatusError interface { HTTPStatusCode() int } +// RetryAfterError preserves a safe upstream retry delay when an adapter cannot +// return a Response, for example when a WebSocket handshake is rejected. +type RetryAfterError interface { + error + RetryAfterDuration() time.Duration +} + +// RequestScopedError marks an upstream rejection that retrying with another +// account or egress cannot resolve. +type RequestScopedError interface { + error + RequestScopedFailure() bool +} + +// PublicMessageError exposes a deliberately sanitized message that may cross +// the public API boundary. Provider errors must opt in; arbitrary Error() +// strings can contain upstream response bodies, tokens, cookies, or request +// diagnostics and therefore are never returned to clients by default. +type PublicMessageError interface { + error + PublicErrorMessage() string +} + // ErrorHTTPStatus extracts the upstream HTTP status from a Provider error chain. func ErrorHTTPStatus(err error) (int, bool) { var statusError HTTPStatusError @@ -40,6 +63,33 @@ func ErrorHTTPStatus(err error) (int, bool) { return status, status > 0 } +// ErrorRetryAfter extracts a positive retry delay from an error chain. +func ErrorRetryAfter(err error) time.Duration { + var retryError RetryAfterError + if !errors.As(err, &retryError) { + return 0 + } + return max(0, retryError.RetryAfterDuration()) +} + +// IsRequestScopedError reports whether the Provider has positively classified +// the failure as request-scoped. +func IsRequestScopedError(err error) bool { + var requestError RequestScopedError + return errors.As(err, &requestError) && requestError.RequestScopedFailure() +} + +// ErrorPublicMessage extracts a message that the Provider has explicitly +// classified as safe for clients. +func ErrorPublicMessage(err error) (string, bool) { + var publicError PublicMessageError + if !errors.As(err, &publicError) { + return "", false + } + message := strings.TrimSpace(publicError.PublicErrorMessage()) + return message, message != "" +} + // MediaPostProcessingStage identifies a local processing stage that failed after media generation. type MediaPostProcessingStage string @@ -240,6 +290,17 @@ type QuotaSnapshot struct { SyncedAt time.Time } +// QuotaGroupSnapshot is an authoritative snapshot for a group of quota modes +// returned by one upstream request. Modes lists the complete local scope so +// callers can atomically remove products that the upstream explicitly reports +// as unavailable without touching unrelated quota windows. +type QuotaGroupSnapshot struct { + Group string + Modes []string + Windows []account.QuotaWindow + SyncedAt time.Time +} + type ImageGenerationRequest struct { Credential account.Credential Model string @@ -248,6 +309,7 @@ type ImageGenerationRequest struct { Size string AspectRatio string Resolution string + Quality string ResponseFormat string Streaming bool PartialImages int @@ -268,23 +330,47 @@ type ImageEditRequest struct { Size string AspectRatio string Resolution string + Quality string ResponseFormat string Streaming bool PartialImages int } +// VideoOperation selects the official xAI video endpoint family. +type VideoOperation = media.VideoOperation + +const ( + VideoOperationGenerate = media.VideoOperationGenerate + VideoOperationEdit = media.VideoOperationEdit + VideoOperationExtend = media.VideoOperationExtend +) + type VideoRequest struct { Credential account.Credential // Billing is used only to determine XAI eligibility in Build auto mode; nil means the account tier is unknown. Billing *account.Billing // JobID binds the local video job to XAI ZDR upload tickets and result assets. - JobID string - Prompt string - Duration int - AspectRatio string - Resolution string + JobID string + // Model is the selected upstream video model when the Provider supports more than one. + Model string + // Operation defaults to generate when empty. + Operation VideoOperation + Prompt string + Duration int + AspectRatio string + Resolution string + // ImageURL is the optional first-frame image (official "image" field). + ImageURL string + // ReferenceURLs are style/content references (official "reference_images"). + // A single reference must stay in reference_images and must not be coerced to image. + // Official docs forbid combining image with reference_images. ReferenceURLs []string - Progress func(int) + // ReferenceAudios are preset voice_ids for reference-to-video (official "reference_audios"). + // At most 3 entries; may be used alone or with reference_images. + ReferenceAudios []string + // VideoURL is required for edit/extend (official "video" field). + VideoURL string + Progress func(int) } type VideoResult struct { @@ -294,6 +380,91 @@ type VideoResult struct { AssetID string } +type TTSOutputFormat struct { + Codec string + SampleRate int + BitRate int +} + +type TTSRequest struct { + Credential account.Credential + Model string + Text string + VoiceID string + Language string + OutputFormat TTSOutputFormat + Speed float64 + OptimizeStreamingLatency int + TextNormalization bool + WithTimestamps bool +} + +type TTSTimestampSpan struct { + Start float64 + End float64 +} + +type TTSTimestamps struct { + GraphChars []string + GraphTimes []TTSTimestampSpan +} + +type TTSResult struct { + Audio []byte + ContentType string + Duration float64 + Base64Audio string + Timestamps *TTSTimestamps + JSONEnvelope bool +} + +type STTRequest struct { + Credential account.Credential + Model string + FileName string + FileMIME string + FileData []byte + URL string + AudioFormat string + SampleRate string + Language string + Format bool + Multichannel bool + Channels int + Diarize bool + KeyTerms []string + FillerWords bool + VADThreshold *float64 +} + +type STTWord struct { + Text string + Start float64 + End float64 + Speaker *int +} + +type STTChannel struct { + Index int + Text string + Words []STTWord +} + +type STTResult struct { + Text string + Language string + Duration float64 + Words []STTWord + Channels []STTChannel + RawJSON []byte +} + +type VoiceInfo struct { + VoiceID string + Name string + Language string +} + // RefreshedCredential represents rotated credentials returned by an OAuth refresh. type RefreshedCredential struct { EncryptedAccessToken string @@ -387,6 +558,20 @@ type QuotaAdapter interface { SyncQuotaMode(ctx context.Context, credential account.Credential, mode string) (account.QuotaWindow, error) } +// QuotaGroupAdapter is optional. It is used when one upstream endpoint returns +// several related quota products as one authoritative response. +type QuotaGroupAdapter interface { + Adapter + SyncQuotaGroup(ctx context.Context, credential account.Credential, group string) (QuotaGroupSnapshot, error) +} + +// QuotaRefreshMetadataAdapter maps a model to an internal refresh group. The +// group is scheduling metadata, not a routable quota mode. +type QuotaRefreshMetadataAdapter interface { + Adapter + QuotaRefreshGroup(upstreamModel string) string +} + // WebAccountSettingsAdapter defines upstream profile-setting capabilities for Grok Web SSO accounts. // This capability belongs only to the Web Provider; Build and Console must not emulate it through generic account logic. type WebAccountSettingsAdapter interface { @@ -426,6 +611,42 @@ type VideoContentDownloader interface { DownloadVideo(ctx context.Context, credential account.Credential, rawURL string) (io.ReadCloser, string, int64, error) } +// TTSAdapter synthesizes speech audio for text prompts. +type TTSAdapter interface { + Adapter + SynthesizeSpeech(ctx context.Context, request TTSRequest) (TTSResult, error) + ListTTSVoices(ctx context.Context, credential account.Credential) ([]VoiceInfo, error) + GetTTSVoice(ctx context.Context, credential account.Credential, voiceID string) (VoiceInfo, error) +} + +// STTAdapter transcribes audio into text. +type STTAdapter interface { + Adapter + TranscribeSpeech(ctx context.Context, request STTRequest) (STTResult, error) +} + +// VoiceWebSocketConn is a minimal duplex websocket used by voice streaming proxies. +type VoiceWebSocketConn interface { + ReadMessage() (messageType int, data []byte, err error) + WriteMessage(messageType int, data []byte) error + SetReadLimit(limit int64) + Close() error +} + +// VoiceWebSocketRequest dials an upstream voice websocket with provider auth. +type VoiceWebSocketRequest struct { + Credential account.Credential + // Path is a v1-relative path such as /realtime or /stt. + Path string + Model string +} + +// VoiceWebSocketAdapter dials official voice websocket endpoints with account auth. +type VoiceWebSocketAdapter interface { + Adapter + DialVoiceWebSocket(ctx context.Context, request VoiceWebSocketRequest) (VoiceWebSocketConn, func(), error) +} + type RoutingMetadataAdapter interface { Adapter QuotaMode(upstreamModel string) string @@ -607,6 +828,21 @@ func (r *Registry) Validate() error { return fmt.Errorf("Provider %s 声明视频能力但未实现适配器", value) } } + if definition.Media.TTS { + if _, ok := adapter.(TTSAdapter); !ok { + return fmt.Errorf("Provider %s 声明语音合成能力但未实现适配器", value) + } + } + if definition.Media.STT { + if _, ok := adapter.(STTAdapter); !ok { + return fmt.Errorf("Provider %s 声明语音识别能力但未实现适配器", value) + } + } + if definition.Media.Realtime { + if _, ok := adapter.(VoiceWebSocketAdapter); !ok { + return fmt.Errorf("Provider %s 声明实时语音能力但未实现 WebSocket 适配器", value) + } + } } return nil } @@ -749,6 +985,15 @@ func (r *Registry) Quota(value account.Provider) (QuotaAdapter, bool) { return result, ok } +func (r *Registry) QuotaGroup(value account.Provider) (QuotaGroupAdapter, bool) { + adapter, ok := r.Get(value) + if !ok { + return nil, false + } + result, ok := adapter.(QuotaGroupAdapter) + return result, ok +} + // WebAccountSettings returns the Grok Web-specific account profile settings capability. func (r *Registry) WebAccountSettings() (WebAccountSettingsAdapter, bool) { adapter, ok := r.Get(account.ProviderWeb) @@ -771,6 +1016,18 @@ func (r *Registry) QuotaMode(value account.Provider, upstreamModel string) strin return metadata.QuotaMode(upstreamModel) } +func (r *Registry) QuotaRefreshGroup(value account.Provider, upstreamModel string) string { + adapter, ok := r.Get(value) + if !ok { + return "" + } + metadata, ok := adapter.(QuotaRefreshMetadataAdapter) + if !ok { + return "" + } + return metadata.QuotaRefreshGroup(upstreamModel) +} + func (r *Registry) TierOrder(value account.Provider, upstreamModel string) []account.WebTier { adapter, ok := r.Get(value) if !ok { @@ -827,6 +1084,33 @@ func (r *Registry) Videos(value account.Provider) (VideoAdapter, bool) { return result, ok } +func (r *Registry) TTS(value account.Provider) (TTSAdapter, bool) { + adapter, ok := r.Get(value) + if !ok { + return nil, false + } + result, ok := adapter.(TTSAdapter) + return result, ok +} + +func (r *Registry) STT(value account.Provider) (STTAdapter, bool) { + adapter, ok := r.Get(value) + if !ok { + return nil, false + } + result, ok := adapter.(STTAdapter) + return result, ok +} + +func (r *Registry) VoiceWebSocket(value account.Provider) (VoiceWebSocketAdapter, bool) { + adapter, ok := r.Get(value) + if !ok { + return nil, false + } + result, ok := adapter.(VoiceWebSocketAdapter) + return result, ok +} + // CredentialRejection 表示上游响应或错误是否构成「凭据被拒」的稳定判定。 // 与网关 UpstreamFailure 的 CredentialRejected / PermanentAccountDenial / SpendingLimitBlocked 分类保持一致, // 供 account.Service 等非网关路径复用同一套失效收敛语义。 diff --git a/backend/internal/infra/provider/web/adapter.go b/backend/internal/infra/provider/web/adapter.go index 0d39acc9..a487e154 100644 --- a/backend/internal/infra/provider/web/adapter.go +++ b/backend/internal/infra/provider/web/adapter.go @@ -115,6 +115,13 @@ func (a *Adapter) QuotaMode(upstreamModel string) string { return "" } +func (a *Adapter) QuotaRefreshGroup(upstreamModel string) string { + if spec, ok := Resolve(upstreamModel); ok && account.IsWebImagineQuotaMode(spec.Mode) { + return account.QuotaGroupWebImagine + } + return "" +} + func (a *Adapter) TierOrder(upstreamModel string) []account.WebTier { spec, ok := Resolve(upstreamModel) if !ok { @@ -136,11 +143,15 @@ func (a *Adapter) PricingModel(upstreamModel string) string { if spec.Capability == modeldomain.CapabilityChat { return "grok-4.5" } - // Public Web image names carry the -lite suffix to distinguish them from + // Public Web image names use the -2.0 suffix to distinguish them from // Console routes. Billing continues to use the upstream xAI model name. if spec.Capability == modeldomain.CapabilityImage { return spec.UpstreamModel } + // Dedicated Web edit upstream keeps a stable billing name. + if spec.Capability == modeldomain.CapabilityImageEdit { + return "grok-imagine-image-edit" + } return spec.PublicID } return upstreamModel diff --git a/backend/internal/infra/provider/web/catalog.go b/backend/internal/infra/provider/web/catalog.go index 83bf552c..af43af45 100644 --- a/backend/internal/infra/provider/web/catalog.go +++ b/backend/internal/infra/provider/web/catalog.go @@ -19,10 +19,13 @@ var catalog = []ModelSpec{ {PublicID: "grok-chat-auto", UpstreamModel: "grok-chat-auto", Capability: modeldomain.CapabilityChat, Mode: "auto", MinimumTier: account.WebTierSuper}, {PublicID: "grok-chat-expert", UpstreamModel: "grok-chat-expert", Capability: modeldomain.CapabilityChat, Mode: "expert", MinimumTier: account.WebTierSuper}, {PublicID: "grok-chat-heavy", UpstreamModel: "grok-chat-heavy", Capability: modeldomain.CapabilityChat, Mode: "heavy", MinimumTier: account.WebTierHeavy}, + // Web generation is exposed with a -lite suffix so it remains visibly + // distinct from the Console resource API. Image editing is a separate + // Super-only upstream model and must not be advertised on Basic routes. {PublicID: "grok-imagine-image-lite", UpstreamModel: "grok-imagine-image", ProtocolModel: "imagine-lite", Capability: modeldomain.CapabilityImage, Mode: "fast", MinimumTier: account.WebTierBasic}, - {PublicID: "grok-imagine-image-quality-lite", UpstreamModel: "grok-imagine-image-quality", ProtocolModel: "imagine", Capability: modeldomain.CapabilityImage, MinimumTier: account.WebTierSuper}, - {PublicID: "grok-imagine-image-edit", UpstreamModel: "imagine-image-edit", Capability: modeldomain.CapabilityImageEdit, MinimumTier: account.WebTierSuper}, - {PublicID: "grok-imagine-video", UpstreamModel: "grok-imagine-video", ProtocolModel: "imagine-video-gen", Capability: modeldomain.CapabilityVideo, MinimumTier: account.WebTierSuper}, + {PublicID: "grok-imagine-image-quality-lite", UpstreamModel: "grok-imagine-image-quality", ProtocolModel: "imagine", Capability: modeldomain.CapabilityImage, Mode: "image_pro", MinimumTier: account.WebTierBasic}, + {PublicID: "grok-imagine-image-edit", UpstreamModel: "imagine-image-edit", Capability: modeldomain.CapabilityImageEdit, Mode: "image_edit", MinimumTier: account.WebTierSuper}, + {PublicID: "grok-imagine-video", UpstreamModel: "grok-imagine-video", ProtocolModel: "imagine-video-gen", Capability: modeldomain.CapabilityVideo, Mode: "video", MinimumTier: account.WebTierSuper}, } func Catalog() []ModelSpec { return append([]ModelSpec(nil), catalog...) } diff --git a/backend/internal/infra/provider/web/image.go b/backend/internal/infra/provider/web/image.go index 45ce0a79..a94f198a 100644 --- a/backend/internal/infra/provider/web/image.go +++ b/backend/internal/infra/provider/web/image.go @@ -274,6 +274,9 @@ func numberAsInt(value any) (int, bool) { } func (a *Adapter) GenerateImage(ctx context.Context, request provider.ImageGenerationRequest) (*provider.Response, error) { + if strings.TrimSpace(request.Quality) != "" { + return invalidImageRequest("Grok Web 图片模型不支持 quality") + } count := request.Count if count <= 0 { count = 1 @@ -675,6 +678,9 @@ func (a *Adapter) generateWSImage(ctx context.Context, request provider.ImageGen } func (a *Adapter) EditImage(ctx context.Context, request provider.ImageEditRequest) (*provider.Response, error) { + if strings.TrimSpace(request.Quality) != "" { + return invalidImageRequest("Grok Web 图片模型不支持 quality") + } if len(request.ImageURLs) == 0 || len(request.ImageURLs) > 8 { return jsonProviderResponse(http.StatusBadRequest, map[string]any{"error": map[string]any{"message": "image 数量必须在 1 到 8 之间", "type": "invalid_request_error"}}), nil } diff --git a/backend/internal/infra/provider/web/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index 474a1be5..2377d375 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -37,34 +37,42 @@ import ( func TestCatalogMatchesSupportedSurface(t *testing.T) { values := Catalog() - if len(values) != 8 { + requiredModels := []string{"grok-chat-fast", "grok-chat-auto", "grok-chat-expert", "grok-chat-heavy", "grok-imagine-image-lite", "grok-imagine-image-quality-lite", "grok-imagine-image-edit", "grok-imagine-video"} + if len(values) != len(requiredModels) { t.Fatalf("catalog size = %d", len(values)) } publicIDs := make(map[string]struct{}, len(values)) - upstreamIDs := make(map[string]struct{}, len(values)) + routeKeys := make(map[string]struct{}, len(values)) for _, value := range values { - if _, exists := publicIDs[value.PublicID]; exists { - t.Fatalf("duplicate public model: %s", value.PublicID) - } - if _, exists := upstreamIDs[value.UpstreamModel]; exists { - t.Fatalf("duplicate route upstream model: %s", value.UpstreamModel) + routeKey := value.PublicID + "|" + string(value.Capability) + if _, exists := routeKeys[routeKey]; exists { + t.Fatalf("duplicate public model capability: %s", routeKey) } + routeKeys[routeKey] = struct{}{} publicIDs[value.PublicID] = struct{}{} - upstreamIDs[value.UpstreamModel] = struct{}{} } - for _, required := range []string{"grok-chat-fast", "grok-chat-auto", "grok-chat-expert", "grok-chat-heavy", "grok-imagine-image-lite", "grok-imagine-image-quality-lite", "grok-imagine-image-edit", "grok-imagine-video"} { + for _, required := range requiredModels { if _, exists := publicIDs[required]; !exists { t.Fatalf("missing supported model: %s", required) } } - for _, removed := range []string{"grok-imagine-image", "grok-imagine-image-quality", "grok-imagine-image-speed", "grok-imagine-image-pro"} { + for _, required := range []string{ + "grok-imagine-image-lite|image", + "grok-imagine-image-quality-lite|image", + "grok-imagine-image-edit|image_edit", + } { + if _, exists := routeKeys[required]; !exists { + t.Fatalf("missing supported route: %s", required) + } + } + for _, removed := range []string{"grok-imagine-image", "grok-imagine-image-quality", "grok-imagine-image-2.0", "grok-imagine-image-quality-2.0", "grok-imagine-image-speed", "grok-imagine-image-pro"} { if _, exists := publicIDs[removed]; exists { t.Fatalf("obsolete image model remains: %s", removed) } } } -func TestWebImageLitePublicNamesPreserveGatewayModels(t *testing.T) { +func TestWebImagePublicNamesPreserveGatewayModels(t *testing.T) { tests := map[string]string{ "grok-imagine-image": "grok-imagine-image-lite", "grok-imagine-image-quality": "grok-imagine-image-quality-lite", @@ -74,10 +82,14 @@ func TestWebImageLitePublicNamesPreserveGatewayModels(t *testing.T) { if !ok { t.Fatalf("missing upstream model %s", upstreamModel) } - if spec.PublicID != publicID || spec.UpstreamModel != upstreamModel { + if spec.PublicID != publicID || spec.UpstreamModel != upstreamModel || spec.Capability != modeldomain.CapabilityImage { t.Fatalf("resolved %s as %#v", upstreamModel, spec) } } + spec, ok := Resolve("imagine-image-edit") + if !ok || spec.PublicID != "grok-imagine-image-edit" || spec.Capability != modeldomain.CapabilityImageEdit { + t.Fatalf("edit upstream resolved as %#v ok=%v", spec, ok) + } } func TestParseMediaPostResponsePreservesStatusAndPostID(t *testing.T) { @@ -1014,7 +1026,7 @@ func TestWebMediaUpstreamDiagnosticLogsStageHeadersWithoutBodyPreview(t *testing } } -func TestChatModelsUseLowestSufficientTierFirst(t *testing.T) { +func TestModelsUseLowestSufficientTierFirst(t *testing.T) { adapter := &Adapter{} tests := []struct { model string @@ -1024,6 +1036,10 @@ func TestChatModelsUseLowestSufficientTierFirst(t *testing.T) { {model: "grok-chat-auto", want: []account.WebTier{account.WebTierSuper, account.WebTierHeavy}}, {model: "grok-chat-expert", want: []account.WebTier{account.WebTierSuper, account.WebTierHeavy}}, {model: "grok-chat-heavy", want: []account.WebTier{account.WebTierHeavy}}, + {model: "grok-imagine-image", want: []account.WebTier{account.WebTierBasic, account.WebTierSuper, account.WebTierHeavy}}, + {model: "grok-imagine-image-quality", want: []account.WebTier{account.WebTierBasic, account.WebTierSuper, account.WebTierHeavy}}, + {model: "imagine-image-edit", want: []account.WebTier{account.WebTierSuper, account.WebTierHeavy}}, + {model: "grok-imagine-video", want: []account.WebTier{account.WebTierSuper, account.WebTierHeavy}}, } for _, test := range tests { got := adapter.TierOrder(test.model) @@ -1047,12 +1063,27 @@ func TestOnlyChatModelsExposeRateLimitModes(t *testing.T) { } continue } + if isImagineQuotaMode(spec.Mode) { + continue + } if spec.Mode != "" { t.Fatalf("media model %s must not expose chat quota mode %q", spec.PublicID, spec.Mode) } } } +func TestQuotaRefreshGroupSeparatesImagineEndpointFromLiteChatQuota(t *testing.T) { + adapter := &Adapter{} + if got := adapter.QuotaRefreshGroup("grok-imagine-image"); got != "" { + t.Fatalf("lite refresh group = %q", got) + } + for _, model := range []string{"grok-imagine-image-quality", "imagine-image-edit", "grok-imagine-video"} { + if got := adapter.QuotaRefreshGroup(model); got != account.QuotaGroupWebImagine { + t.Fatalf("QuotaRefreshGroup(%q) = %q", model, got) + } + } +} + func TestConsumeUpstreamChatFixture(t *testing.T) { fixture := strings.Join([]string{ `data: {"result":{"conversation":{"conversationId":"conv_1"}}}`, diff --git a/backend/internal/infra/provider/web/quota.go b/backend/internal/infra/provider/web/quota.go index f7268d43..eb47bd6a 100644 --- a/backend/internal/infra/provider/web/quota.go +++ b/backend/internal/infra/provider/web/quota.go @@ -21,37 +21,53 @@ import ( const weeklyQuotaMode = "weekly" func (a *Adapter) SyncQuota(ctx context.Context, credential account.Credential) (provider.QuotaSnapshot, error) { - windows := make([]account.QuotaWindow, 0, 2) + chatWindows := make([]account.QuotaWindow, 0, 2) autoWindow, autoErr := a.SyncQuotaMode(ctx, credential, "auto") if errors.Is(autoErr, provider.ErrUnauthorized) { return provider.QuotaSnapshot{}, autoErr } if autoErr == nil { - windows = append(windows, autoWindow) + chatWindows = append(chatWindows, autoWindow) } fastWindow, fastErr := a.SyncQuotaMode(ctx, credential, "fast") if errors.Is(fastErr, provider.ErrUnauthorized) { return provider.QuotaSnapshot{}, fastErr } if fastErr == nil { - windows = append(windows, fastWindow) + chatWindows = append(chatWindows, fastWindow) } - if len(windows) > 0 { - tier, _ := resolveWebTierFromQuota(credential.WebTier, windows, false) + imagineSnapshot, imagineErr := a.SyncQuotaGroup(ctx, credential, account.QuotaGroupWebImagine) + if imagineErr != nil { + // A full refresh replaces every stored window. Never return a partial + // snapshot, otherwise a transient Imagine failure would erase the last + // known authoritative media quotas. + return provider.QuotaSnapshot{}, imagineErr + } + if len(chatWindows) > 0 { + tier, _ := resolveWebTierFromQuota(credential.WebTier, chatWindows, false) + var windows []account.QuotaWindow // Basic/未知账号没有付费周池,避免为每次完整同步额外访问付费端点。 // 只有模式额度已经确认付费等级时才读取 weekly 作为权威额度。 if tier == account.WebTierSuper || tier == account.WebTierHeavy { if weekly, weeklyErr := a.syncWeeklyCredits(ctx, credential); weeklyErr == nil { - windows = []account.QuotaWindow{weekly} + // 周池覆盖 chat 模式窗口,但保留 imagine 窗口供前端展示与触顶判定。 + kept := make([]account.QuotaWindow, 0, 1+len(imagineSnapshot.Windows)) + kept = append(kept, weekly) + kept = append(kept, imagineSnapshot.Windows...) + windows = kept } } + if windows == nil { + windows = append(chatWindows, imagineSnapshot.Windows...) + } return provider.QuotaSnapshot{Tier: tier, Windows: windows, SyncedAt: time.Now().UTC()}, nil } // 模式端点暂不可用时,仅已确认的付费账号允许用 weekly 兜底; // Basic/Auto 不能凭周额度探测提权,也不应制造无意义的付费端点流量。 if credential.WebTier == account.WebTierSuper || credential.WebTier == account.WebTierHeavy { if weekly, weeklyErr := a.syncWeeklyCredits(ctx, credential); weeklyErr == nil { - return provider.QuotaSnapshot{Tier: credential.WebTier, Windows: []account.QuotaWindow{weekly}, SyncedAt: time.Now().UTC()}, nil + kept := append([]account.QuotaWindow{weekly}, imagineSnapshot.Windows...) + return provider.QuotaSnapshot{Tier: credential.WebTier, Windows: kept, SyncedAt: time.Now().UTC()}, nil } else { return provider.QuotaSnapshot{}, weeklyErr } @@ -62,6 +78,141 @@ func (a *Adapter) SyncQuota(ctx context.Context, credential account.Credential) return provider.QuotaSnapshot{}, autoErr } +// SyncQuotaGroup refreshes the authoritative Web Imagine quota group. The +// upstream endpoint returns every media product in one response, so callers +// must persist the snapshot atomically instead of treating its fields as four +// independent requests. +func (a *Adapter) SyncQuotaGroup(ctx context.Context, credential account.Credential, group string) (provider.QuotaGroupSnapshot, error) { + if group != account.QuotaGroupWebImagine { + return provider.QuotaGroupSnapshot{}, fmt.Errorf("unsupported Web quota group %q", group) + } + cfg := a.config() + token, err := a.cipher.Decrypt(credential.EncryptedAccessToken) + if err != nil { + return provider.QuotaGroupSnapshot{}, err + } + lease, err := a.egress.AcquireCredential(ctx, domainegress.ScopeWeb, credential) + if err != nil { + return provider.QuotaGroupSnapshot{}, err + } + defer lease.Release() + endpoint := cfg.BaseURL + "/rest/media/imagine/quota_info" + requestCtx, cancel := context.WithTimeout(ctx, time.Duration(cfg.QuotaTimeoutSeconds)*time.Second) + defer cancel() + request, err := http.NewRequestWithContext(requestCtx, http.MethodPost, endpoint, bytes.NewReader([]byte("{}"))) + if err != nil { + return provider.QuotaGroupSnapshot{}, err + } + request.Header = buildHeaders(token, lease, "application/json") + applyAppHeaders(request.Header, cfg.BaseURL, cfg.BaseURL+"/imagine") + a.applySignedStatsig(requestCtx, request, token, lease) + response, err := lease.DoDeferredForbidden(request) + if err != nil { + a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, 0, err) + return provider.QuotaGroupSnapshot{}, err + } + body, err := io.ReadAll(io.LimitReader(response.Body, 4<<20)) + _ = response.Body.Close() + if err != nil { + return provider.QuotaGroupSnapshot{}, err + } + if response.StatusCode == http.StatusUnauthorized { + return provider.QuotaGroupSnapshot{}, provider.ErrUnauthorized + } + if response.StatusCode == http.StatusForbidden && provider.IsDefinitiveAccountBlockBody(body) { + return provider.QuotaGroupSnapshot{}, fmt.Errorf("%w: account blocked", provider.ErrUnauthorized) + } + if response.StatusCode < 200 || response.StatusCode >= 300 { + a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, response.StatusCode, nil) + return provider.QuotaGroupSnapshot{}, fmt.Errorf("Grok Web Imagine 配额接口返回 %d", response.StatusCode) + } + a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, response.StatusCode, nil) + now := time.Now().UTC() + windows, err := decodeImagineQuotaSnapshot(body, credential.ID, now) + if err != nil { + return provider.QuotaGroupSnapshot{}, err + } + return provider.QuotaGroupSnapshot{ + Group: account.QuotaGroupWebImagine, Modes: account.WebImagineQuotaModes(), Windows: windows, SyncedAt: now, + }, nil +} + +type imagineQuotaProduct struct { + Available *bool `json:"available"` + RemainingQueries *int `json:"remainingQueries"` + WindowSizeSeconds *int `json:"windowSizeSeconds"` + NextAvailableAt *time.Time `json:"nextAvailableAt"` +} + +func isImagineQuotaMode(mode string) bool { + return account.IsWebImagineQuotaMode(mode) +} + +func decodeImagineQuotaSnapshot(body []byte, accountID uint64, now time.Time) ([]account.QuotaWindow, error) { + var fields map[string]json.RawMessage + if err := json.Unmarshal(body, &fields); err != nil { + return nil, fmt.Errorf("解析 Grok Web Imagine 配额: %w", err) + } + products := []struct { + field string + mode string + }{ + {"image", ""}, // lite uses the chat fast/weekly quota path. + {"imagePro", account.QuotaModeWebImagePro}, + {"imageEdit", account.QuotaModeWebImageEdit}, + {"video", account.QuotaModeWebVideo}, + {"video720p", account.QuotaModeWebVideo720p}, + } + windows := make([]account.QuotaWindow, 0, 4) + for _, item := range products { + raw, ok := fields[item.field] + if !ok { + return nil, fmt.Errorf("Grok Web Imagine 配额响应缺少字段 %s", item.field) + } + if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) { + continue + } + var product imagineQuotaProduct + if err := json.Unmarshal(raw, &product); err != nil { + return nil, fmt.Errorf("解析 Grok Web Imagine 配额字段 %s: %w", item.field, err) + } + if product.Available == nil { + return nil, fmt.Errorf("Grok Web Imagine 配额字段 %s 结构不完整", item.field) + } + if item.mode == "" { + continue + } + if *product.Available && (product.RemainingQueries == nil || product.WindowSizeSeconds == nil) { + return nil, fmt.Errorf("Grok Web Imagine 配额字段 %s 结构不完整", item.field) + } + remaining := 0 + if product.RemainingQueries != nil { + remaining = max(0, *product.RemainingQueries) + } + windowSeconds := 86400 + if product.WindowSizeSeconds != nil { + windowSeconds = *product.WindowSizeSeconds + } + if windowSeconds <= 0 { + return nil, fmt.Errorf("Grok Web Imagine 配额字段 %s 的 windowSizeSeconds 无效", item.field) + } + var resetAt *time.Time + if product.NextAvailableAt != nil { + value := product.NextAvailableAt.UTC() + resetAt = &value + } else if !*product.Available || remaining == 0 { + value := now.Add(time.Duration(windowSeconds) * time.Second) + resetAt = &value + } + windows = append(windows, account.QuotaWindow{ + AccountID: accountID, Mode: item.mode, Remaining: remaining, Total: 0, + WindowSeconds: windowSeconds, ResetAt: resetAt, SyncedAt: &now, + Source: account.QuotaSourceUpstream, UpdatedAt: now, + }) + } + return windows, nil +} + func resolveWebTierFromQuota(current account.WebTier, windows []account.QuotaWindow, weeklyAvailable bool) (account.WebTier, bool) { if len(windows) > 0 { tier, known := inferWebTierFromQuota(windows) @@ -126,6 +277,18 @@ func (a *Adapter) SyncQuotaMode(ctx context.Context, credential account.Credenti if mode == weeklyQuotaMode { return a.syncWeeklyCredits(ctx, credential) } + if account.IsWebImagineQuotaMode(mode) { + snapshot, err := a.SyncQuotaGroup(ctx, credential, account.QuotaGroupWebImagine) + if err != nil { + return account.QuotaWindow{}, err + } + for _, w := range snapshot.Windows { + if w.Mode == mode { + return w, nil + } + } + return account.QuotaWindow{}, fmt.Errorf("imagine 配额响应缺少 %s", mode) + } cfg := a.config() token, err := a.cipher.Decrypt(credential.EncryptedAccessToken) if err != nil { diff --git a/backend/internal/infra/provider/web/quota_test.go b/backend/internal/infra/provider/web/quota_test.go index a1ad19b0..9c7e8bab 100644 --- a/backend/internal/infra/provider/web/quota_test.go +++ b/backend/internal/infra/provider/web/quota_test.go @@ -9,6 +9,7 @@ import ( "math" "net/http" "net/http/httptest" + "strings" "sync" "sync/atomic" "testing" @@ -77,6 +78,8 @@ func TestSyncQuotaFetchesWeeklyOnlyAfterPaidTierIsConfirmed(t *testing.T) { var weeklyCalls atomic.Int64 server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { switch request.URL.Path { + case "/rest/media/imagine/quota_info": + writeEmptyImagineQuota(writer) case "/grok_api_v2.GrokBuildBilling/GetGrokCreditsConfig": weeklyCalls.Add(1) writer.Header().Set("Content-Type", "application/grpc-web+proto") @@ -386,6 +389,8 @@ func TestSyncQuotaCorrectsStoredSuperFromFreshWebQuota(t *testing.T) { var weeklyCalls atomic.Int64 server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { switch request.URL.Path { + case "/rest/media/imagine/quota_info": + writeEmptyImagineQuota(writer) case "/grok_api_v2.GrokBuildBilling/GetGrokCreditsConfig": weeklyCalls.Add(1) http.Error(writer, "not available", http.StatusNotFound) @@ -440,3 +445,63 @@ func TestSyncQuotaCorrectsStoredSuperFromFreshWebQuota(t *testing.T) { t.Fatalf("basic account probed weekly endpoint %d times", weeklyCalls.Load()) } } + +func writeEmptyImagineQuota(writer http.ResponseWriter) { + writer.Header().Set("Content-Type", "application/json") + _, _ = writer.Write([]byte(`{"image":null,"imageEdit":null,"imagePro":null,"video":null,"video720p":null}`)) +} + +func TestDecodeImagineQuotaSnapshotMatchesObservedProtocol(t *testing.T) { + now := time.Date(2026, 8, 13, 8, 0, 0, 0, time.UTC) + body := []byte(`{ + "image": null, + "imageEdit": null, + "imagePro": {"available":true,"remainingQueries":4,"windowSizeSeconds":86400}, + "video": null, + "video720p": {"available":true,"remainingQueries":1,"windowSizeSeconds":86400} + }`) + windows, err := decodeImagineQuotaSnapshot(body, 42, now) + if err != nil { + t.Fatal(err) + } + if len(windows) != 2 { + t.Fatalf("windows = %#v", windows) + } + if windows[0].Mode != account.QuotaModeWebImagePro || windows[0].Remaining != 4 || windows[0].Total != 0 || windows[0].ResetAt != nil { + t.Fatalf("image_pro = %#v", windows[0]) + } + if windows[1].Mode != account.QuotaModeWebVideo720p || windows[1].Remaining != 1 || windows[1].Total != 0 || windows[1].ResetAt != nil { + t.Fatalf("video_720p = %#v", windows[1]) + } +} + +func TestDecodeImagineQuotaSnapshotRequiresCompleteResponse(t *testing.T) { + now := time.Now().UTC() + _, err := decodeImagineQuotaSnapshot([]byte(`{"image":null,"imageEdit":null,"imagePro":null,"video":null}`), 42, now) + if err == nil || !strings.Contains(err.Error(), "video720p") { + t.Fatalf("err = %v", err) + } +} + +func TestDecodeImagineQuotaSnapshotAcceptsExplicitUnavailableProduct(t *testing.T) { + now := time.Now().UTC() + windows, err := decodeImagineQuotaSnapshot([]byte(`{ + "image":null,"imageEdit":{"available":false},"imagePro":null,"video":null,"video720p":null + }`), 42, now) + if err != nil { + t.Fatal(err) + } + if len(windows) != 1 || windows[0].Mode != account.QuotaModeWebImageEdit || windows[0].Remaining != 0 || windows[0].ResetAt == nil { + t.Fatalf("windows = %#v", windows) + } +} + +func TestDecodeImagineQuotaSnapshotRejectsIncompleteAvailableProduct(t *testing.T) { + now := time.Now().UTC() + _, err := decodeImagineQuotaSnapshot([]byte(`{ + "image":null,"imageEdit":null,"imagePro":{"available":true},"video":null,"video720p":null + }`), 42, now) + if err == nil || !strings.Contains(err.Error(), "imagePro") { + t.Fatalf("err = %v", err) + } +} diff --git a/backend/internal/infra/provider/web/video.go b/backend/internal/infra/provider/web/video.go index 2289eb25..c0c502a6 100644 --- a/backend/internal/infra/provider/web/video.go +++ b/backend/internal/infra/provider/web/video.go @@ -219,8 +219,17 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque } defer lease.Release() parentID := "" - references := make([]string, 0, len(request.ReferenceURLs)) + rawReferences := make([]string, 0, 1+len(request.ReferenceURLs)) + if imageURL := strings.TrimSpace(request.ImageURL); imageURL != "" { + rawReferences = append(rawReferences, imageURL) + } for _, rawReference := range request.ReferenceURLs { + if value := strings.TrimSpace(rawReference); value != "" { + rawReferences = append(rawReferences, value) + } + } + references := make([]string, 0, len(rawReferences)) + for _, rawReference := range rawReferences { reference, referenceErr := a.prepareVideoReference(ctx, cfg, lease, token, rawReference) if referenceErr != nil { return provider.VideoResult{}, referenceErr diff --git a/backend/internal/pkg/tunnelproxy/tunnelproxy.go b/backend/internal/pkg/tunnelproxy/tunnelproxy.go new file mode 100644 index 00000000..c6314036 --- /dev/null +++ b/backend/internal/pkg/tunnelproxy/tunnelproxy.go @@ -0,0 +1,745 @@ +package tunnelproxy + +import ( + "context" + "crypto/tls" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "github.com/Asutorufa/yuhaiin/pkg/net/netapi" + "github.com/Asutorufa/yuhaiin/pkg/net/proxy/trojan" + "github.com/Asutorufa/yuhaiin/pkg/net/proxy/vless" + "github.com/Asutorufa/yuhaiin/pkg/net/proxy/vmess" + "github.com/Asutorufa/yuhaiin/pkg/protos/node/protocol" + "github.com/coder/websocket" + "github.com/google/uuid" + sscore "github.com/shadowsocks/go-shadowsocks2/core" + "github.com/shadowsocks/go-shadowsocks2/socks" +) + +type Config struct { + Scheme string + Server string + Credential string + Method string + AlterID int + Cipher string + Transport string + TLS bool + ServerName string + Insecure bool + ALPN []string + WebSocketHost string + WebSocketPath string + CanonicalProxyURL string +} + +const tunnelHandshakeTimeout = 10 * time.Second + +func IsSupportedScheme(scheme string) bool { + switch strings.ToLower(strings.TrimSpace(scheme)) { + case "trojan", "vless", "ss", "vmess": + return true + default: + return false + } +} + +func Normalize(value string) (string, error) { + config, err := Parse(value) + if err != nil { + return "", err + } + return config.CanonicalProxyURL, nil +} + +func Parse(value string) (Config, error) { + value = strings.TrimSpace(value) + if strings.IndexFunc(value, func(character rune) bool { return character < 0x20 || character == 0x7f }) >= 0 { + return Config{}, errors.New("隧道代理地址包含控制字符") + } + scheme, _, ok := strings.Cut(value, "://") + if !ok || !IsSupportedScheme(scheme) { + return Config{}, errors.New("不支持的隧道代理协议") + } + switch strings.ToLower(scheme) { + case "ss": + return parseShadowsocks(value) + case "vmess": + return parseVMess(value) + default: + return parseUserInfoProxy(value) + } +} + +func parseUserInfoProxy(value string) (Config, error) { + parsed, err := url.Parse(value) + if err != nil || parsed.Hostname() == "" || parsed.User == nil { + return Config{}, errors.New("隧道代理地址格式无效") + } + scheme := strings.ToLower(parsed.Scheme) + credential := parsed.User.Username() + if credential == "" { + return Config{}, errors.New("隧道代理凭据不能为空") + } + if _, hasPassword := parsed.User.Password(); hasPassword { + return Config{}, errors.New("隧道代理凭据格式无效") + } + if parsed.Path != "" && parsed.Path != "/" { + return Config{}, errors.New("隧道代理地址路径无效") + } + server, err := canonicalServer(parsed.Hostname(), parsed.Port()) + if err != nil { + return Config{}, err + } + query := parsed.Query() + transport := strings.ToLower(firstNonEmpty(query.Get("type"), query.Get("network"))) + if transport == "" || transport == "none" { + transport = "tcp" + } + if transport == "websocket" { + transport = "ws" + } + if transport != "tcp" && transport != "ws" { + return Config{}, fmt.Errorf("暂不支持 %s 传输", transport) + } + if flow := strings.TrimSpace(query.Get("flow")); flow != "" { + return Config{}, fmt.Errorf("暂不支持 VLESS flow %q", flow) + } + if scheme == "vless" { + parsedUUID, err := uuid.Parse(credential) + if err != nil { + return Config{}, errors.New("VLESS UUID 无效") + } + credential = parsedUUID.String() + if encryption := strings.ToLower(strings.TrimSpace(query.Get("encryption"))); encryption != "" && encryption != "none" { + return Config{}, errors.New("VLESS encryption 必须为 none") + } + } + security := strings.ToLower(strings.TrimSpace(query.Get("security"))) + tlsEnabled := scheme == "trojan" + switch security { + case "", "tls": + if security == "tls" { + tlsEnabled = true + } + case "none": + tlsEnabled = false + default: + return Config{}, fmt.Errorf("暂不支持 %s security %q", strings.ToUpper(scheme), security) + } + if headerType := strings.ToLower(strings.TrimSpace(query.Get("headerType"))); headerType != "" && headerType != "none" { + return Config{}, fmt.Errorf("暂不支持 %s headerType %q", strings.ToUpper(scheme), headerType) + } + insecure, err := queryBool(query, "allowInsecure", "insecure", "skip-cert-verify") + if err != nil { + return Config{}, err + } + serverName := firstNonEmpty(query.Get("sni"), query.Get("peer"), parsed.Hostname()) + wsHost := firstNonEmpty(query.Get("host"), serverName) + if err := validateWebSocketHost(wsHost); transport == "ws" && err != nil { + return Config{}, err + } + wsPath := query.Get("path") + if wsPath == "" { + wsPath = "/" + } else if !strings.HasPrefix(wsPath, "/") { + wsPath = "/" + wsPath + } + if transport == "tcp" && (query.Get("path") != "" || query.Get("host") != "") { + return Config{}, errors.New("TCP 隧道不能包含 WebSocket host/path") + } + config := Config{ + Scheme: scheme, Server: server, Credential: credential, Transport: transport, + TLS: tlsEnabled, ServerName: serverName, Insecure: insecure, + ALPN: splitList(query.Get("alpn")), WebSocketHost: wsHost, WebSocketPath: wsPath, + } + config.CanonicalProxyURL = canonicalUserInfoProxyURL(config) + if err := validateConfig(config); err != nil { + return Config{}, fmt.Errorf("创建 %s 隧道配置: %w", strings.ToUpper(scheme), err) + } + return config, nil +} + +func canonicalUserInfoProxyURL(config Config) string { + query := make(url.Values) + query.Set("type", config.Transport) + if config.TLS { + query.Set("security", "tls") + } else { + query.Set("security", "none") + } + if config.Scheme == "vless" { + query.Set("encryption", "none") + } + query.Set("sni", config.ServerName) + if config.Insecure { + query.Set("allowInsecure", "1") + } + if len(config.ALPN) != 0 { + query.Set("alpn", strings.Join(config.ALPN, ",")) + } + if config.Transport == "ws" { + query.Set("host", config.WebSocketHost) + query.Set("path", config.WebSocketPath) + } + return (&url.URL{ + Scheme: config.Scheme, + User: url.User(config.Credential), + Host: config.Server, + RawQuery: query.Encode(), + }).String() +} + +func parseShadowsocks(value string) (Config, error) { + payload := value[len("ss://"):] + if before, _, found := strings.Cut(payload, "#"); found { + payload = before + } + if before, rawQuery, found := strings.Cut(payload, "?"); found { + query, err := url.ParseQuery(rawQuery) + if err != nil { + return Config{}, errors.New("Shadowsocks 查询参数无效") + } + if plugin := strings.TrimSpace(query.Get("plugin")); plugin != "" { + return Config{}, errors.New("暂不支持 Shadowsocks plugin") + } + if len(query) != 0 { + return Config{}, errors.New("Shadowsocks 查询参数无效") + } + payload = before + } + var userPart, serverPart string + if separator := strings.LastIndex(payload, "@"); separator >= 0 { + userPart, serverPart = payload[:separator], payload[separator+1:] + decoded, err := url.PathUnescape(userPart) + if err != nil { + return Config{}, errors.New("Shadowsocks 凭据无效") + } + if !strings.Contains(decoded, ":") { + decoded, err = decodeBase64String(decoded) + if err != nil { + return Config{}, errors.New("Shadowsocks 凭据不是有效的 Base64") + } + } + userPart = decoded + } else { + decoded, err := decodeBase64String(payload) + if err != nil { + return Config{}, errors.New("旧式 Shadowsocks 地址不是有效的 Base64") + } + separator := strings.LastIndex(decoded, "@") + if separator < 0 { + return Config{}, errors.New("旧式 Shadowsocks 地址格式无效") + } + userPart, serverPart = decoded[:separator], decoded[separator+1:] + } + method, password, ok := strings.Cut(userPart, ":") + if !ok || strings.TrimSpace(method) == "" || password == "" { + return Config{}, errors.New("Shadowsocks method/password 不能为空") + } + method = strings.ToLower(strings.TrimSpace(method)) + switch method { + case "aes-128-gcm", "aes-256-gcm", "chacha20-ietf-poly1305": + default: + return Config{}, fmt.Errorf("暂不支持 Shadowsocks method %q", method) + } + serverURL, err := url.Parse("ss://" + serverPart) + if err != nil || serverURL.User != nil || (serverURL.Path != "" && serverURL.Path != "/") || serverURL.RawQuery != "" || serverURL.Fragment != "" { + return Config{}, errors.New("Shadowsocks 服务器地址无效") + } + server, err := canonicalServer(serverURL.Hostname(), serverURL.Port()) + if err != nil { + return Config{}, err + } + credential := method + ":" + password + config := Config{ + Scheme: "ss", Server: server, Credential: password, Method: method, Transport: "tcp", + CanonicalProxyURL: "ss://" + base64.RawURLEncoding.EncodeToString([]byte(credential)) + "@" + server, + } + if err := validateConfig(config); err != nil { + return Config{}, fmt.Errorf("创建 Shadowsocks 隧道配置: %w", err) + } + return config, nil +} + +type vmessShare struct { + Version string `json:"v,omitempty"` + Address string `json:"add"` + Port string `json:"port"` + UUID string `json:"id"` + AlterID string `json:"aid"` + Cipher string `json:"scy,omitempty"` + Network string `json:"net"` + TLS string `json:"tls,omitempty"` + ServerName string `json:"sni,omitempty"` + Host string `json:"host,omitempty"` + Path string `json:"path,omitempty"` + AllowInsecure bool `json:"allowInsecure,omitempty"` +} + +func parseVMess(value string) (Config, error) { + payload := value[len("vmess://"):] + if before, _, found := strings.Cut(payload, "#"); found { + payload = before + } + decoded, err := decodeBase64Bytes(payload) + if err != nil { + return Config{}, errors.New("VMess 配置不是有效的 Base64") + } + var raw map[string]any + if err := json.Unmarshal(decoded, &raw); err != nil { + return Config{}, errors.New("VMess 配置不是有效的 JSON") + } + address := jsonString(raw, "add") + port := jsonString(raw, "port") + server, err := canonicalServer(address, port) + if err != nil { + return Config{}, fmt.Errorf("VMess %w", err) + } + parsedUUID, err := uuid.Parse(jsonString(raw, "id")) + if err != nil { + return Config{}, errors.New("VMess UUID 无效") + } + userID := parsedUUID.String() + alterID, err := strconv.Atoi(firstNonEmpty(jsonString(raw, "aid"), "0")) + if err != nil || alterID < 0 || alterID > 65535 { + return Config{}, errors.New("VMess alterId 无效") + } + cipher := strings.ToLower(firstNonEmpty(jsonString(raw, "scy"), jsonString(raw, "security"), "auto")) + switch cipher { + case "auto", "aes-128-gcm", "chacha20-poly1305", "none": + default: + return Config{}, fmt.Errorf("暂不支持 VMess cipher %q", cipher) + } + transport := strings.ToLower(firstNonEmpty(jsonString(raw, "net"), "tcp")) + if transport == "websocket" { + transport = "ws" + } + if transport != "tcp" && transport != "ws" { + return Config{}, fmt.Errorf("暂不支持 VMess %s 传输", transport) + } + if headerType := strings.ToLower(jsonString(raw, "type")); headerType != "" && headerType != "none" { + return Config{}, fmt.Errorf("暂不支持 VMess header type %q", headerType) + } + tlsMode := strings.ToLower(jsonString(raw, "tls")) + if tlsMode != "" && tlsMode != "none" && tlsMode != "tls" { + return Config{}, fmt.Errorf("暂不支持 VMess TLS 模式 %q", tlsMode) + } + tlsEnabled := tlsMode == "tls" + serverName := firstNonEmpty(jsonString(raw, "sni"), address) + host := firstNonEmpty(jsonString(raw, "host"), serverName) + if err := validateWebSocketHost(host); transport == "ws" && err != nil { + return Config{}, err + } + path := jsonString(raw, "path") + if path == "" { + path = "/" + } else if !strings.HasPrefix(path, "/") { + path = "/" + path + } + if transport == "tcp" && (jsonString(raw, "path") != "" || jsonString(raw, "host") != "") { + return Config{}, errors.New("VMess TCP 隧道不能包含 WebSocket host/path") + } + insecure, err := jsonBool(raw, "allowInsecure") + if err != nil { + return Config{}, err + } + share := vmessShare{ + Version: "2", Address: address, Port: port, UUID: userID, AlterID: strconv.Itoa(alterID), Cipher: cipher, + Network: transport, ServerName: serverName, AllowInsecure: insecure, + } + if transport == "ws" { + share.Host = host + share.Path = path + } + if tlsEnabled { + share.TLS = "tls" + } + canonicalJSON, err := json.Marshal(share) + if err != nil { + return Config{}, err + } + config := Config{ + Scheme: "vmess", Server: server, Credential: userID, AlterID: alterID, Cipher: cipher, + Transport: transport, TLS: tlsEnabled, ServerName: serverName, Insecure: insecure, + WebSocketHost: host, WebSocketPath: path, + CanonicalProxyURL: "vmess://" + base64.RawStdEncoding.EncodeToString(canonicalJSON), + } + if err := validateConfig(config); err != nil { + return Config{}, fmt.Errorf("创建 VMess 隧道配置: %w", err) + } + return config, nil +} + +type Dialer struct { + proxy netapi.Proxy + shadowsocksCipher sscore.StreamConnCipher + server string +} + +func NewDialer(value string) (*Dialer, error) { + config, err := Parse(value) + if err != nil { + return nil, err + } + if config.Scheme == "ss" { + cipher, err := sscore.PickCipher(config.Method, nil, config.Credential) + if err != nil { + return nil, err + } + return &Dialer{shadowsocksCipher: cipher, server: config.Server}, nil + } + proxy, err := buildProxy(config) + if err != nil { + return nil, err + } + return &Dialer{proxy: proxy}, nil +} + +func (d *Dialer) Dial(network, address string) (net.Conn, error) { + return d.DialContext(context.Background(), network, address) +} + +func (d *Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) { + if d == nil || (d.proxy == nil && d.shadowsocksCipher == nil) { + return nil, errors.New("隧道代理拨号器未初始化") + } + if !strings.HasPrefix(network, "tcp") { + return nil, fmt.Errorf("隧道代理不支持网络 %q", network) + } + if d.shadowsocksCipher != nil { + return d.dialShadowsocks(ctx, address) + } + target, err := netapi.ParseAddress(network, address) + if err != nil { + return nil, err + } + return d.proxy.Conn(ctx, target) +} + +func (d *Dialer) dialShadowsocks(ctx context.Context, address string) (net.Conn, error) { + target := socks.ParseAddr(address) + if target == nil { + return nil, errors.New("Shadowsocks 目标地址无效") + } + connection, err := newServerNetDialer().DialContext(ctx, "tcp", d.server) + if err != nil { + return nil, err + } + connection = d.shadowsocksCipher.StreamConn(connection) + if _, err := connection.Write(target); err != nil { + _ = connection.Close() + return nil, fmt.Errorf("写入 Shadowsocks 目标地址: %w", err) + } + return connection, nil +} + +func validateConfig(config Config) error { + if config.Scheme == "ss" { + _, err := sscore.PickCipher(config.Method, nil, config.Credential) + return err + } + _, err := buildProxy(config) + return err +} + +func buildProxy(config Config) (netapi.Proxy, error) { + var current netapi.Proxy = &serverDialer{address: config.Server} + if config.Transport == "ws" { + current = &websocketProxy{config: config, dialer: current} + } else if config.TLS { + current = &tlsProxy{config: config, dialer: current} + } + switch config.Scheme { + case "trojan": + protocolConfig := &protocol.Trojan{} + protocolConfig.SetPassword(config.Credential) + return trojan.NewClient(protocolConfig, current) + case "vless": + protocolConfig := &protocol.Vless{} + protocolConfig.SetUuid(config.Credential) + return newOwnedVLESSProxy(protocolConfig, current) + case "vmess": + protocolConfig := &protocol.Vmess{} + protocolConfig.SetUuid(config.Credential) + protocolConfig.SetAlterId(strconv.Itoa(config.AlterID)) + protocolConfig.SetSecurity(config.Cipher) + return vmess.NewClient(protocolConfig, current) + default: + return nil, errors.New("不支持的隧道代理协议") + } +} + +// ownedVLESSProxy closes the transport connection when the upstream VLESS +// client fails while writing its initial request. yuhaiin's VLESS client does +// not transfer the failed connection back to its caller, so ownership must be +// retained at this boundary to prevent failed retries from leaking sockets. +type ownedVLESSProxy struct { + netapi.EmptyDispatch + config *protocol.Vless + dialer netapi.Proxy +} + +func newOwnedVLESSProxy(config *protocol.Vless, dialer netapi.Proxy) (netapi.Proxy, error) { + if _, err := vless.NewClient(config, dialer); err != nil { + return nil, err + } + return &ownedVLESSProxy{config: config, dialer: dialer}, nil +} + +func (p *ownedVLESSProxy) Conn(ctx context.Context, address netapi.Address) (net.Conn, error) { + connection, err := p.dialer.Conn(ctx, address) + if err != nil { + return nil, err + } + client, err := vless.NewClient(p.config, &singleConnectionProxy{connection: connection}) + if err != nil { + _ = connection.Close() + return nil, err + } + result, err := client.Conn(ctx, address) + if err != nil { + _ = connection.Close() + return nil, err + } + return result, nil +} + +func (p *ownedVLESSProxy) PacketConn(ctx context.Context, address netapi.Address) (net.PacketConn, error) { + return nil, errors.New("VLESS 隧道不支持 UDP") +} + +type singleConnectionProxy struct { + netapi.EmptyDispatch + connection net.Conn +} + +func (p *singleConnectionProxy) Conn(context.Context, netapi.Address) (net.Conn, error) { + if p.connection == nil { + return nil, errors.New("VLESS 底层连接不可用") + } + connection := p.connection + p.connection = nil + return connection, nil +} + +func (p *singleConnectionProxy) PacketConn(context.Context, netapi.Address) (net.PacketConn, error) { + return nil, errors.New("VLESS 隧道不支持 UDP") +} + +type tlsProxy struct { + netapi.EmptyDispatch + config Config + dialer netapi.Proxy +} + +func (p *tlsProxy) Conn(ctx context.Context, address netapi.Address) (net.Conn, error) { + connection, err := p.dialer.Conn(ctx, address) + if err != nil { + return nil, err + } + tlsConnection := tls.Client(connection, p.tlsConfig()) + handshakeCtx, cancel := newTunnelHandshakeContext(ctx) + defer cancel() + if err := tlsConnection.HandshakeContext(handshakeCtx); err != nil { + _ = connection.Close() + return nil, fmt.Errorf("隧道 TLS 握手: %w", err) + } + return tlsConnection, nil +} + +func (p *tlsProxy) PacketConn(context.Context, netapi.Address) (net.PacketConn, error) { + return nil, errors.New("TLS 隧道不支持 UDP") +} + +func (p *tlsProxy) tlsConfig() *tls.Config { + return &tls.Config{ + MinVersion: tls.VersionTLS12, ServerName: p.config.ServerName, + InsecureSkipVerify: p.config.Insecure, NextProtos: append([]string(nil), p.config.ALPN...), + } +} + +type websocketProxy struct { + netapi.EmptyDispatch + config Config + dialer netapi.Proxy +} + +func (p *websocketProxy) Conn(ctx context.Context, address netapi.Address) (net.Conn, error) { + scheme := "ws" + if p.config.TLS { + scheme = "wss" + } + path, rawQuery, _ := strings.Cut(p.config.WebSocketPath, "?") + endpoint := (&url.URL{Scheme: scheme, Host: p.config.WebSocketHost, Path: path, RawQuery: rawQuery}).String() + transport := &http.Transport{ + Proxy: nil, + DialContext: func(dialCtx context.Context, _, _ string) (net.Conn, error) { + return p.dialer.Conn(dialCtx, address) + }, + ForceAttemptHTTP2: false, + TLSClientConfig: websocketTLSConfig(p.config), + } + handshakeCtx, cancel := newTunnelHandshakeContext(ctx) + defer cancel() + connection, _, err := websocket.Dial(handshakeCtx, endpoint, &websocket.DialOptions{ + HTTPClient: &http.Client{Transport: transport}, + Host: p.config.WebSocketHost, + }) + if err != nil { + transport.CloseIdleConnections() + return nil, fmt.Errorf("隧道 WebSocket 握手: %w", err) + } + return websocket.NetConn(context.Background(), connection, websocket.MessageBinary), nil +} + +func (p *websocketProxy) PacketConn(context.Context, netapi.Address) (net.PacketConn, error) { + return nil, errors.New("WebSocket 隧道不支持 UDP") +} + +type serverDialer struct { + netapi.EmptyDispatch + address string +} + +func (d *serverDialer) Conn(ctx context.Context, _ netapi.Address) (net.Conn, error) { + return newServerNetDialer().DialContext(ctx, "tcp", d.address) +} + +func newServerNetDialer() *net.Dialer { + return &net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second} +} + +func newTunnelHandshakeContext(ctx context.Context) (context.Context, context.CancelFunc) { + return context.WithTimeout(ctx, tunnelHandshakeTimeout) +} + +func websocketTLSConfig(config Config) *tls.Config { + tlsConfig := (&tlsProxy{config: config}).tlsConfig() + tlsConfig.NextProtos = []string{"http/1.1"} + return tlsConfig +} + +func validateWebSocketHost(host string) error { + parsed, err := url.Parse("http://" + strings.TrimSpace(host)) + if err != nil || parsed.Hostname() == "" || parsed.User != nil || parsed.Path != "" || parsed.RawQuery != "" || parsed.Fragment != "" { + return errors.New("WebSocket host 无效") + } + if parsed.Port() != "" { + if _, err := canonicalServer(parsed.Hostname(), parsed.Port()); err != nil { + return errors.New("WebSocket host 无效") + } + } + return nil +} + +func (d *serverDialer) PacketConn(context.Context, netapi.Address) (net.PacketConn, error) { + return nil, errors.New("当前隧道代理不支持 UDP") +} + +func canonicalServer(host, port string) (string, error) { + host = strings.TrimSpace(strings.Trim(host, "[]")) + if host == "" { + return "", errors.New("隧道代理服务器不能为空") + } + parsedPort, err := strconv.ParseUint(strings.TrimSpace(port), 10, 16) + if err != nil || parsedPort == 0 { + return "", errors.New("隧道代理端口无效") + } + return net.JoinHostPort(host, strconv.FormatUint(parsedPort, 10)), nil +} + +func decodeBase64String(value string) (string, error) { + decoded, err := decodeBase64Bytes(value) + return string(decoded), err +} + +func decodeBase64Bytes(value string) ([]byte, error) { + value = strings.TrimSpace(value) + for _, encoding := range []*base64.Encoding{base64.RawStdEncoding, base64.StdEncoding, base64.RawURLEncoding, base64.URLEncoding} { + if decoded, err := encoding.DecodeString(value); err == nil { + return decoded, nil + } + } + return nil, errors.New("invalid base64") +} + +func firstNonEmpty(values ...string) string { + for _, value := range values { + if strings.TrimSpace(value) != "" { + return strings.TrimSpace(value) + } + } + return "" +} + +func splitList(value string) []string { + var result []string + for item := range strings.SplitSeq(value, ",") { + if item = strings.TrimSpace(item); item != "" { + result = append(result, item) + } + } + return result +} + +func queryBool(query url.Values, names ...string) (bool, error) { + for _, name := range names { + if raw, ok := query[name]; ok && len(raw) != 0 { + return parseBool(raw[0], name) + } + } + return false, nil +} + +func jsonBool(value map[string]any, name string) (bool, error) { + raw, ok := value[name] + if !ok || raw == nil { + return false, nil + } + switch typed := raw.(type) { + case bool: + return typed, nil + case string: + return parseBool(typed, name) + case float64: + return parseBool(strconv.FormatFloat(typed, 'f', -1, 64), name) + default: + return false, fmt.Errorf("%s 必须是布尔值", name) + } +} + +func parseBool(value, name string) (bool, error) { + switch strings.ToLower(strings.TrimSpace(value)) { + case "1", "true", "yes": + return true, nil + case "", "0", "false", "no": + return false, nil + default: + return false, fmt.Errorf("%s 必须是布尔值", name) + } +} + +func jsonString(value map[string]any, name string) string { + raw, ok := value[name] + if !ok || raw == nil { + return "" + } + switch typed := raw.(type) { + case string: + return strings.TrimSpace(typed) + case float64: + return strconv.FormatFloat(typed, 'f', -1, 64) + default: + return "" + } +} diff --git a/backend/internal/pkg/tunnelproxy/tunnelproxy_test.go b/backend/internal/pkg/tunnelproxy/tunnelproxy_test.go new file mode 100644 index 00000000..a34f86a8 --- /dev/null +++ b/backend/internal/pkg/tunnelproxy/tunnelproxy_test.go @@ -0,0 +1,223 @@ +package tunnelproxy + +import ( + "context" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Asutorufa/yuhaiin/pkg/net/netapi" + "github.com/Asutorufa/yuhaiin/pkg/protos/node/protocol" + "github.com/coder/websocket" +) + +const testUUID = "123e4567-e89b-12d3-a456-426614174000" + +func TestNormalizeStripsRemarksAndBuildsDialers(t *testing.T) { + vmessJSON := fmt.Sprintf(`{"v":"2","ps":"node one","add":"proxy.example","port":"443","id":%q,"aid":"0","scy":"auto","net":"ws","tls":"tls","sni":"edge.example","host":"edge.example","path":"/ws"}`, testUUID) + vmessURL := "vmess://" + base64.RawStdEncoding.EncodeToString([]byte(vmessJSON)) + tests := []struct { + name string + raw string + }{ + {name: "trojan", raw: "trojan://secret@proxy.example:443?security=tls&sni=edge.example&type=ws&host=edge.example&path=%2Fws#one"}, + {name: "vless", raw: "vless://" + testUUID + "@proxy.example:443?encryption=none&security=tls&sni=edge.example&type=ws&host=edge.example&path=%2Fws#one"}, + {name: "shadowsocks", raw: "ss://" + base64.RawURLEncoding.EncodeToString([]byte("aes-128-gcm:secret")) + "@proxy.example:8388#one"}, + {name: "vmess", raw: vmessURL}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + normalized, err := Normalize(test.raw) + if err != nil { + t.Fatal(err) + } + if strings.Contains(normalized, "#") || strings.Contains(normalized, "node one") { + t.Fatalf("remark leaked into normalized URL: %q", normalized) + } + if _, err := NewDialer(normalized); err != nil { + t.Fatalf("construct dialer: %v", err) + } + }) + } +} + +func TestNormalizeRemarksDoNotChangeIdentity(t *testing.T) { + base := "trojan://secret@proxy.example:443?security=tls&sni=edge.example" + one, err := Normalize(base + "#one") + if err != nil { + t.Fatal(err) + } + two, err := Normalize(base + "#two") + if err != nil { + t.Fatal(err) + } + if one != two { + t.Fatalf("remark changed identity: %q != %q", one, two) + } +} + +func TestNormalizeEquivalentShareLinksHaveOneIdentity(t *testing.T) { + trojanOne, err := Normalize("trojan://secret@proxy.example:443?type=websocket&security=tls&sni=edge.example&host=edge.example&path=ws") + if err != nil { + t.Fatal(err) + } + trojanTwo, err := Normalize("trojan://secret@proxy.example:443?network=ws&peer=edge.example&host=edge.example&path=%2Fws") + if err != nil { + t.Fatal(err) + } + if trojanOne != trojanTwo { + t.Fatalf("equivalent Trojan links have different identities: %q != %q", trojanOne, trojanTwo) + } + + vmessOne := vmessTestURL(t, map[string]any{ + "v": "2", "add": "proxy.example", "port": "443", "id": testUUID, + "aid": "0", "scy": "auto", "net": "ws", "tls": "tls", + "sni": "edge.example", "host": "edge.example", "path": "ws", + }) + vmessTwo := vmessTestURL(t, map[string]any{ + "v": "2", "add": "proxy.example", "port": "443", "id": testUUID, + "aid": "0", "scy": "auto", "net": "ws", "tls": "tls", + "sni": "edge.example", "host": "edge.example", "path": "/ws", + }) + normalizedOne, err := Normalize(vmessOne) + if err != nil { + t.Fatal(err) + } + normalizedTwo, err := Normalize(vmessTwo) + if err != nil { + t.Fatal(err) + } + if normalizedOne != normalizedTwo { + t.Fatalf("equivalent VMess links have different identities: %q != %q", normalizedOne, normalizedTwo) + } +} + +func TestOwnedVLESSProxyClosesConnectionWhenInitialWriteFails(t *testing.T) { + client, server := net.Pipe() + if err := server.Close(); err != nil { + t.Fatal(err) + } + tracked := &closeTrackingConn{Conn: client} + config := &protocol.Vless{} + config.SetUuid(testUUID) + proxy, err := newOwnedVLESSProxy(config, &singleConnectionProxy{connection: tracked}) + if err != nil { + t.Fatal(err) + } + if _, err := proxy.Conn(context.Background(), netapi.ParseDomainPort("tcp", "target.example", 443)); err == nil { + t.Fatal("VLESS initial write unexpectedly succeeded") + } + if !tracked.closed { + t.Fatal("failed VLESS connection was not closed") + } +} + +func TestTunnelHandshakeContextHasIndependentDeadline(t *testing.T) { + ctx, cancel := newTunnelHandshakeContext(context.Background()) + defer cancel() + deadline, ok := ctx.Deadline() + if !ok { + t.Fatal("tunnel handshake context has no deadline") + } + remaining := time.Until(deadline) + if remaining <= 0 || remaining > tunnelHandshakeTimeout { + t.Fatalf("tunnel handshake deadline remaining = %v", remaining) + } +} + +func TestNormalizeSupportsLegacyShadowsocks(t *testing.T) { + raw := "ss://" + base64.RawStdEncoding.EncodeToString([]byte("chacha20-ietf-poly1305:secret@proxy.example:8388")) + "#legacy" + normalized, err := Normalize(raw) + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(normalized, "ss://") || strings.Contains(normalized, "#") { + t.Fatalf("normalized legacy URL = %q", normalized) + } +} + +func TestParseRejectsUnsupportedOrMalformedLinks(t *testing.T) { + for _, raw := range []string{ + "hysteria2://secret@proxy.example:443", + "tuic://user:secret@proxy.example:443", + "vless://not-a-uuid@proxy.example:443?encryption=none", + "vless://" + testUUID + "@proxy.example:443?encryption=none&flow=xtls-rprx-vision", + "trojan://secret@proxy.example:443?type=grpc", + "trojan://secret@proxy.example:443/unexpected", + "ss://" + base64.RawURLEncoding.EncodeToString([]byte("rc4-md5:secret")) + "@proxy.example:8388", + "ss://" + base64.RawURLEncoding.EncodeToString([]byte("aes-128-gcm:secret")) + "@proxy.example:8388/unexpected", + "vmess://not-base64", + } { + if _, err := Normalize(raw); err == nil { + t.Fatalf("invalid tunnel accepted: %q", raw) + } + } +} + +func TestWebSocketTransportCarriesBinaryStream(t *testing.T) { + handlerResult := make(chan error, 1) + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if request.Host != "edge.example" || request.URL.Path != "/ws" { + handlerResult <- fmt.Errorf("request host=%q path=%q", request.Host, request.URL.Path) + return + } + connection, err := websocket.Accept(writer, request, nil) + if err != nil { + handlerResult <- err + return + } + stream := websocket.NetConn(context.Background(), connection, websocket.MessageBinary) + defer stream.Close() + _, err = io.CopyN(stream, stream, 4) + handlerResult <- err + })) + defer server.Close() + serverAddress := strings.TrimPrefix(server.URL, "http://") + proxy := &websocketProxy{ + config: Config{Server: serverAddress, WebSocketHost: "edge.example", WebSocketPath: "/ws"}, + dialer: &serverDialer{address: serverAddress}, + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + connection, err := proxy.Conn(ctx, netapi.ParseDomainPort("tcp", "target.example", 443)) + if err != nil { + t.Fatal(err) + } + defer connection.Close() + if _, err := connection.Write([]byte("pong")); err != nil { + t.Fatal(err) + } + response := make([]byte, 4) + if _, err := io.ReadFull(connection, response); err != nil || string(response) != "pong" { + t.Fatalf("response=%q err=%v", response, err) + } + if err := <-handlerResult; err != nil { + t.Fatal(err) + } +} + +type closeTrackingConn struct { + net.Conn + closed bool +} + +func (c *closeTrackingConn) Close() error { + c.closed = true + return c.Conn.Close() +} + +func vmessTestURL(t *testing.T, config map[string]any) string { + t.Helper() + payload, err := json.Marshal(config) + if err != nil { + t.Fatal(err) + } + return "vmess://" + base64.RawStdEncoding.EncodeToString(payload) +} diff --git a/backend/internal/repository/account.go b/backend/internal/repository/account.go index 98ea4865..bd07fd88 100644 --- a/backend/internal/repository/account.go +++ b/backend/internal/repository/account.go @@ -169,6 +169,7 @@ type AccountRepository interface { HasQuotaWindows(ctx context.Context, accountID uint64) (bool, error) GetQuotaWindows(ctx context.Context, accountIDs []uint64) (map[uint64][]account.QuotaWindow, error) ReplaceQuotaWindows(ctx context.Context, accountID uint64, tier account.WebTier, syncedAt time.Time, values []account.QuotaWindow) error + ReplaceQuotaWindowGroup(ctx context.Context, accountID uint64, syncedAt time.Time, modes []string, values []account.QuotaWindow) error SaveQuotaWindows(ctx context.Context, accountID uint64, tier account.WebTier, syncedAt time.Time, values []account.QuotaWindow) error UpsertManyByIdentity(ctx context.Context, values []account.Credential) ([]AccountUpsertResult, error) DecrementQuotaWindow(ctx context.Context, accountID uint64, mode string, now time.Time) (bool, error) diff --git a/backend/internal/transport/http/egress/handler.go b/backend/internal/transport/http/egress/handler.go index c5d792eb..a8610f96 100644 --- a/backend/internal/transport/http/egress/handler.go +++ b/backend/internal/transport/http/egress/handler.go @@ -800,6 +800,8 @@ type sourceRequest struct { Enabled bool `json:"enabled"` URL *string `json:"url"` ClearURL bool `json:"clearUrl"` + ProxyURL *string `json:"proxyURL"` + ClearProxyURL bool `json:"clearProxyURL"` RefreshIntervalSeconds *int `json:"refreshIntervalSeconds"` DefaultAccountCapacity *int `json:"defaultAccountCapacity"` } @@ -810,6 +812,7 @@ type sourceResponse struct { Scope string `json:"scope"` Enabled bool `json:"enabled"` URLConfigured bool `json:"urlConfigured"` + ProxyConfigured bool `json:"proxyConfigured"` RefreshIntervalSeconds int `json:"refreshIntervalSeconds"` DefaultAccountCapacity int `json:"defaultAccountCapacity"` LastSyncedAt *time.Time `json:"lastSyncedAt,omitempty"` @@ -835,8 +838,6 @@ type operationsConfigRequest struct { AutoAssignEnabled bool `json:"autoAssignEnabled"` AutoBalanceEnabled bool `json:"autoBalanceEnabled"` AssignmentIntervalSeconds int `json:"assignmentIntervalSeconds"` - SubscriptionProxyURL *string `json:"subscriptionProxyURL,omitempty"` - ClearSubscriptionProxy bool `json:"clearSubscriptionProxy,omitempty"` Fallbacks map[string]operationsFallbackRequest `json:"fallbacks"` } @@ -846,14 +847,13 @@ type operationsFallbackRequest struct { } type operationsConfigResponse struct { - ProbeProvider string `json:"probeProvider"` - ProbeIntervalSeconds int `json:"probeIntervalSeconds"` - AutoAssignEnabled bool `json:"autoAssignEnabled"` - AutoBalanceEnabled bool `json:"autoBalanceEnabled"` - AssignmentIntervalSeconds int `json:"assignmentIntervalSeconds"` - SubscriptionProxyConfigured bool `json:"subscriptionProxyConfigured"` - Fallbacks map[string]operationsFallbackResponse `json:"fallbacks"` - UpdatedAt time.Time `json:"updatedAt"` + ProbeProvider string `json:"probeProvider"` + ProbeIntervalSeconds int `json:"probeIntervalSeconds"` + AutoAssignEnabled bool `json:"autoAssignEnabled"` + AutoBalanceEnabled bool `json:"autoBalanceEnabled"` + AssignmentIntervalSeconds int `json:"assignmentIntervalSeconds"` + Fallbacks map[string]operationsFallbackResponse `json:"fallbacks"` + UpdatedAt time.Time `json:"updatedAt"` } type operationsFallbackResponse struct { @@ -866,12 +866,6 @@ func (value operationsConfigRequest) input() (egressapp.OperationsConfigInput, e ProbeProvider: egressdomain.ProbeProvider(strings.TrimSpace(value.ProbeProvider)), ProbeIntervalSeconds: value.ProbeIntervalSeconds, AutoAssignEnabled: value.AutoAssignEnabled, AutoBalanceEnabled: value.AutoBalanceEnabled, AssignmentIntervalSeconds: value.AssignmentIntervalSeconds, } - if value.SubscriptionProxyURL != nil { - result.SubscriptionProxyURL = value.SubscriptionProxyURL - } - if value.ClearSubscriptionProxy { - result.ClearSubscriptionProxy = true - } if value.Fallbacks == nil { return result, nil } @@ -895,6 +889,7 @@ func (value operationsConfigRequest) input() (egressapp.OperationsConfigInput, e func (value sourceRequest) input() egressapp.SubscriptionSourceInput { return egressapp.SubscriptionSourceInput{ Name: value.Name, Scope: egressdomain.Scope(value.Scope), Enabled: value.Enabled, URL: value.URL, ClearURL: value.ClearURL, + ProxyURL: value.ProxyURL, ClearProxyURL: value.ClearProxyURL, RefreshIntervalSeconds: value.RefreshIntervalSeconds, DefaultAccountCapacity: value.DefaultAccountCapacity, } } @@ -902,6 +897,7 @@ func (value sourceRequest) input() egressapp.SubscriptionSourceInput { func newSourceResponse(value egressdomain.PublicSubscriptionSource) sourceResponse { return sourceResponse{ ID: value.ID, Name: value.Name, Scope: string(value.Scope), Enabled: value.Enabled, URLConfigured: value.URLConfigured, + ProxyConfigured: value.ProxyConfigured, RefreshIntervalSeconds: value.RefreshIntervalSeconds, DefaultAccountCapacity: value.DefaultAccountCapacity, LastSyncedAt: value.LastSyncedAt, NextSyncAt: value.NextSyncAt, LastSyncImported: value.LastSyncImported, LastSyncError: value.LastSyncError, } @@ -920,8 +916,7 @@ func newOperationsConfigResponse(value egressdomain.OperationsConfig) operations return operationsConfigResponse{ ProbeProvider: string(value.ProbeProvider.Normalized()), ProbeIntervalSeconds: value.ProbeIntervalSeconds, AutoAssignEnabled: value.AutoAssignEnabled, AutoBalanceEnabled: value.AutoBalanceEnabled, AssignmentIntervalSeconds: value.AssignmentIntervalSeconds, - SubscriptionProxyConfigured: value.EncryptedSubscriptionProxyURL != "", - Fallbacks: fallbacks, UpdatedAt: value.UpdatedAt, + Fallbacks: fallbacks, UpdatedAt: value.UpdatedAt, } } diff --git a/backend/internal/transport/http/egress/handler_test.go b/backend/internal/transport/http/egress/handler_test.go index 5e53991e..ad182620 100644 --- a/backend/internal/transport/http/egress/handler_test.go +++ b/backend/internal/transport/http/egress/handler_test.go @@ -281,16 +281,3 @@ func TestOperationsConfigRequestRejectsInvalidFallbackNodeID(t *testing.T) { t.Fatalf("invalid node ID error = %v", err) } } - -func TestOperationsConfigResponseReportsSubscriptionProxyWithoutExposingIt(t *testing.T) { - response := newOperationsConfigResponse(egressdomain.OperationsConfig{ - ProbeProvider: egressdomain.ProbeProviderCloudflare, - EncryptedSubscriptionProxyURL: "encrypted-secret-must-not-be-returned", - }) - if !response.SubscriptionProxyConfigured { - t.Fatal("configured subscription proxy was not reported") - } - if response.ProbeProvider != "cloudflare" { - t.Fatalf("probe provider=%q", response.ProbeProvider) - } -} diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index 6a59717d..efc81731 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -22,6 +22,7 @@ import ( clientkeydomain "github.com/chenyme/grok2api/backend/internal/domain/clientkey" mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media" modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" + "github.com/chenyme/grok2api/backend/internal/infra/provider" "github.com/chenyme/grok2api/backend/internal/pkg/neterror" "github.com/chenyme/grok2api/backend/internal/transport/http/middleware" "github.com/gin-gonic/gin" @@ -88,8 +89,20 @@ func (h *Handler) Register(router *gin.RouterGroup) { router.POST("/images/generations", h.generateImage) router.POST("/images/edits", h.editImage) router.POST("/videos/generations", h.generateVideo) + router.POST("/videos/edits", h.editVideo) + router.POST("/videos/extensions", h.extendVideo) router.GET("/videos/:requestId", h.getVideo) router.GET("/videos/:requestId/content", h.getVideoContent) + router.POST("/tts", h.synthesizeSpeech) + router.GET("/tts/voices", h.listTTSVoices) + router.GET("/tts/voices/:voiceId", h.getTTSVoice) + router.POST("/stt", h.transcribeSpeech) + router.GET("/stt", h.proxySTTWebSocket) + // OpenAI-compatible audio aliases for common client SDKs. + router.POST("/audio/speech", h.synthesizeOpenAISpeech) + router.POST("/audio/tasks", h.synthesizeOpenAIAudioTask) + router.POST("/audio/transcriptions", h.transcribeOpenAIAudio) + router.GET("/realtime", h.proxyRealtimeWebSocket) router.POST("/responses/compact", h.compactResponse) router.GET("/responses/:responseId", h.getResponse) router.DELETE("/responses/:responseId", h.deleteResponse) @@ -124,6 +137,7 @@ type imageGenerationRequest struct { Size string `json:"size"` AspectRatio string `json:"aspect_ratio"` Resolution string `json:"resolution"` + Quality string `json:"quality"` ResponseFormat string `json:"response_format"` StorageOptions json.RawMessage `json:"storage_options"` Stream bool `json:"stream"` @@ -143,6 +157,7 @@ type imageEditJSONRequest struct { Size string `json:"size"` AspectRatio string `json:"aspect_ratio"` Resolution string `json:"resolution"` + Quality string `json:"quality"` ResponseFormat string `json:"response_format"` StorageOptions json.RawMessage `json:"storage_options"` Stream bool `json:"stream"` @@ -154,6 +169,10 @@ type videoGenerationImage struct { FileID string `json:"file_id"` } +type videoGenerationAudio struct { + VoiceID string `json:"voice_id"` +} + type videoGenerationRequest struct { Model string `json:"model"` Prompt string `json:"prompt"` @@ -163,6 +182,8 @@ type videoGenerationRequest struct { Resolution string `json:"resolution"` Image *videoGenerationImage `json:"image"` ReferenceImages []videoGenerationImage `json:"reference_images"` + ReferenceAudios []videoGenerationAudio `json:"reference_audios"` + Video *videoGenerationImage `json:"video"` Output json.RawMessage `json:"output"` StorageOptions json.RawMessage `json:"storage_options"` } @@ -392,6 +413,11 @@ func (h *Handler) generateImage(c *gin.Context) { return } } + quality := strings.ToLower(strings.TrimSpace(request.Quality)) + if quality != "" && quality != "low" && quality != "medium" { + writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", "quality 必须是 low 或 medium") + return + } clientKey, requestID, ok := requestIdentity(c) if !ok { return @@ -399,7 +425,7 @@ func (h *Handler) generateImage(c *gin.Context) { result, err := h.gateway.GenerateImage(c.Request.Context(), gateway.ImageGenerationInput{ RequestID: requestID, ClientKey: clientKey, PublicModel: request.Model, Prompt: request.Prompt, Count: count, Size: request.Size, AspectRatio: request.AspectRatio, - Resolution: request.Resolution, ResponseFormat: request.ResponseFormat, + Resolution: request.Resolution, Quality: quality, ResponseFormat: request.ResponseFormat, Streaming: request.Stream, PartialImages: partialImages, }) if err != nil { @@ -419,20 +445,30 @@ func (h *Handler) writeMediaResult(c *gin.Context, result *gateway.Result) { writeOpenAIError(c, http.StatusServiceUnavailable, clientCode, credentialErrorMessage(clientCode)) return } + if result.StatusCode < http.StatusOK || (result.StatusCode >= http.StatusMultipleChoices && result.StatusCode < http.StatusBadRequest) { + errorCode = "invalid_upstream_status" + writeOpenAIError(c, http.StatusBadGateway, "invalid_upstream_response", "上游媒体服务返回了不安全的重定向响应") + return + } + contentType, safeContentType := normalizeMediaResponseContentType(result.Header.Get("Content-Type")) + if !safeContentType { + errorCode = "unsafe_media_content_type" + writeOpenAIError(c, http.StatusBadGateway, "invalid_media_type", "上游媒体服务返回了不受支持的内容类型") + return + } contentLength, contentLengthErr := strconv.ParseInt(result.Header.Get("Content-Length"), 10, 64) if contentLengthErr == nil && contentLength > maxMediaResponseTransferBytes { errorCode = "response_too_large" writeOpenAIError(c, http.StatusBadGateway, "media_too_large", "上游媒体超过 2 GiB 安全上限") return } - copyHeaders(c.Writer.Header(), result.Header) + setSafeMediaResponseHeaders(c, result.Header) if contentLengthErr == nil && contentLength >= 0 { c.Header("Content-Length", strconv.FormatInt(contentLength, 10)) } else { c.Header("Trailer", mediaTransferErrorTrailer) } - c.Status(result.StatusCode) - if err := copyMedia(responseDeadlineWriter{ResponseWriter: c.Writer}, result.Body, maxMediaResponseTransferBytes); err != nil { + if err := writeMediaBody(c, result.Body, contentType, result.StatusCode, maxMediaResponseTransferBytes); err != nil { if errors.Is(err, errResponseTransferLimit) { errorCode = "response_too_large" } else { @@ -444,13 +480,39 @@ func (h *Handler) writeMediaResult(c *gin.Context, result *gateway.Result) { } } -type responseDeadlineWriter struct{ http.ResponseWriter } +func normalizeMediaResponseContentType(value string) (string, bool) { + mediaType, _, err := mime.ParseMediaType(strings.TrimSpace(value)) + if err != nil { + return "", false + } + mediaType = strings.ToLower(mediaType) + switch mediaType { + case "application/json": + return "application/json; charset=utf-8", true + case "text/plain": + return "text/plain; charset=utf-8", true + case "application/ogg": + return mediaType, true + } + if strings.HasPrefix(mediaType, "audio/") { + switch mediaType { + case "audio/aac", "audio/flac", "audio/l16", "audio/mpeg", "audio/mp3", "audio/ogg", "audio/opus", "audio/pcm", "audio/wav", "audio/webm", "audio/x-flac", "audio/x-wav": + return mediaType, true + } + } + return "", false +} -func (w responseDeadlineWriter) Write(payload []byte) (int, error) { - if err := setResponseWriteDeadline(w.ResponseWriter); err != nil { - return 0, err +func setSafeMediaResponseHeaders(c *gin.Context, upstream http.Header) { + c.Header("Cache-Control", "private, no-store") + c.Header("X-Content-Type-Options", "nosniff") + c.Header("Content-Security-Policy", "default-src 'none'; sandbox") + c.Header("Referrer-Policy", "no-referrer") + for _, name := range []string{"Retry-After", "X-Request-Id"} { + if value := strings.TrimSpace(upstream.Get(name)); value != "" { + c.Header(name, value) + } } - return w.ResponseWriter.Write(payload) } func setResponseWriteDeadline(writer http.ResponseWriter) error { @@ -461,7 +523,11 @@ func setResponseWriteDeadline(writer http.ResponseWriter) error { return err } -func copyMedia(writer io.Writer, source io.Reader, limit int64) error { +// writeMediaBody binds the validated non-HTML content type before emitting the +// response body, so no caller can stream media bytes without their MIME context. +func writeMediaBody(c *gin.Context, source io.Reader, contentType string, statusCode int, limit int64) error { + c.Header("Content-Type", contentType) + c.Status(statusCode) buffer := make([]byte, 64<<10) var transferred int64 for { @@ -475,7 +541,10 @@ func copyMedia(writer io.Writer, source io.Reader, limit int64) error { if int64(writeSize) > remaining { writeSize = int(remaining) } - written, writeErr := writer.Write(buffer[:writeSize]) + if err := setResponseWriteDeadline(c.Writer); err != nil { + return err + } + written, writeErr := c.Writer.Write(buffer[:writeSize]) transferred += int64(written) if writeErr != nil { return writeErr @@ -577,6 +646,11 @@ func (h *Handler) editImage(c *gin.Context) { writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", "resolution 必须是 1k 或 2k") return } + quality := strings.ToLower(strings.TrimSpace(request.Quality)) + if quality != "" && quality != "low" && quality != "medium" { + writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", "quality 必须是 low 或 medium") + return + } clientKey, requestID, ok := requestIdentity(c) if !ok { return @@ -584,7 +658,7 @@ func (h *Handler) editImage(c *gin.Context) { result, err := h.gateway.EditImage(c.Request.Context(), gateway.ImageEditInput{ RequestID: requestID, ClientKey: clientKey, PublicModel: model, Prompt: prompt, ImageURLs: imageURLs, Count: count, Size: size, AspectRatio: aspectRatio, - Resolution: resolution, ResponseFormat: request.ResponseFormat, + Resolution: resolution, Quality: quality, ResponseFormat: request.ResponseFormat, Streaming: request.Stream, PartialImages: partialImages, }) if err != nil { @@ -607,14 +681,32 @@ func requestIdentity(c *gin.Context) (clientkeydomain.Key, string, bool) { } func (h *Handler) generateVideo(c *gin.Context) { + h.handleVideoCreate(c, gatewayVideoOperationGenerate, "视频生成") +} + +func (h *Handler) editVideo(c *gin.Context) { + h.handleVideoCreate(c, gatewayVideoOperationEdit, "视频编辑") +} + +func (h *Handler) extendVideo(c *gin.Context) { + h.handleVideoCreate(c, gatewayVideoOperationExtend, "视频延长") +} + +const ( + gatewayVideoOperationGenerate = "generate" + gatewayVideoOperationEdit = "edit" + gatewayVideoOperationExtend = "extend" +) + +func (h *Handler) handleVideoCreate(c *gin.Context, operation, label string) { c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.maxBodyBytes) if !isJSONRequest(c) { - writeOpenAIError(c, http.StatusUnsupportedMediaType, "invalid_request", "视频生成仅支持 application/json") + writeOpenAIError(c, http.StatusUnsupportedMediaType, "invalid_request", label+"仅支持 application/json") return } var request videoGenerationRequest if err := decodeSingleJSON(c.Request.Body, &request, true); err != nil { - writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "视频生成 JSON 请求无效: "+err.Error()) + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", label+" JSON 请求无效: "+err.Error()) return } if hasJSONValue(request.Output) { @@ -625,71 +717,179 @@ func (h *Handler) generateVideo(c *gin.Context) { writeOpenAIError(c, http.StatusBadRequest, "unsupported_parameter", "当前兼容层暂不支持 storage_options") return } - duration, err := parseVideoDuration(request.Duration) - if err != nil { - writeOpenAIError(c, http.StatusBadRequest, "invalid_request", err.Error()) - return - } model := strings.TrimSpace(request.Model) prompt := strings.TrimSpace(request.Prompt) if model == "" { - writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "视频生成缺少有效 model") + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", label+"缺少有效 model") return } - aspectRatio := strings.TrimSpace(request.AspectRatio) - if aspectRatio == "" { - aspectRatio = "16:9" - } - if !validVideoAspectRatio(aspectRatio) { - writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "aspect_ratio 必须是 1:1、16:9、9:16、4:3、3:4、3:2 或 2:3") - return - } - resolution := strings.ToLower(strings.TrimSpace(request.Resolution)) - if resolution == "" { - resolution = "720p" - } - if resolution != "480p" && resolution != "720p" && resolution != "1080p" { - writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "resolution 必须是 480p、720p 或 1080p") - return - } - inputs := append([]videoGenerationImage(nil), request.ReferenceImages...) - if request.Image != nil { - inputs = append([]videoGenerationImage{*request.Image}, inputs...) - } - if len(inputs) > mediadomain.MaxInputImages { - writeOpenAIError(c, http.StatusBadRequest, "invalid_request", fmt.Sprintf("image 与 reference_images 合计不能超过 %d 张", mediadomain.MaxInputImages)) - return - } - referenceURLs := make([]string, 0, len(inputs)) - for _, input := range inputs { + parseVideoImage := func(input videoGenerationImage, field string) (string, bool) { urlValue := strings.TrimSpace(input.URL) fileID := strings.TrimSpace(input.FileID) if (urlValue == "") == (fileID == "") { - writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "每个 image 必须且只能提供 url 或 file_id") - return + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", field+" 必须且只能提供 url 或 file_id") + return "", false } if fileID != "" { if !mediadomain.IsInputAssetID(fileID) { - writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "image.file_id 无效") + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", field+".file_id 无效") + return "", false + } + return gateway.VideoInputFileReference(fileID), true + } + return urlValue, true + } + + duration := 0 + aspectRatio := "" + resolution := "" + imageURL := "" + referenceURLs := []string{} + referenceAudios := []string{} + videoURL := "" + + if operation == gatewayVideoOperationGenerate { + var err error + duration, err = parseVideoDuration(request.Duration) + if err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", err.Error()) + return + } + aspectRatio = strings.TrimSpace(request.AspectRatio) + if aspectRatio == "" { + aspectRatio = "16:9" + } + if !validVideoAspectRatio(aspectRatio) { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "aspect_ratio 必须是 1:1、16:9、9:16、4:3、3:4、3:2 或 2:3") + return + } + resolution = strings.ToLower(strings.TrimSpace(request.Resolution)) + if resolution == "" { + resolution = "720p" + } + if resolution != "480p" && resolution != "720p" && resolution != "1080p" { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "resolution 必须是 480p、720p 或 1080p") + return + } + if request.Image != nil { + value, ok := parseVideoImage(*request.Image, "image") + if !ok { + return + } + imageURL = value + } + referenceURLs = make([]string, 0, len(request.ReferenceImages)) + for _, input := range request.ReferenceImages { + value, ok := parseVideoImage(input, "reference_images") + if !ok { + return + } + referenceURLs = append(referenceURLs, value) + } + referenceAudios = make([]string, 0, len(request.ReferenceAudios)) + for i, input := range request.ReferenceAudios { + voiceID := strings.TrimSpace(input.VoiceID) + if voiceID == "" { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", fmt.Sprintf("reference_audios[%d].voice_id 不能为空", i)) + return + } + referenceAudios = append(referenceAudios, voiceID) + } + if len(referenceAudios) > 3 { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "reference_audios 最多 3 个") + return + } + if imageURL != "" && (len(referenceURLs) > 0 || len(referenceAudios) > 0) { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "image 不能与 reference_images/reference_audios 同时使用") + return + } + if len(referenceURLs) > mediadomain.MaxInputImages { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", fmt.Sprintf("reference_images 不能超过 %d 张", mediadomain.MaxInputImages)) + return + } + hasReferenceMode := len(referenceURLs) > 0 || len(referenceAudios) > 0 + if hasReferenceMode { + if prompt == "" { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "参考图/参考音频视频必须提供 prompt") + return + } + if resolution == "1080p" { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "参考图视频 resolution 最高 720p") + return + } + } + if prompt == "" && imageURL == "" && !hasReferenceMode { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "文本生视频必须提供 prompt;图片生视频可以省略 prompt") + return + } + if request.Video != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "视频生成不支持 video 输入") + return + } + } else { + if prompt == "" { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", label+"必须提供 prompt") + return + } + if request.Video == nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", label+"必须提供 video") + return + } + value, ok := parseVideoImage(*request.Video, "video") + if !ok { + return + } + videoURL = value + if request.Image != nil || len(request.ReferenceImages) > 0 || len(request.ReferenceAudios) > 0 { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", label+"不支持 image、reference_images 或 reference_audios") + return + } + if strings.TrimSpace(request.AspectRatio) != "" || strings.TrimSpace(request.Resolution) != "" { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", label+"不支持 aspect_ratio 或 resolution") + return + } + if operation == gatewayVideoOperationEdit { + if hasJSONValue(request.Duration) { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "视频编辑不支持 duration") return } - referenceURLs = append(referenceURLs, gateway.VideoInputFileReference(fileID)) } else { - referenceURLs = append(referenceURLs, urlValue) + // extend: duration optional, default 6, range 2-10 + if hasJSONValue(request.Duration) { + var err error + duration, err = parseVideoDuration(request.Duration) + if err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", err.Error()) + return + } + } else { + duration = 6 + } + if duration < 2 || duration > 10 { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "视频延长 duration 必须在 2 到 10 秒之间") + return + } } } - if prompt == "" && len(referenceURLs) == 0 { - writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "文本生视频必须提供 prompt;图片生视频可以省略 prompt") - return - } + clientKey, requestID, ok := requestIdentity(c) if !ok { return } + var op provider.VideoOperation + switch operation { + case gatewayVideoOperationEdit: + op = provider.VideoOperationEdit + case gatewayVideoOperationExtend: + op = provider.VideoOperationExtend + default: + op = provider.VideoOperationGenerate + } job, err := h.gateway.CreateVideo(c.Request.Context(), gateway.VideoInput{ RequestID: requestID, ClientKey: clientKey, PublicModel: model, - Prompt: prompt, Duration: duration, AspectRatio: aspectRatio, Resolution: resolution, - ReferenceURLs: referenceURLs, + Operation: op, + Prompt: prompt, Duration: duration, AspectRatio: aspectRatio, Resolution: resolution, + ImageURL: imageURL, ReferenceURLs: referenceURLs, ReferenceAudios: referenceAudios, VideoURL: videoURL, }) if err != nil { writeGatewayError(c, err) @@ -742,17 +942,22 @@ func writeVideoContent(c *gin.Context, body io.Reader, contentType string, size writeOpenAIError(c, http.StatusBadGateway, "media_too_large", "上游媒体超过 2 GiB 安全上限") return } - c.Header("Content-Type", contentType) + contentType, ok := normalizeVideoResponseContentType(contentType) + if !ok { + writeOpenAIError(c, http.StatusBadGateway, "invalid_media_type", "上游视频服务返回了不受支持的内容类型") + return + } c.Header("Content-Disposition", "inline") c.Header("Cache-Control", "private, no-store") c.Header("X-Content-Type-Options", "nosniff") + c.Header("Content-Security-Policy", "default-src 'none'; sandbox") + c.Header("Referrer-Policy", "no-referrer") if size >= 0 { c.Header("Content-Length", strconv.FormatInt(size, 10)) } else { c.Header("Trailer", mediaTransferErrorTrailer) } - c.Status(http.StatusOK) - if err := copyMedia(responseDeadlineWriter{ResponseWriter: c.Writer}, body, maxMediaResponseTransferBytes); err != nil && size < 0 { + if err := writeMediaBody(c, body, contentType, http.StatusOK, maxMediaResponseTransferBytes); err != nil && size < 0 { errorCode := "stream_interrupted" if errors.Is(err, errResponseTransferLimit) { errorCode = "response_too_large" @@ -761,6 +966,19 @@ func writeVideoContent(c *gin.Context, body io.Reader, contentType string, size } } +func normalizeVideoResponseContentType(value string) (string, bool) { + mediaType, _, err := mime.ParseMediaType(strings.TrimSpace(value)) + if err != nil { + return "", false + } + switch strings.ToLower(mediaType) { + case "video/mp4", "video/quicktime", "video/webm": + return strings.ToLower(mediaType), true + default: + return "", false + } +} + func parseVideoDuration(durationRaw json.RawMessage) (int, error) { duration, hasDuration, err := parseOptionalVideoInteger(durationRaw) if err != nil { @@ -834,9 +1052,17 @@ func videoGenerationResponse(job mediadomain.Job, contentURLs ...string) gin.H { if len(contentURLs) > 0 && contentURLs[0] != "" { videoURL = contentURLs[0] } + video := gin.H{"url": videoURL, "respect_moderation": true} + operation := job.Operation + if operation == "" { + operation = mediadomain.VideoOperationGenerate + } + if operation == mediadomain.VideoOperationGenerate && job.Seconds > 0 { + video["duration"] = job.Seconds + } return gin.H{ "status": "done", "model": job.Model, "progress": 100, - "video": gin.H{"url": videoURL, "duration": job.Seconds, "respect_moderation": true}, + "video": video, } case mediadomain.StatusFailed: return gin.H{ @@ -1687,6 +1913,9 @@ func writeGatewayError(c *gin.Context, err error) { case errors.Is(err, gateway.ErrVideoInputTooLarge), errors.Is(err, gateway.ErrVideoInputUnavailable): status, code = http.StatusBadRequest, "invalid_request" message = err.Error() + case errors.Is(err, gateway.ErrVideoOperationUnsupported): + status, code = http.StatusBadRequest, "unsupported_model" + message = err.Error() case errors.As(err, &upstreamFailure): if isSanitizedUpstreamAvailabilityFailure(upstreamFailure) { // Gateway mid-tier behavior: never expose upstream upgrade/billing prompts to clients. diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go index 3b16d30d..75a7dc69 100644 --- a/backend/internal/transport/http/inference/handler_test.go +++ b/backend/internal/transport/http/inference/handler_test.go @@ -344,6 +344,85 @@ func TestDirectUpstreamCredentialResponsesAreRewritten(t *testing.T) { } } +func TestMediaResultRejectsActiveContentAndRedirects(t *testing.T) { + gin.SetMode(gin.TestMode) + handler := NewHandler(nil, nil, 1<<20) + for _, tc := range []struct { + name string + status int + contentType string + headers http.Header + }{ + {name: "html", status: http.StatusOK, contentType: "text/html; charset=utf-8"}, + {name: "svg", status: http.StatusOK, contentType: "image/svg+xml"}, + {name: "redirect", status: http.StatusFound, contentType: "text/plain", headers: http.Header{"Location": {"javascript:alert(1)"}}}, + } { + t.Run(tc.name, func(t *testing.T) { + finalCode := "" + header := make(http.Header) + for name, values := range tc.headers { + header[name] = append([]string(nil), values...) + } + header.Set("Content-Type", tc.contentType) + result := &gateway.Result{ + StatusCode: tc.status, + Header: header, + Body: io.NopCloser(strings.NewReader(``)), + Finalize: func(_ gateway.Usage, _, code string) { + finalCode = code + }, + } + router := gin.New() + router.GET("/", func(c *gin.Context) { handler.writeMediaResult(c, result) }) + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) + if recorder.Code != http.StatusBadGateway || strings.Contains(recorder.Body.String(), "must-not-reflect") || recorder.Header().Get("Location") != "" || finalCode == "" { + t.Fatalf("status=%d headers=%#v body=%s finalize=%q", recorder.Code, recorder.Header(), recorder.Body.String(), finalCode) + } + }) + } +} + +func TestMediaResultPinsSafeResponseHeaders(t *testing.T) { + gin.SetMode(gin.TestMode) + handler := NewHandler(nil, nil, 1<<20) + result := &gateway.Result{ + StatusCode: http.StatusOK, + Header: http.Header{ + "Content-Type": {"audio/mpeg; attacker=ignored"}, + "Content-Length": {"5"}, + "Set-Cookie": {"upstream=secret"}, + "Location": {"javascript:alert(1)"}, + "X-Request-Id": {"upstream-request"}, + }, + Body: io.NopCloser(strings.NewReader("audio")), + Finalize: func(gateway.Usage, string, string) {}, + } + router := gin.New() + router.GET("/", func(c *gin.Context) { handler.writeMediaResult(c, result) }) + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) + if recorder.Code != http.StatusOK || recorder.Body.String() != "audio" { + t.Fatalf("status=%d body=%q", recorder.Code, recorder.Body.String()) + } + if recorder.Header().Get("Content-Type") != "audio/mpeg" || recorder.Header().Get("X-Content-Type-Options") != "nosniff" || recorder.Header().Get("Content-Security-Policy") == "" { + t.Fatalf("safe headers = %#v", recorder.Header()) + } + if recorder.Header().Get("Set-Cookie") != "" || recorder.Header().Get("Location") != "" || recorder.Header().Get("X-Request-Id") != "upstream-request" { + t.Fatalf("unsafe or missing forwarded headers = %#v", recorder.Header()) + } +} + +func TestVideoContentRejectsUnsafeContentType(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + context, _ := gin.CreateTestContext(recorder) + writeVideoContent(context, strings.NewReader(``), "text/html", -1) + if recorder.Code != http.StatusBadGateway || strings.Contains(recorder.Body.String(), "must-not-reflect") { + t.Fatalf("status=%d headers=%#v body=%s", recorder.Code, recorder.Header(), recorder.Body.String()) + } +} + func TestMessagesEndpointUsesAnthropicContract(t *testing.T) { gin.SetMode(gin.TestMode) router := gin.New() @@ -428,6 +507,11 @@ func TestVideoGenerationResponseMatchesOfficialPollingShape(t *testing.T) { if done["status"] != "done" || done["progress"] != 100 || !ok || video["url"] != "https://assets.grok.com/video.mp4" || video["duration"] != 8 || video["respect_moderation"] != true { t.Fatalf("done response=%#v", done) } + extended := videoGenerationResponse(mediadomain.Job{Operation: mediadomain.VideoOperationExtend, Status: mediadomain.StatusCompleted, Seconds: 6, UpstreamURL: "https://assets.grok.com/extended.mp4"}) + extendedVideo, ok := extended["video"].(gin.H) + if !ok || extendedVideo["duration"] != nil { + t.Fatalf("extended response exposes requested extension as output duration: %#v", extended) + } failed := videoGenerationResponse(mediadomain.Job{Status: mediadomain.StatusFailed, ErrorCode: "account_unavailable", ErrorMessage: "try later"}) errorValue, ok := failed["error"].(gin.H) if failed["status"] != "failed" || !ok || errorValue["code"] != "service_unavailable" || failed["model"] != nil || failed["progress"] != nil { @@ -447,6 +531,7 @@ func TestImageGenerationEndpointValidatesXAIContractBeforeRouting(t *testing.T) }{ {name: "zero n", body: `{"model":"grok-imagine-image","prompt":"test","n":0}`, want: "n 必须在 1 到 10 之间"}, {name: "large n", body: `{"model":"grok-imagine-image","prompt":"test","n":11}`, want: "n 必须在 1 到 10 之间"}, + {name: "invalid quality", body: `{"model":"grok-imagine-image-2.0","prompt":"test","quality":"high"}`, want: "quality 必须是 low 或 medium"}, {name: "storage options", body: `{"model":"grok-imagine-image","prompt":"test","storage_options":{"filename":"test.jpg"}}`, want: "不支持 storage_options"}, } { t.Run(test.name, func(t *testing.T) { @@ -505,6 +590,17 @@ func TestImageEditAcceptsOfficialJSONShape(t *testing.T) { t.Fatalf("invalid resolution status=%d body=%s", invalidResolutionRecorder.Code, invalidResolutionRecorder.Body.String()) } + invalidQuality := httptest.NewRequest(http.MethodPost, "/v1/images/edits", strings.NewReader(`{ + "model":"grok-imagine-image-2.0","prompt":"test","quality":"high", + "image":{"url":"https://example.com/input.png"} + }`)) + invalidQuality.Header.Set("Content-Type", "application/json") + invalidQualityRecorder := httptest.NewRecorder() + router.ServeHTTP(invalidQualityRecorder, invalidQuality) + if invalidQualityRecorder.Code != http.StatusBadRequest || !strings.Contains(invalidQualityRecorder.Body.String(), "quality 必须是 low 或 medium") { + t.Fatalf("invalid quality status=%d body=%s", invalidQualityRecorder.Code, invalidQualityRecorder.Body.String()) + } + validBatchCount := httptest.NewRequest(http.MethodPost, "/v1/images/edits", strings.NewReader(`{ "model":"grok-imagine-image-quality","prompt":"test","n":2, "image":{"url":"https://example.com/input.png"} @@ -982,24 +1078,29 @@ func TestCopyJSONForwardsBodyBeyondMetadataInspectionLimit(t *testing.T) { func TestCopyMediaRejectsUnknownLengthOverflowWithoutWritingPastLimit(t *testing.T) { payload := bytes.Repeat([]byte("v"), 33) - var destination bytes.Buffer - err := copyMedia(&destination, bytes.NewReader(payload), 32) + recorder := httptest.NewRecorder() + context, _ := gin.CreateTestContext(recorder) + err := writeMediaBody(context, bytes.NewReader(payload), "video/mp4", http.StatusOK, 32) if !errors.Is(err, errResponseTransferLimit) { t.Fatalf("copy error = %v", err) } - if destination.Len() != 32 { - t.Fatalf("forwarded media size = %d", destination.Len()) + if recorder.Body.Len() != 32 { + t.Fatalf("forwarded media size = %d", recorder.Body.Len()) } } func TestCopyMediaAllowsExactLimit(t *testing.T) { payload := bytes.Repeat([]byte("v"), 32) - var destination bytes.Buffer - if err := copyMedia(&destination, bytes.NewReader(payload), 32); err != nil { + recorder := httptest.NewRecorder() + context, _ := gin.CreateTestContext(recorder) + if err := writeMediaBody(context, bytes.NewReader(payload), "video/mp4", http.StatusOK, 32); err != nil { t.Fatal(err) } - if !bytes.Equal(destination.Bytes(), payload) { - t.Fatalf("forwarded media = %q", destination.Bytes()) + if !bytes.Equal(recorder.Body.Bytes(), payload) { + t.Fatalf("forwarded media = %q", recorder.Body.Bytes()) + } + if recorder.Header().Get("Content-Type") != "video/mp4" { + t.Fatalf("content type = %q", recorder.Header().Get("Content-Type")) } } @@ -1027,3 +1128,91 @@ func TestSelectionErrorResponseDistinguishesCoolingAndSaturation(t *testing.T) { }) } } + +func TestReferenceToVideoRequestValidation(t *testing.T) { + gin.SetMode(gin.TestMode) + handler := &Handler{maxBodyBytes: 1 << 20} + router := gin.New() + handler.Register(router.Group("/v1")) + + combined := httptest.NewRequest(http.MethodPost, "/v1/videos/generations", strings.NewReader(`{ + "model":"grok-imagine-video","prompt":"x", + "image":{"url":"https://example.com/a.png"}, + "reference_images":[{"url":"https://example.com/b.png"}] + }`)) + combined.Header.Set("Content-Type", "application/json") + combinedRec := httptest.NewRecorder() + router.ServeHTTP(combinedRec, combined) + if combinedRec.Code != http.StatusBadRequest || !strings.Contains(combinedRec.Body.String(), "不能与") { + t.Fatalf("combined image+refs status=%d body=%s", combinedRec.Code, combinedRec.Body.String()) + } + + highRes := httptest.NewRequest(http.MethodPost, "/v1/videos/generations", strings.NewReader(`{ + "model":"grok-imagine-video","prompt":"x","resolution":"1080p", + "reference_images":[{"url":"https://example.com/b.png"}] + }`)) + highRes.Header.Set("Content-Type", "application/json") + highResRec := httptest.NewRecorder() + router.ServeHTTP(highResRec, highRes) + if highResRec.Code != http.StatusBadRequest || !strings.Contains(highResRec.Body.String(), "720p") { + t.Fatalf("r2v 1080p status=%d body=%s", highResRec.Code, highResRec.Body.String()) + } + + tooManyAudio := httptest.NewRequest(http.MethodPost, "/v1/videos/generations", strings.NewReader(`{ + "model":"grok-imagine-video","prompt":"x","duration":8,"resolution":"720p", + "reference_audios":[{"voice_id":"eve"},{"voice_id":"ara"},{"voice_id":"rex"},{"voice_id":"sal"}] + }`)) + tooManyAudio.Header.Set("Content-Type", "application/json") + tooManyAudioRec := httptest.NewRecorder() + router.ServeHTTP(tooManyAudioRec, tooManyAudio) + if tooManyAudioRec.Code != http.StatusBadRequest || !strings.Contains(tooManyAudioRec.Body.String(), "最多 3") { + t.Fatalf("too many audios status=%d body=%s", tooManyAudioRec.Code, tooManyAudioRec.Body.String()) + } + + valid := httptest.NewRequest(http.MethodPost, "/v1/videos/generations", strings.NewReader(`{ + "model":"grok-imagine-video","prompt":"The person speaks","duration":8, + "aspect_ratio":"9:16","resolution":"720p", + "reference_images":[{"url":"https://example.com/p.png"}], + "reference_audios":[{"voice_id":"eve"}] + }`)) + valid.Header.Set("Content-Type", "application/json") + validRec := httptest.NewRecorder() + router.ServeHTTP(validRec, valid) + if validRec.Code != http.StatusUnauthorized { + t.Fatalf("valid r2v status=%d body=%s", validRec.Code, validRec.Body.String()) + } +} +func TestEditAndExtendVideoRequestValidation(t *testing.T) { + gin.SetMode(gin.TestMode) + handler := &Handler{maxBodyBytes: 1 << 20} + router := gin.New() + group := router.Group("/v1") + handler.Register(group) + + // Model compatibility is resolved from the selected upstream route, not the + // caller-controlled public model name. + rec := httptest.NewRecorder() + context, _ := gin.CreateTestContext(rec) + writeGatewayError(context, gateway.ErrVideoOperationUnsupported) + if rec.Code != http.StatusBadRequest { + t.Fatalf("unsupported video route status = %d body = %s", rec.Code, rec.Body.String()) + } + + // missing video on extend + req := httptest.NewRequest(http.MethodPost, "/v1/videos/extensions", strings.NewReader(`{"model":"grok-imagine-video","prompt":"x","duration":4}`)) + req.Header.Set("Content-Type", "application/json") + rec = httptest.NewRecorder() + router.ServeHTTP(rec, req) + if rec.Code != http.StatusBadRequest { + t.Fatalf("extend missing video status = %d body = %s", rec.Code, rec.Body.String()) + } + + // invalid extend duration + req = httptest.NewRequest(http.MethodPost, "/v1/videos/extensions", strings.NewReader(`{"model":"grok-imagine-video","prompt":"x","duration":15,"video":{"url":"https://example.com/a.mp4"}}`)) + req.Header.Set("Content-Type", "application/json") + rec = httptest.NewRecorder() + router.ServeHTTP(rec, req) + if rec.Code != http.StatusBadRequest { + t.Fatalf("extend bad duration status = %d body = %s", rec.Code, rec.Body.String()) + } +} diff --git a/backend/internal/transport/http/inference/openai_audio_handler.go b/backend/internal/transport/http/inference/openai_audio_handler.go new file mode 100644 index 00000000..ba964d31 --- /dev/null +++ b/backend/internal/transport/http/inference/openai_audio_handler.go @@ -0,0 +1,170 @@ +package inference + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/chenyme/grok2api/backend/internal/application/gateway" + "github.com/gin-gonic/gin" +) + +// OpenAI-compatible audio request shapes. +// https://platform.openai.com/docs/api-reference/audio +type openAISpeechRequest struct { + Model string `json:"model"` + Input string `json:"input"` + Voice string `json:"voice"` + ResponseFormat string `json:"response_format"` + Speed *float64 `json:"speed"` + // Optional Grok/Console extensions accepted without breaking OpenAI clients. + Language string `json:"language"` + VoiceID string `json:"voice_id"` + OutputFormat json.RawMessage `json:"output_format"` + OptimizeStreamingLatency json.RawMessage `json:"optimize_streaming_latency"` + TextNormalization *bool `json:"text_normalization"` + WithTimestamps *bool `json:"with_timestamps"` +} + +func (h *Handler) synthesizeOpenAISpeech(c *gin.Context) { + h.handleOpenAISpeech(c) +} + +// synthesizeOpenAIAudioTask keeps a compatibility path used by some OpenAI-style +// clients that post speech jobs to /v1/audio/tasks instead of /v1/audio/speech. +// Behavior matches /audio/speech: raw audio by default, JSON only when requested. +func (h *Handler) synthesizeOpenAIAudioTask(c *gin.Context) { + h.handleOpenAISpeech(c) +} + +func (h *Handler) handleOpenAISpeech(c *gin.Context) { + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.maxBodyBytes) + if !isJSONRequest(c) { + writeOpenAIError(c, http.StatusUnsupportedMediaType, "invalid_request", "audio speech 仅支持 application/json") + return + } + var request openAISpeechRequest + if err := decodeSingleJSON(c.Request.Body, &request, false); err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "audio speech 请求无效") + return + } + + text := strings.TrimSpace(request.Input) + if text == "" { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "input 不能为空") + return + } + language := strings.TrimSpace(request.Language) + if language == "" { + // Console TTS requires language; default keeps OpenAI clients working. + language = "en" + } + model := strings.TrimSpace(request.Model) + if model == "" { + model = "grok-voice-latest" + } + voiceID := firstNonEmpty(strings.TrimSpace(request.VoiceID), strings.TrimSpace(request.Voice)) + if mapped := mapOpenAIVoiceID(voiceID); mapped != "" { + voiceID = mapped + } + + format, err := parseTTSOutputFormat(request.OutputFormat) + if err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", err.Error()) + return + } + if format.Codec == "" { + if codec := mapOpenAIResponseFormat(request.ResponseFormat); codec != "" { + format.Codec = codec + } else if strings.TrimSpace(request.ResponseFormat) != "" { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "response_format 不受支持") + return + } else { + format.Codec = "mp3" + } + } + + speed, err := parseTTSSpeed(request.Speed) + if err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", err.Error()) + return + } + optimize, err := parseOptimizeStreamingLatency(request.OptimizeStreamingLatency) + if err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", err.Error()) + return + } + + clientKey, requestID, ok := requestIdentity(c) + if !ok { + return + } + input := gateway.TTSInput{ + RequestID: requestID, + ClientKey: clientKey, + PublicModel: model, + Text: text, + VoiceID: voiceID, + Language: language, + OutputFormat: format, + Speed: speed, + OptimizeStreamingLatency: optimize, + } + if request.TextNormalization != nil { + input.TextNormalization = *request.TextNormalization + } + if request.WithTimestamps != nil { + input.WithTimestamps = *request.WithTimestamps + } + + result, err := h.gateway.SynthesizeSpeech(c.Request.Context(), input) + if err != nil { + writeGatewayError(c, err) + return + } + h.writeMediaResult(c, result) +} + +func (h *Handler) transcribeOpenAIAudio(c *gin.Context) { + h.transcribeSpeechRequest(c, true) +} + +func mapOpenAIResponseFormat(value string) string { + switch strings.ToLower(strings.TrimSpace(value)) { + case "", "mp3": + return "mp3" + case "opus", "ogg": + return "opus" + case "aac": + return "aac" + case "flac": + return "flac" + case "wav", "wave": + return "wav" + case "pcm", "pcm16": + return "pcm" + default: + return "" + } +} + +// mapOpenAIVoiceID keeps common OpenAI voice names usable against Console voices. +// Unknown values pass through so custom voice_id and built-in Grok ids still work. +func mapOpenAIVoiceID(voice string) string { + switch strings.ToLower(strings.TrimSpace(voice)) { + case "alloy", "verse": + return "ara" + case "echo", "ballad": + return "eve" + case "fable", "coral": + return "sal" + case "onyx", "ash": + return "rex" + case "nova", "sage": + return "leo" + case "shimmer", "marin": + return "sia" + default: + return strings.TrimSpace(voice) + } +} diff --git a/backend/internal/transport/http/inference/openai_audio_handler_test.go b/backend/internal/transport/http/inference/openai_audio_handler_test.go new file mode 100644 index 00000000..56b9fb99 --- /dev/null +++ b/backend/internal/transport/http/inference/openai_audio_handler_test.go @@ -0,0 +1,138 @@ +package inference + +import ( + "math" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" +) + +func TestStreamingSTTDurationAcceptsOnlyCompletedFiniteEvents(t *testing.T) { + duration, ok := streamingSTTDuration([]byte(`{"type":"transcript.done","duration":3.45,"text":"hello"}`)) + if !ok || math.Abs(duration-3.45) > 1e-9 { + t.Fatalf("completed duration = %v, ok = %t", duration, ok) + } + for _, payload := range [][]byte{ + []byte(`{"type":"transcript.delta","duration":3.45}`), + []byte(`{"type":"transcript.done","duration":0}`), + []byte(`{"type":"transcript.done","duration":"3.45"}`), + []byte(`not-json`), + } { + if duration, ok := streamingSTTDuration(payload); ok || duration != 0 { + t.Fatalf("invalid payload %q produced duration %v, ok = %t", payload, duration, ok) + } + } +} + +func TestOpenAIAudioSpeechValidatesAndMapsFields(t *testing.T) { + gin.SetMode(gin.TestMode) + router := gin.New() + NewHandler(nil, nil, 1<<20).Register(router.Group("/v1")) + + missingInput := httptest.NewRequest(http.MethodPost, "/v1/audio/speech", strings.NewReader(`{"model":"grok-voice-latest","voice":"alloy"}`)) + missingInput.Header.Set("Content-Type", "application/json") + missingRecorder := httptest.NewRecorder() + router.ServeHTTP(missingRecorder, missingInput) + if missingRecorder.Code != http.StatusBadRequest || !strings.Contains(missingRecorder.Body.String(), "input") { + t.Fatalf("missing input status=%d body=%s", missingRecorder.Code, missingRecorder.Body.String()) + } + + badFormat := httptest.NewRequest(http.MethodPost, "/v1/audio/speech", strings.NewReader(`{"model":"grok-voice-latest","input":"hi","response_format":"midi"}`)) + badFormat.Header.Set("Content-Type", "application/json") + badFormatRecorder := httptest.NewRecorder() + router.ServeHTTP(badFormatRecorder, badFormat) + if badFormatRecorder.Code != http.StatusBadRequest || !strings.Contains(badFormatRecorder.Body.String(), "response_format") { + t.Fatalf("bad format status=%d body=%s", badFormatRecorder.Code, badFormatRecorder.Body.String()) + } + + // Reach auth after successful mapping/validation. + valid := httptest.NewRequest(http.MethodPost, "/v1/audio/speech", strings.NewReader(`{ + "model":"grok-voice-latest","input":"Hello from OpenAI clients.","voice":"alloy","response_format":"mp3","speed":1.0 + }`)) + valid.Header.Set("Content-Type", "application/json") + validRecorder := httptest.NewRecorder() + router.ServeHTTP(validRecorder, valid) + if validRecorder.Code != http.StatusUnauthorized { + t.Fatalf("valid openai speech status=%d body=%s", validRecorder.Code, validRecorder.Body.String()) + } + + task := httptest.NewRequest(http.MethodPost, "/v1/audio/tasks", strings.NewReader(`{ + "model":"grok-voice-latest","input":"Hello from OpenAI clients.","voice":"nova" + }`)) + task.Header.Set("Content-Type", "application/json") + taskRecorder := httptest.NewRecorder() + router.ServeHTTP(taskRecorder, task) + if taskRecorder.Code != http.StatusUnauthorized { + t.Fatalf("valid openai audio task status=%d body=%s", taskRecorder.Code, taskRecorder.Body.String()) + } + + transcription := httptest.NewRequest(http.MethodPost, "/v1/audio/transcriptions", strings.NewReader(`{"model":"grok-stt","url":"https://example.com/a.wav"}`)) + transcription.Header.Set("Content-Type", "application/json") + transcriptionRecorder := httptest.NewRecorder() + router.ServeHTTP(transcriptionRecorder, transcription) + if transcriptionRecorder.Code != http.StatusUnauthorized { + t.Fatalf("openai transcription status=%d body=%s", transcriptionRecorder.Code, transcriptionRecorder.Body.String()) + } + + badTranscriptionFormat := httptest.NewRequest(http.MethodPost, "/v1/audio/transcriptions", strings.NewReader(`{"model":"grok-stt","url":"https://example.com/a.wav","response_format":"srt"}`)) + badTranscriptionFormat.Header.Set("Content-Type", "application/json") + badTranscriptionRecorder := httptest.NewRecorder() + router.ServeHTTP(badTranscriptionRecorder, badTranscriptionFormat) + if badTranscriptionRecorder.Code != http.StatusBadRequest || !strings.Contains(badTranscriptionRecorder.Body.String(), "response_format") { + t.Fatalf("bad transcription format status=%d body=%s", badTranscriptionRecorder.Code, badTranscriptionRecorder.Body.String()) + } + + unsupportedPrompt := httptest.NewRequest(http.MethodPost, "/v1/audio/transcriptions", strings.NewReader(`{"model":"grok-stt","url":"https://example.com/a.wav","prompt":"special spelling"}`)) + unsupportedPrompt.Header.Set("Content-Type", "application/json") + unsupportedPromptRecorder := httptest.NewRecorder() + router.ServeHTTP(unsupportedPromptRecorder, unsupportedPrompt) + if unsupportedPromptRecorder.Code != http.StatusBadRequest || !strings.Contains(unsupportedPromptRecorder.Body.String(), "prompt") { + t.Fatalf("unsupported prompt status=%d body=%s", unsupportedPromptRecorder.Code, unsupportedPromptRecorder.Body.String()) + } + + translation := httptest.NewRequest(http.MethodPost, "/v1/audio/translations", strings.NewReader(`{"model":"grok-stt","url":"https://example.com/a.wav"}`)) + translation.Header.Set("Content-Type", "application/json") + translationRecorder := httptest.NewRecorder() + router.ServeHTTP(translationRecorder, translation) + if translationRecorder.Code != http.StatusNotFound { + t.Fatalf("unsupported translation status=%d body=%s", translationRecorder.Code, translationRecorder.Body.String()) + } +} + +func TestTTSOptionValidationIsSharedByNativeAndOpenAIHandlers(t *testing.T) { + if _, err := parseTTSSpeed(float64Pointer(0.2)); err == nil { + t.Fatal("invalid speed was accepted") + } + if _, err := parseOptimizeStreamingLatency([]byte(`2.5`)); err == nil { + t.Fatal("fractional optimize_streaming_latency was accepted") + } + if _, err := parseOptimizeStreamingLatency([]byte(`"invalid"`)); err == nil { + t.Fatal("invalid optimize_streaming_latency was accepted") + } + if _, err := parseTTSOutputFormat([]byte(`{"codec":"mp3","sample_rate":0}`)); err == nil { + t.Fatal("invalid sample rate was accepted") + } + if value, err := parseOptimizeStreamingLatency([]byte(`"4"`)); err != nil || value != 4 { + t.Fatalf("valid optimize_streaming_latency = %d, %v", value, err) + } +} + +func float64Pointer(value float64) *float64 { return &value } + +func TestMapOpenAIVoiceAndFormat(t *testing.T) { + if got := mapOpenAIVoiceID("alloy"); got != "ara" { + t.Fatalf("alloy map = %q", got) + } + if got := mapOpenAIVoiceID("custom_voice_123"); got != "custom_voice_123" { + t.Fatalf("passthrough map = %q", got) + } + if got := mapOpenAIResponseFormat("wav"); got != "wav" { + t.Fatalf("wav map = %q", got) + } + if got := mapOpenAIResponseFormat("midi"); got != "" { + t.Fatalf("midi map = %q", got) + } +} diff --git a/backend/internal/transport/http/inference/voice_handler.go b/backend/internal/transport/http/inference/voice_handler.go new file mode 100644 index 00000000..b727ccd0 --- /dev/null +++ b/backend/internal/transport/http/inference/voice_handler.go @@ -0,0 +1,419 @@ +package inference + +import ( + "encoding/json" + "errors" + "io" + "math" + "net/http" + "strconv" + "strings" + + "github.com/chenyme/grok2api/backend/internal/application/gateway" + "github.com/chenyme/grok2api/backend/internal/infra/provider" + "github.com/chenyme/grok2api/backend/internal/transport/http/middleware" + "github.com/gin-gonic/gin" +) + +type ttsRequest struct { + Model string `json:"model"` + Text string `json:"text"` + VoiceID string `json:"voice_id"` + Language string `json:"language"` + OutputFormat json.RawMessage `json:"output_format"` + Speed *float64 `json:"speed"` + OptimizeStreamingLatency json.RawMessage `json:"optimize_streaming_latency"` + TextNormalization *bool `json:"text_normalization"` + WithTimestamps *bool `json:"with_timestamps"` +} + +func (h *Handler) synthesizeSpeech(c *gin.Context) { + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.maxBodyBytes) + if !isJSONRequest(c) { + writeOpenAIError(c, http.StatusUnsupportedMediaType, "invalid_request", "TTS 仅支持 application/json") + return + } + var request ttsRequest + if err := decodeSingleJSON(c.Request.Body, &request, false); err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "TTS 请求无效") + return + } + text := strings.TrimSpace(request.Text) + language := strings.TrimSpace(request.Language) + if text == "" || language == "" { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "TTS 缺少有效 text 或 language") + return + } + model := strings.TrimSpace(request.Model) + if model == "" { + model = "grok-voice-latest" + } + format, err := parseTTSOutputFormat(request.OutputFormat) + if err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", err.Error()) + return + } + speed, err := parseTTSSpeed(request.Speed) + if err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", err.Error()) + return + } + optimize, err := parseOptimizeStreamingLatency(request.OptimizeStreamingLatency) + if err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", err.Error()) + return + } + clientKey, requestID, ok := requestIdentity(c) + if !ok { + return + } + input := gateway.TTSInput{ + RequestID: requestID, ClientKey: clientKey, PublicModel: model, Text: text, VoiceID: strings.TrimSpace(request.VoiceID), + Language: language, OutputFormat: format, Speed: speed, OptimizeStreamingLatency: optimize, + } + if request.TextNormalization != nil { + input.TextNormalization = *request.TextNormalization + } + if request.WithTimestamps != nil { + input.WithTimestamps = *request.WithTimestamps + } + result, err := h.gateway.SynthesizeSpeech(c.Request.Context(), input) + if err != nil { + writeGatewayError(c, err) + return + } + h.writeMediaResult(c, result) +} + +func (h *Handler) listTTSVoices(c *gin.Context) { + clientKey, requestID, ok := requestIdentity(c) + if !ok { + return + } + model := strings.TrimSpace(c.Query("model")) + if model == "" { + model = "grok-voice-latest" + } + result, err := h.gateway.ListTTSVoices(c.Request.Context(), gateway.VoiceListInput{RequestID: requestID, ClientKey: clientKey, PublicModel: model}) + if err != nil { + writeGatewayError(c, err) + return + } + h.writeMediaResult(c, result) +} + +func (h *Handler) getTTSVoice(c *gin.Context) { + clientKey, requestID, ok := requestIdentity(c) + if !ok { + return + } + model := strings.TrimSpace(c.Query("model")) + if model == "" { + model = "grok-voice-latest" + } + result, err := h.gateway.GetTTSVoice(c.Request.Context(), gateway.VoiceIDInput{ + RequestID: requestID, ClientKey: clientKey, PublicModel: model, VoiceID: c.Param("voiceId"), + }) + if err != nil { + writeGatewayError(c, err) + return + } + h.writeMediaResult(c, result) +} + +func (h *Handler) transcribeSpeech(c *gin.Context) { + h.transcribeSpeechRequest(c, false) +} + +func (h *Handler) transcribeSpeechRequest(c *gin.Context, openAICompatible bool) { + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.maxBodyBytes) + contentType := strings.ToLower(strings.TrimSpace(c.GetHeader("Content-Type"))) + input := gateway.STTInput{PublicModel: "grok-stt"} + unsupportedOpenAIParameter := "" + if strings.HasPrefix(contentType, "multipart/form-data") { + if err := c.Request.ParseMultipartForm(h.maxBodyBytes); err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "STT multipart 请求无效") + return + } + form := c.Request.MultipartForm + get := func(name string) string { + if form == nil { + return "" + } + values := form.Value[name] + if len(values) == 0 { + return "" + } + return strings.TrimSpace(values[0]) + } + if model := get("model"); model != "" { + input.PublicModel = model + } + input.URL = get("url") + input.AudioFormat = get("audio_format") + input.SampleRate = firstNonEmpty(get("sample_rate"), get("sample_rate_hertz")) + input.Language = get("language") + if openAICompatible { + input.ResponseFormat = get("response_format") + if get("prompt") != "" { + unsupportedOpenAIParameter = "prompt" + } + if temperature := get("temperature"); temperature != "" && temperature != "0" && temperature != "0.0" { + unsupportedOpenAIParameter = "temperature" + } + if form != nil && len(form.Value["timestamp_granularities[]"]) > 0 { + unsupportedOpenAIParameter = "timestamp_granularities[]" + } + } + input.Format = parseTruthy(get("format")) + input.Multichannel = parseTruthy(get("multichannel")) + if channels := get("channels"); channels != "" { + if value, err := strconv.Atoi(channels); err == nil { + input.Channels = value + } + } + input.Diarize = parseTruthy(get("diarize")) + input.FillerWords = parseTruthy(get("filler_words")) + if form != nil { + input.KeyTerms = append([]string(nil), form.Value["keyterm"]...) + } + if threshold := get("vad_threshold"); threshold != "" { + if value, err := strconv.ParseFloat(threshold, 64); err == nil { + input.VADThreshold = &value + } + } + file, header, err := c.Request.FormFile("file") + if err == nil { + defer file.Close() + data, readErr := io.ReadAll(io.LimitReader(file, h.maxBodyBytes+1)) + if readErr != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "读取音频文件失败") + return + } + if int64(len(data)) > h.maxBodyBytes { + writeOpenAIError(c, http.StatusRequestEntityTooLarge, "request_too_large", "音频文件超过限制") + return + } + input.FileData = data + if header != nil { + input.FileName = header.Filename + input.FileMIME = header.Header.Get("Content-Type") + } + } + } else if isJSONRequest(c) { + var payload struct { + Model string `json:"model"` + URL string `json:"url"` + AudioFormat string `json:"audio_format"` + SampleRate any `json:"sample_rate"` + Language string `json:"language"` + Format any `json:"format"` + Multichannel any `json:"multichannel"` + Channels any `json:"channels"` + Diarize any `json:"diarize"` + KeyTerms []string `json:"keyterm"` + FillerWords any `json:"filler_words"` + VADThreshold *float64 `json:"vad_threshold"` + ResponseFormat string `json:"response_format"` + Prompt string `json:"prompt"` + Temperature *float64 `json:"temperature"` + TimestampGranularities []string `json:"timestamp_granularities"` + } + if err := decodeSingleJSON(c.Request.Body, &payload, false); err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "STT JSON 请求无效") + return + } + if strings.TrimSpace(payload.Model) != "" { + input.PublicModel = strings.TrimSpace(payload.Model) + } + input.URL = strings.TrimSpace(payload.URL) + input.AudioFormat = strings.TrimSpace(payload.AudioFormat) + input.SampleRate = anyString(payload.SampleRate) + input.Language = strings.TrimSpace(payload.Language) + input.Format = anyTruthy(payload.Format) + input.Multichannel = anyTruthy(payload.Multichannel) + if channels := anyString(payload.Channels); channels != "" { + if value, err := strconv.Atoi(channels); err == nil { + input.Channels = value + } + } + input.Diarize = anyTruthy(payload.Diarize) + input.KeyTerms = payload.KeyTerms + input.FillerWords = anyTruthy(payload.FillerWords) + input.VADThreshold = payload.VADThreshold + if openAICompatible { + input.ResponseFormat = strings.TrimSpace(payload.ResponseFormat) + if strings.TrimSpace(payload.Prompt) != "" { + unsupportedOpenAIParameter = "prompt" + } + if payload.Temperature != nil && *payload.Temperature != 0 { + unsupportedOpenAIParameter = "temperature" + } + if len(payload.TimestampGranularities) > 0 { + unsupportedOpenAIParameter = "timestamp_granularities" + } + } + } else { + writeOpenAIError(c, http.StatusUnsupportedMediaType, "invalid_request", "STT 支持 multipart/form-data 或 application/json") + return + } + if openAICompatible { + if unsupportedOpenAIParameter != "" { + writeOpenAIError(c, http.StatusBadRequest, "unsupported_parameter", unsupportedOpenAIParameter+" 暂不支持,不能无损转换到 Console STT") + return + } + input.ResponseFormat = strings.ToLower(strings.TrimSpace(input.ResponseFormat)) + if input.ResponseFormat == "" { + input.ResponseFormat = "json" + } + switch input.ResponseFormat { + case "json", "verbose_json", "text": + default: + writeOpenAIError(c, http.StatusBadRequest, "invalid_parameter", "response_format 必须是 json、verbose_json 或 text") + return + } + } + if len(input.FileData) == 0 && strings.TrimSpace(input.URL) == "" { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "STT 必须提供 file 或 url") + return + } + clientKey, requestID, ok := requestIdentity(c) + if !ok { + return + } + input.ClientKey = clientKey + input.RequestID = requestID + result, err := h.gateway.TranscribeSpeech(c.Request.Context(), input) + if err != nil { + writeGatewayError(c, err) + return + } + h.writeMediaResult(c, result) +} + +func bytesTrim(value json.RawMessage) []byte { + return []byte(strings.TrimSpace(string(value))) +} + +func parseTTSOutputFormat(value json.RawMessage) (provider.TTSOutputFormat, error) { + format := provider.TTSOutputFormat{} + if len(bytesTrim(value)) == 0 { + return format, nil + } + var raw struct { + Codec string `json:"codec"` + SampleRate *int `json:"sample_rate"` + BitRate *int `json:"bit_rate"` + } + if err := json.Unmarshal(value, &raw); err != nil { + return format, errors.New("output_format 无效") + } + format.Codec = strings.ToLower(strings.TrimSpace(raw.Codec)) + if raw.SampleRate != nil { + if *raw.SampleRate <= 0 { + return provider.TTSOutputFormat{}, errors.New("output_format.sample_rate 必须大于 0") + } + format.SampleRate = *raw.SampleRate + } + if raw.BitRate != nil { + if *raw.BitRate <= 0 { + return provider.TTSOutputFormat{}, errors.New("output_format.bit_rate 必须大于 0") + } + format.BitRate = *raw.BitRate + } + return format, nil +} + +func parseTTSSpeed(value *float64) (float64, error) { + if value == nil { + return 0, nil + } + if math.IsNaN(*value) || math.IsInf(*value, 0) || *value < 0.25 || *value > 4 { + return 0, errors.New("speed 必须在 0.25 到 4.0 之间") + } + return *value, nil +} + +func parseOptimizeStreamingLatency(value json.RawMessage) (int, error) { + if len(bytesTrim(value)) == 0 { + return 0, nil + } + var result int + var asString string + if json.Unmarshal(value, &asString) == nil { + parsed, err := strconv.Atoi(strings.TrimSpace(asString)) + if err != nil { + return 0, errors.New("optimize_streaming_latency 必须是 0 到 4 的整数") + } + result = parsed + } else { + var asNumber float64 + if json.Unmarshal(value, &asNumber) != nil || math.IsNaN(asNumber) || math.IsInf(asNumber, 0) || math.Trunc(asNumber) != asNumber { + return 0, errors.New("optimize_streaming_latency 必须是 0 到 4 的整数") + } + result = int(asNumber) + } + if result < 0 || result > 4 { + return 0, errors.New("optimize_streaming_latency 必须是 0 到 4 的整数") + } + return result, nil +} + +func parseTruthy(value string) bool { + switch strings.ToLower(strings.TrimSpace(value)) { + case "1", "true", "yes", "on": + return true + default: + return false + } +} + +func anyTruthy(value any) bool { + switch typed := value.(type) { + case nil: + return false + case bool: + return typed + case string: + return parseTruthy(typed) + case float64: + return typed != 0 + default: + return false + } +} + +func anyString(value any) string { + switch typed := value.(type) { + case nil: + return "" + case string: + return strings.TrimSpace(typed) + case float64: + return strconv.FormatInt(int64(typed), 10) + case json.Number: + return typed.String() + default: + return strings.TrimSpace(stringify(value)) + } +} + +func stringify(value any) string { + data, err := json.Marshal(value) + if err != nil { + return "" + } + return strings.Trim(string(data), `"`) +} + +func firstNonEmpty(values ...string) string { + for _, value := range values { + if strings.TrimSpace(value) != "" { + return strings.TrimSpace(value) + } + } + return "" +} + +// keep middleware import used for request identity compatibility in package docs. +var _ = middleware.ClientKey diff --git a/backend/internal/transport/http/inference/voice_ws_handler.go b/backend/internal/transport/http/inference/voice_ws_handler.go new file mode 100644 index 00000000..f9d35af3 --- /dev/null +++ b/backend/internal/transport/http/inference/voice_ws_handler.go @@ -0,0 +1,156 @@ +package inference + +import ( + "encoding/json" + "io" + "math" + "net/http" + "strings" + "sync" + + upstreamws "github.com/bogdanfinn/websocket" + "github.com/chenyme/grok2api/backend/internal/application/gateway" + "github.com/gin-gonic/gin" + clientws "github.com/gorilla/websocket" +) + +const voiceWSMessageLimit = 16 << 20 + +var voiceWSUpgrader = clientws.Upgrader{ + ReadBufferSize: 32 << 10, + WriteBufferSize: 32 << 10, + CheckOrigin: func(*http.Request) bool { + return true + }, + EnableCompression: true, +} + +func (h *Handler) proxyRealtimeWebSocket(c *gin.Context) { + h.proxyVoiceWebSocket(c, "/realtime") +} + +func (h *Handler) proxySTTWebSocket(c *gin.Context) { + if !clientws.IsWebSocketUpgrade(c.Request) { + writeOpenAIError(c, http.StatusMethodNotAllowed, "invalid_request", "STT 流式接口需要 WebSocket Upgrade") + return + } + h.proxyVoiceWebSocket(c, "/stt") +} + +func (h *Handler) proxyVoiceWebSocket(c *gin.Context, pathValue string) { + if !clientws.IsWebSocketUpgrade(c.Request) { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "请求不是有效的 WebSocket Upgrade") + return + } + clientKey, requestID, ok := requestIdentity(c) + if !ok { + return + } + model := strings.TrimSpace(c.Query("model")) + session, err := h.gateway.OpenVoiceWebSocket(c.Request.Context(), gateway.VoiceWebSocketInput{ + RequestID: requestID, ClientKey: clientKey, PublicModel: model, Path: pathValue, + }) + if err != nil { + writeGatewayError(c, err) + return + } + + clientConn, err := voiceWSUpgrader.Upgrade(c.Writer, c.Request, nil) + if err != nil { + session.Finalize(gateway.VoiceWebSocketOutcome{ErrorCode: "client_upgrade_failed"}) + return + } + clientConn.SetReadLimit(voiceWSMessageLimit) + session.Conn.SetReadLimit(voiceWSMessageLimit) + + var once sync.Once + var outcomeMu sync.Mutex + outcome := gateway.VoiceWebSocketOutcome{} + closeAll := func() { + once.Do(func() { + _ = clientConn.Close() + if session.Conn != nil { + _ = session.Conn.Close() + } + outcomeMu.Lock() + finalOutcome := outcome + outcomeMu.Unlock() + session.Finalize(finalOutcome) + }) + } + defer closeAll() + + type pumpResult struct { + upstreamSide bool + result voiceWSPumpResult + } + errCh := make(chan pumpResult, 2) + go func() { + errCh <- pumpResult{result: proxyVoiceWSPump(func() (int, []byte, error) { + return clientConn.ReadMessage() + }, session.Conn.WriteMessage)} + }() + go func() { + errCh <- pumpResult{upstreamSide: true, result: proxyVoiceWSPump(func() (int, []byte, error) { + messageType, payload, readErr := session.Conn.ReadMessage() + if readErr == nil && pathValue == "/stt" { + if duration, ok := streamingSTTDuration(payload); ok { + outcomeMu.Lock() + outcome.AudioDurationSeconds = max(outcome.AudioDurationSeconds, duration) + outcomeMu.Unlock() + } + } + return messageType, payload, readErr + }, clientConn.WriteMessage)} + }() + first := <-errCh + if !isNormalVoiceWSClose(first.result.err) { + outcomeMu.Lock() + if (first.upstreamSide && !first.result.writeFailed) || (!first.upstreamSide && first.result.writeFailed) { + outcome.ErrorCode = "upstream_stream_interrupted" + outcome.UpstreamFailed = true + } else { + outcome.ErrorCode = "client_stream_interrupted" + } + outcomeMu.Unlock() + } +} + +func streamingSTTDuration(payload []byte) (float64, bool) { + var event struct { + Type string `json:"type"` + Duration float64 `json:"duration"` + } + if err := json.Unmarshal(payload, &event); err != nil || strings.TrimSpace(event.Type) != "transcript.done" { + return 0, false + } + if event.Duration <= 0 || math.IsNaN(event.Duration) || math.IsInf(event.Duration, 0) { + return 0, false + } + return event.Duration, true +} + +type voiceWSPumpResult struct { + err error + writeFailed bool +} + +func proxyVoiceWSPump(read func() (int, []byte, error), write func(int, []byte) error) voiceWSPumpResult { + for { + messageType, payload, err := read() + if err != nil { + return voiceWSPumpResult{err: err} + } + if err := write(messageType, payload); err != nil { + return voiceWSPumpResult{err: err, writeFailed: true} + } + } +} + +func isNormalVoiceWSClose(err error) bool { + if err == nil || err == io.EOF { + return true + } + return clientws.IsCloseError(err, clientws.CloseNormalClosure, clientws.CloseGoingAway) || + upstreamws.IsCloseError(err, upstreamws.CloseNormalClosure, upstreamws.CloseGoingAway) +} diff --git a/backend/internal/transport/http/media/handler.go b/backend/internal/transport/http/media/handler.go index 01f10527..7165f46e 100644 --- a/backend/internal/transport/http/media/handler.go +++ b/backend/internal/transport/http/media/handler.go @@ -38,7 +38,7 @@ func (h *Handler) RegisterAdmin(router *gin.RouterGroup) { router.DELETE("/media/images", h.deleteImages) router.GET("/media/images/stats", h.imageStats) router.POST("/media/inputs/import", h.importInputImageFromURL) - router.POST("/media/inputs/upload", h.uploadInputImage) + router.POST("/media/inputs/upload", h.uploadInputAsset) router.GET("/media/videos", h.listVideos) router.DELETE("/media/videos", h.deleteVideos) router.GET("/media/videos/stats", h.videoStats) diff --git a/backend/internal/transport/http/media/ingest.go b/backend/internal/transport/http/media/ingest.go index 5a401caf..23ff13a2 100644 --- a/backend/internal/transport/http/media/ingest.go +++ b/backend/internal/transport/http/media/ingest.go @@ -1,6 +1,7 @@ package media import ( + "bytes" "context" "crypto/tls" "errors" @@ -15,6 +16,7 @@ import ( "time" mediaapp "github.com/chenyme/grok2api/backend/internal/application/media" + mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media" "github.com/chenyme/grok2api/backend/internal/pkg/netguard" "github.com/chenyme/grok2api/backend/internal/shared/response" "github.com/gin-gonic/gin" @@ -22,7 +24,7 @@ import ( const ( // 20 MiB 为各 Provider 的共同安全输入上限,同时为全局 32 MiB multipart 请求上限保留编码开销。 - ingestMaxImageBytes = 20 << 20 + ingestMaxImageBytes = mediadomain.MaxInputAssetBytes // ingestFetchTimeout 是 URL 导入单次抓取的整体超时。 ingestFetchTimeout = 20 * time.Second // ingestResolveTimeout 限制每个重定向目标的 DNS 解析时间。 @@ -290,8 +292,8 @@ func (h *Handler) importInputImageFromURL(c *gin.Context) { h.saveIngestedImage(c, data) } -// uploadInputImage 接收管理员上传的本地图片文件(multipart 字段名 file),登记到临时输入区。 -func (h *Handler) uploadInputImage(c *gin.Context) { +// uploadInputAsset 接收管理员上传的本地图片或视频(multipart 字段名 file),登记到临时输入区。 +func (h *Handler) uploadInputAsset(c *gin.Context) { if !h.acquireIngest(c) { return } @@ -300,14 +302,14 @@ func (h *Handler) uploadInputImage(c *gin.Context) { if err != nil { var maxBytesError *http.MaxBytesError if errors.As(err, &maxBytesError) { - response.Error(c, http.StatusRequestEntityTooLarge, "imageTooLarge", "图片超过请求大小上限") + response.Error(c, http.StatusRequestEntityTooLarge, "mediaTooLarge", "文件超过请求大小上限") return } response.Error(c, http.StatusBadRequest, "invalidRequest", "缺少上传文件") return } if fileHeader.Size > ingestMaxImageBytes { - response.Error(c, http.StatusRequestEntityTooLarge, "imageTooLarge", "图片超过大小上限") + response.Error(c, http.StatusRequestEntityTooLarge, "mediaTooLarge", "文件超过大小上限") return } src, err := fileHeader.Open() @@ -322,10 +324,38 @@ func (h *Handler) uploadInputImage(c *gin.Context) { return } if int64(len(data)) > ingestMaxImageBytes { - response.Error(c, http.StatusRequestEntityTooLarge, "imageTooLarge", "图片超过大小上限") + response.Error(c, http.StatusRequestEntityTooLarge, "mediaTooLarge", "文件超过大小上限") return } - h.saveIngestedImage(c, data) + declaredMIME := strings.ToLower(strings.TrimSpace(strings.Split(fileHeader.Header.Get("Content-Type"), ";")[0])) + detectedMIME := strings.ToLower(http.DetectContentType(data)) + if strings.HasPrefix(detectedMIME, "image/") { + h.saveIngestedImage(c, data) + return + } + if strings.HasPrefix(declaredMIME, "video/") || strings.HasPrefix(detectedMIME, "video/") { + contentType := declaredMIME + if contentType == "" { + contentType = detectedMIME + } + asset, saveErr := h.service.SaveInputVideo(c.Request.Context(), contentType, bytes.NewReader(data)) + if saveErr != nil { + switch { + case errors.Is(saveErr, mediaapp.ErrVideoUploadTooLarge): + response.Error(c, http.StatusRequestEntityTooLarge, "mediaTooLarge", "视频超过大小上限") + case errors.Is(saveErr, mediaapp.ErrInvalidVideoUpload): + response.Error(c, http.StatusBadRequest, "invalidVideo", "视频内容无效或格式不支持(mp4/webm/quicktime)") + case errors.Is(saveErr, mediaapp.ErrMediaCapacity): + response.Error(c, http.StatusInsufficientStorage, "mediaCapacityExceeded", "媒体临时存储容量不足") + default: + response.Error(c, http.StatusInternalServerError, "mediaSaveVideoFailed", "保存视频失败") + } + return + } + h.writeInputAsset(c, asset) + return + } + response.Error(c, http.StatusBadRequest, "invalidMedia", "仅支持图片或视频文件") } // saveIngestedImage 收口两种临时输入路径:校验、落盘并登记 TTL,不进入图库。 @@ -343,12 +373,16 @@ func (h *Handler) saveIngestedImage(c *gin.Context, data []byte) { response.Error(c, http.StatusInternalServerError, "mediaSaveImageFailed", "保存图片失败") return } + h.writeInputAsset(c, asset) +} + +func (h *Handler) writeInputAsset(c *gin.Context, asset mediadomain.Asset) { expiresAt := "" if asset.ExpiresAt != nil { expiresAt = asset.ExpiresAt.Format(time.RFC3339) } response.Success(c, http.StatusCreated, gin.H{ - "fileId": asset.ID, "mimeType": asset.MIMEType, "sizeBytes": asset.SizeBytes, "expiresAt": expiresAt, + "fileId": asset.ID, "kind": asset.Kind, "mimeType": asset.MIMEType, "sizeBytes": asset.SizeBytes, "expiresAt": expiresAt, }) } @@ -357,7 +391,7 @@ func (h *Handler) acquireIngest(c *gin.Context) bool { case h.ingestSlots <- struct{}{}: return true default: - response.Error(c, http.StatusServiceUnavailable, "mediaIngestBusy", "图片暂存并发已满,请稍后重试") + response.Error(c, http.StatusServiceUnavailable, "mediaIngestBusy", "媒体暂存并发已满,请稍后重试") return false } } diff --git a/backend/internal/transport/http/middleware/body_memory.go b/backend/internal/transport/http/middleware/body_memory.go index baab60a9..37e7d0e0 100644 --- a/backend/internal/transport/http/middleware/body_memory.go +++ b/backend/internal/transport/http/middleware/body_memory.go @@ -94,8 +94,22 @@ func inferenceBodyOperation(path string) string { return "image_generation" case "/v1/images/edits": return "image_edit" + case "/v1/tts": + return "tts" + case "/v1/stt": + return "stt" + case "/v1/audio/speech", "/v1/audio/tasks": + return "tts" + case "/v1/audio/transcriptions": + return "stt" + case "/v1/realtime": + return "realtime_websocket" case "/v1/videos/generations": return "video_generation" + case "/v1/videos/edits": + return "video_edit" + case "/v1/videos/extensions": + return "video_extension" default: return "other" } diff --git a/backend/internal/transport/http/swagger_annotations.go b/backend/internal/transport/http/swagger_annotations.go index 14304874..6d265f00 100644 --- a/backend/internal/transport/http/swagger_annotations.go +++ b/backend/internal/transport/http/swagger_annotations.go @@ -63,12 +63,28 @@ type SwaggerImageEditRequest struct { } // SwaggerVideoGenerationRequest 表示视频生成请求。 +// image 与 reference_images/reference_audios 互斥;参考图模式 resolution 最高 720p。 type SwaggerVideoGenerationRequest struct { - Model string `json:"model" example:"grok-imagine-video"` - Prompt string `json:"prompt" example:"A cinematic tracking shot in the rain"` - Duration int `json:"duration" example:"8"` - AspectRatio string `json:"aspect_ratio,omitempty" example:"16:9"` - Resolution string `json:"resolution,omitempty" example:"720p"` + Model string `json:"model" example:"grok-imagine-video"` + Prompt string `json:"prompt" example:"A cinematic tracking shot in the rain"` + Duration int `json:"duration" example:"8"` + AspectRatio string `json:"aspect_ratio,omitempty" example:"16:9"` + Resolution string `json:"resolution,omitempty" example:"720p"` + Image *SwaggerVideoMediaInput `json:"image,omitempty"` + ReferenceImages []SwaggerVideoMediaInput `json:"reference_images,omitempty"` + ReferenceAudios []SwaggerVideoAudioInput `json:"reference_audios,omitempty"` + Video *SwaggerVideoMediaInput `json:"video,omitempty"` +} + +// SwaggerVideoMediaInput 表示视频相关的图片/视频输入。 +type SwaggerVideoMediaInput struct { + URL string `json:"url,omitempty" example:"https://example.com/input.png"` + FileID string `json:"file_id,omitempty" example:"file_123"` +} + +// SwaggerVideoAudioInput 表示参考音频(内置 voice_id)。 +type SwaggerVideoAudioInput struct { + VoiceID string `json:"voice_id" example:"eve"` } // swaggerHealth godoc @@ -217,6 +233,30 @@ func swaggerGetImage() {} // @Router /v1/videos/generations [post] func swaggerGenerateVideo() {} +// swaggerEditVideo godoc +// @Summary 创建异步视频编辑任务 +// @Tags Videos +// @Security BearerAuth +// @Accept json +// @Produce json +// @Param request body SwaggerVideoGenerationRequest true "请求" +// @Success 200 {object} map[string]string +// @Failure 400 {object} map[string]any +// @Router /v1/videos/edits [post] +func swaggerEditVideo() {} + +// swaggerExtendVideo godoc +// @Summary 创建异步视频延长任务 +// @Tags Videos +// @Security BearerAuth +// @Accept json +// @Produce json +// @Param request body SwaggerVideoGenerationRequest true "请求" +// @Success 200 {object} map[string]string +// @Failure 400 {object} map[string]any +// @Router /v1/videos/extensions [post] +func swaggerExtendVideo() {} + // swaggerGetVideo godoc // @Summary 查询异步视频任务 // @Tags Videos diff --git a/frontend/src/app/app-shell.tsx b/frontend/src/app/app-shell.tsx index 168f3783..97bf6e7f 100644 --- a/frontend/src/app/app-shell.tsx +++ b/frontend/src/app/app-shell.tsx @@ -1,5 +1,5 @@ import { zodResolver } from "@hookform/resolvers/zod"; -import { Box, ChevronDown, Eye, Image, KeyRound, Languages, LayoutDashboard, LogOut, Menu, MessageSquareText, Monitor, Moon, MoreHorizontal, Settings, ShieldCheck, Sparkles, Sun, Users, Video } from "lucide-react"; +import { AudioLines, Box, ChevronDown, Eye, Image, KeyRound, Languages, LayoutDashboard, LogOut, Menu, MessageSquareText, Monitor, Moon, MoreHorizontal, Settings, ShieldCheck, Sparkles, Sun, Users, Video } from "lucide-react"; import { useTheme } from "next-themes"; import { useState, type ReactNode } from "react"; import { useForm } from "react-hook-form"; @@ -55,9 +55,24 @@ const documentation = [ icon: Video, items: [ { href: "/docs/video/generations", label: "Video Generations", method: "POST" }, + { href: "/docs/video/edits", label: "Video Edits", method: "POST" }, + { href: "/docs/video/extensions", label: "Video Extensions", method: "POST" }, { href: "/docs/video/get", label: "Get Video", method: "GET" }, ], }, + { + label: "Voice", + icon: AudioLines, + items: [ + { href: "/docs/voice/tts", label: "Text to Speech", method: "POST" }, + { href: "/docs/voice/audio-speech", label: "OpenAI Speech", method: "POST" }, + { href: "/docs/voice/audio-tasks", label: "OpenAI Audio Tasks", method: "POST" }, + { href: "/docs/voice/audio-transcriptions", label: "OpenAI Transcriptions", method: "POST" }, + { href: "/docs/voice/voices", label: "List Voices", method: "GET" }, + { href: "/docs/voice/stt", label: "Speech to Text", method: "POST" }, + { href: "/docs/voice/realtime", label: "Realtime WebSocket", method: "GET" }, + ], + }, ] as const; export function AppShell() { diff --git a/frontend/src/entities/model/model-api.ts b/frontend/src/entities/model/model-api.ts index 2303e683..f32bbb72 100644 --- a/frontend/src/entities/model/model-api.ts +++ b/frontend/src/entities/model/model-api.ts @@ -21,7 +21,7 @@ const modelRouteValidator = hasShape({ publicId: isString, provider: isOneOf("grok_build", "grok_web", "grok_console"), upstreamModel: isString, - capability: isOneOf("responses", "chat", "image", "image_edit", "video"), + capability: isOneOf("responses", "chat", "image", "image_edit", "video", "tts", "stt", "realtime"), origin: isOneOf("catalog", "discovered", "manual"), enabled: isBoolean, accountIds: isArrayOf(isString), @@ -35,7 +35,7 @@ const modelRouteValidator = hasShape({ }); const decodeModelRoute = createObjectDecoder("model route", { id: isString, publicId: isString, provider: isOneOf("grok_build", "grok_web", "grok_console"), upstreamModel: isString, - capability: isOneOf("responses", "chat", "image", "image_edit", "video"), origin: isOneOf("catalog", "discovered", "manual"), + capability: isOneOf("responses", "chat", "image", "image_edit", "video", "tts", "stt", "realtime"), origin: isOneOf("catalog", "discovered", "manual"), enabled: isBoolean, accountIds: isArrayOf(isString), bindingMode: isBoolean, supportedAccounts: isNumber, syncedAccounts: isNumber, totalAccounts: isNumber, capabilityKnown: isBoolean, available: isBoolean, lastSyncedAt: isOptional(isString), }); @@ -43,7 +43,7 @@ const decodeModelPage = createPaginatedDecoder(modelRouteValidato const modelRouteGroupValidator = hasShape({ key: isString, routes: (value) => Array.isArray(value) && value.length > 0 && value.every(modelRouteValidator), - endpointCapabilities: isArrayOf(isOneOf("completions", "responses", "messages", "image", "image_edit", "video")), + endpointCapabilities: isArrayOf(isOneOf("completions", "responses", "messages", "image", "image_edit", "video", "tts", "stt", "realtime")), }); const decodeModelGroupPage = createPaginatedDecoder(modelRouteGroupValidator); const modelAccountValidator = hasShape({ id: isString, name: isString }); diff --git a/frontend/src/entities/model/types.ts b/frontend/src/entities/model/types.ts index 997d81d6..ed36fa8b 100644 --- a/frontend/src/entities/model/types.ts +++ b/frontend/src/entities/model/types.ts @@ -3,7 +3,7 @@ export type ModelRouteDTO = { publicId: string; provider: "grok_build" | "grok_web" | "grok_console"; upstreamModel: string; - capability: "responses" | "chat" | "image" | "image_edit" | "video"; + capability: "responses" | "chat" | "image" | "image_edit" | "video" | "tts" | "stt" | "realtime"; origin: "catalog" | "discovered" | "manual"; enabled: boolean; accountIds: string[]; @@ -16,7 +16,7 @@ export type ModelRouteDTO = { lastSyncedAt?: string; }; -export type ModelEndpointCapability = "completions" | "responses" | "messages" | "image" | "image_edit" | "video"; +export type ModelEndpointCapability = "completions" | "responses" | "messages" | "image" | "image_edit" | "video" | "tts" | "stt" | "realtime"; export type ModelRouteGroupDTO = { key: string; diff --git a/frontend/src/features/accounts/account-quota.tsx b/frontend/src/features/accounts/account-quota.tsx index 778c295f..8843cb6e 100644 --- a/frontend/src/features/accounts/account-quota.tsx +++ b/frontend/src/features/accounts/account-quota.tsx @@ -103,6 +103,18 @@ function BuildQuota({ quota, billing, locale }: { quota: QuotaDTO; billing?: Bil const visibleWebQuotaModes = ["auto", "fast", "expert", "heavy"] as const; +const imagineQuotaModes = [ + { mode: "image_pro", labelKey: "imagineModeImagePro" as const }, + { mode: "image_edit", labelKey: "imagineModeImageEdit" as const }, + { mode: "video", labelKey: "imagineModeVideo" as const }, + { mode: "video_720p", labelKey: "imagineModeVideo720p" as const }, +] as const; + +function imagineWindowsOf(windows: WebQuotaWindow[]): WebQuotaWindow[] { + const known: Set = new Set(imagineQuotaModes.map((item) => item.mode)); + return windows.filter((window) => known.has(window.mode)); +} + export function ConsoleQuota({ windows, locale }: { windows: NonNullable; locale: string }) { const { t } = useTranslation(); if (windows.length === 0) return {t("accounts.quotaNotSynced")}; @@ -129,26 +141,85 @@ export function WebQuota({ windows, locale, tier }: { windows: NonNullable{t("accounts.quotaNotSynced")}; const windowsByMode = new Map(windows.map((window) => [window.mode, window])); + const imagineWindows = imagineWindowsOf(windows); const weekly = windowsByMode.get("weekly"); - if (weekly) return ; - const fast = windowsByMode.get("fast"); - if (tier === "basic" && fast) return ; + const mainBlock = (() => { + if (weekly) return ; + const fast = windowsByMode.get("fast"); + if (tier === "basic" && fast) return ; + return ( + + {visibleWebQuotaModes.map((mode) => { + const window = windowsByMode.get(mode); + if (!window) { + return {mode}-; + } + return ; + })} + + ); + })(); + + if (imagineWindows.length === 0) return mainBlock; return ( - - {visibleWebQuotaModes.map((mode) => { - const window = windowsByMode.get(mode); - if (!window) { - return {mode}-; - } - return ; - })} + + {mainBlock} + ); } type WebQuotaWindow = NonNullable[number]; +function imagineModeLabel(mode: string, t: TFunction): string { + const entry = imagineQuotaModes.find((item) => item.mode === mode); + return entry ? t(`accounts.${entry.labelKey}`) : mode; +} + +function ImagineQuotaRow({ windows, locale, t }: { windows: WebQuotaWindow[]; locale: string; t: TFunction }) { + const windowsByMode = new Map(windows.map((window) => [window.mode, window])); + const columns = imagineQuotaModes.filter((item) => windowsByMode.has(item.mode)); + if (columns.length === 0) return null; + return ( + + {columns.map(({ mode }) => { + const window = windowsByMode.get(mode)!; + const exhausted = window.remaining <= 0; + const hasTotal = window.total > 0; + const used = hasTotal ? Math.max(0, window.total - window.remaining) : 0; + const percent = hasTotal ? Math.max(0, Math.min(100, used / window.total * 100)) : 0; + const label = imagineModeLabel(mode, t); + return ( + + + + + {label} + {exhausted ? ( + {t("accounts.imagineQuotaExhausted")} + ) : hasTotal ? ( + {formatNumber(window.remaining, locale, 0)}/{formatNumber(window.total, locale, 0)} + ) : ( + {t("accounts.imagineQuotaRemaining", { remaining: formatNumber(window.remaining, locale, 0) })} + )} + + + {exhausted ? : hasTotal ? : null} + + + + + {exhausted ? t("accounts.imagineQuotaExhausted") : t("accounts.imagineQuotaRemaining", { remaining: formatNumber(window.remaining, locale, 0) })} + {window.resetAt ? t("accounts.quotaResetAt", { time: formatDateTime(window.resetAt, locale) }) : t("accounts.quotaResetUnknown")} + + + ); + })} + + ); +} + function WeeklyWebQuota({ window, locale, t }: { window: WebQuotaWindow; locale: string; t: TFunction }) { const usedPercent = Math.max(0, Math.min(100, window.usagePercent)); const breakdown = (window.breakdown ?? []).filter((item) => item.usagePercent > 0); diff --git a/frontend/src/features/audits/request-audits-api.ts b/frontend/src/features/audits/request-audits-api.ts index 925ec7dc..ffe4d976 100644 --- a/frontend/src/features/audits/request-audits-api.ts +++ b/frontend/src/features/audits/request-audits-api.ts @@ -32,7 +32,7 @@ export type AuditDTO = { modelPublicId?: string; modelUpstreamModel?: string; provider: "grok_build" | "grok_web" | "grok_console"; - operation: "responses" | "compaction" | "chat" | "messages" | "image" | "image_edit" | "video"; + operation: "responses" | "compaction" | "chat" | "messages" | "image" | "image_edit" | "video" | "tts" | "stt" | "realtime" | "voice"; usageSource: "upstream" | "estimated" | "none"; accountId?: string; accountName?: string; @@ -141,7 +141,7 @@ const auditBillingValidator = hasShape({ const auditValidator = hasShape({ id: isString, requestId: isString, clientKeyId: isString, clientKeyName: isOptional(isString), modelRouteId: isString, modelPublicId: isOptional(isString), modelUpstreamModel: isOptional(isString), provider: isOneOf("grok_build", "grok_web", "grok_console"), - operation: isOneOf("responses", "compaction", "chat", "messages", "image", "image_edit", "video"), usageSource: isOneOf("upstream", "estimated", "none"), + operation: isOneOf("responses", "compaction", "chat", "messages", "image", "image_edit", "video", "tts", "stt", "realtime", "voice"), usageSource: isOneOf("upstream", "estimated", "none"), accountId: isOptional(isString), accountName: isOptional(isString), egressNodeId: isOptional(isString), egressNodeName: isOptional(isString), egressScope: isOptional(isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset", "grok_console_asset")), egressMode: isOptional(isOneOf("direct", "proxy")), diff --git a/frontend/src/features/audits/request-audits-page.tsx b/frontend/src/features/audits/request-audits-page.tsx index 28dfac2e..6d769b9e 100644 --- a/frontend/src/features/audits/request-audits-page.tsx +++ b/frontend/src/features/audits/request-audits-page.tsx @@ -407,7 +407,7 @@ function EgressValue({ audit }: { audit: AuditDTO }) { function BillingValue({ audit }: { audit: AuditDTO }) { const { t, i18n } = useTranslation(); const billing = audit.billing ?? fallbackBillingBreakdown(audit); - const amount = billing ? formatUSDCost(billing.totalInUsdTicks, 2) : "-"; + const amount = billing ? formatUSDCost(billing.totalInUsdTicks, 2) : t("audits.unbilled"); return ( {billing ? ( @@ -417,7 +417,7 @@ function BillingValue({ audit }: { audit: AuditDTO }) { - ) : -} + ) : {amount}} {audit.numServerSideToolsUsed > 0 ? ( {t("audits.serverTools", { count: audit.numServerSideToolsUsed })} @@ -584,6 +584,16 @@ function UsageDetails({ audit, locale }: { audit: AuditDTO; locale: string }) { if (audit.operation === "video") { return ; } + if (audit.operation === "tts" || audit.operation === "stt" || audit.operation === "realtime" || audit.operation === "voice") { + return ( + + + {t(`audits.operations.${audit.operation}`)} + {(audit.durationMs / 1000).toFixed(2)}s + + + ); + } if (audit.operation === "image" || audit.operation === "image_edit" || audit.mediaInputImages > 0 || audit.mediaOutputImages > 0) { return ; } diff --git a/frontend/src/features/creative-console/creative-console-api.ts b/frontend/src/features/creative-console/creative-console-api.ts index 06796dfc..b19e5235 100644 --- a/frontend/src/features/creative-console/creative-console-api.ts +++ b/frontend/src/features/creative-console/creative-console-api.ts @@ -87,6 +87,7 @@ export async function generateImage(input: { count: number; aspectRatio: string; resolution: string; + quality?: "low" | "medium"; signal?: AbortSignal; }): Promise { const payload = await publicApiRequest( @@ -100,6 +101,7 @@ export async function generateImage(input: { n: input.count, aspect_ratio: input.aspectRatio, resolution: input.resolution, + ...(input.quality ? { quality: input.quality } : {}), response_format: "url", stream: false, }, @@ -117,6 +119,8 @@ export async function createVideo(input: { prompt: string; imageURL?: string; imageFileID?: string; + referenceImages?: Array<{ url?: string; fileId?: string }>; + referenceVoiceIds?: string[]; duration: number; aspectRatio: string; resolution: string; @@ -131,6 +135,15 @@ export async function createVideo(input: { }; if (input.imageFileID) body.image = { file_id: input.imageFileID }; else if (input.imageURL) body.image = { url: input.imageURL }; + if (input.referenceImages && input.referenceImages.length > 0) { + body.reference_images = input.referenceImages.map((item) => { + if (item.fileId) return { file_id: item.fileId }; + return { url: item.url }; + }); + } + if (input.referenceVoiceIds && input.referenceVoiceIds.length > 0) { + body.reference_audios = input.referenceVoiceIds.map((voiceId) => ({ voice_id: voiceId })); + } const payload = await publicApiRequest( input.apiKey, "/videos/generations", @@ -143,6 +156,61 @@ export async function createVideo(input: { return requestId; } +export async function editVideo(input: { + apiKey: string; + model: string; + prompt: string; + videoURL?: string; + videoFileID?: string; + signal?: AbortSignal; +}): Promise { + const payload = await publicApiRequest( + input.apiKey, + "/videos/edits", + { + method: "POST", + body: { + model: input.model, + prompt: input.prompt, + video: input.videoFileID ? { file_id: input.videoFileID } : { url: input.videoURL }, + }, + signal: input.signal, + }, + ); + const requestId = readVideoRequestID(payload); + if (!requestId) { + throw new CreativeApiError(200, "The video response did not contain a request ID", "invalid_response"); + } + return requestId; +} + +export async function extendVideo(input: { + apiKey: string; + model: string; + prompt: string; + videoURL?: string; + videoFileID?: string; + duration?: number; + signal?: AbortSignal; +}): Promise { + const body: Record = { + model: input.model, + prompt: input.prompt, + video: input.videoFileID ? { file_id: input.videoFileID } : { url: input.videoURL }, + }; + if (typeof input.duration === "number") body.duration = input.duration; + const payload = await publicApiRequest( + input.apiKey, + "/videos/extensions", + { method: "POST", body, signal: input.signal }, + ); + const requestId = readVideoRequestID(payload); + if (!requestId) { + throw new CreativeApiError(200, "The video response did not contain a request ID", "invalid_response"); + } + return requestId; +} + export async function getVideo(input: { apiKey: string; requestId: string; @@ -157,6 +225,145 @@ export async function getVideo(input: { return status.video ? { ...status, video: { ...status.video, url: resolveMediaURL(status.video.url) } } : status; } + +export type VoiceInfo = { + voiceId: string; + name: string; + language?: string; +}; + +export type TTSResult = { + url: string; + contentType: string; + duration?: number; +}; + +export type STTResult = { + text: string; + language?: string; + duration?: number; + words?: Array<{ text: string; start: number; end: number; speaker?: number }>; +}; + +export async function listVoices(input: { + apiKey: string; + model?: string; + signal?: AbortSignal; +}): Promise { + const query = input.model ? `?model=${encodeURIComponent(input.model)}` : ""; + const payload = await publicApiRequest(input.apiKey, `/tts/voices${query}`, { method: "GET", signal: input.signal }); + if (!isRecord(payload) || !Array.isArray(payload.voices)) { + throw new CreativeApiError(200, "The voice list response was invalid", "invalid_response"); + } + return payload.voices.map((item) => { + if (!isRecord(item) || typeof item.voice_id !== "string") { + throw new CreativeApiError(200, "The voice list response was invalid", "invalid_response"); + } + return { + voiceId: item.voice_id, + name: typeof item.name === "string" ? item.name : item.voice_id, + language: typeof item.language === "string" ? item.language : undefined, + }; + }); +} + +export async function synthesizeSpeech(input: { + apiKey: string; + model: string; + text: string; + voiceId: string; + language: string; + speed?: number; + signal?: AbortSignal; +}): Promise { + const response = await fetch("/v1/tts", { + method: "POST", + headers: new Headers({ + Accept: "application/json, audio/*", + Authorization: `Bearer ${input.apiKey}`, + "Content-Type": "application/json", + }), + body: JSON.stringify({ + model: input.model, + text: input.text, + voice_id: input.voiceId, + language: input.language, + ...(typeof input.speed === "number" ? { speed: input.speed } : {}), + }), + signal: input.signal, + }); + const contentType = response.headers.get("content-type") || ""; + if (!response.ok) { + const responseText = await response.text(); + const payload = parseJSON(responseText); + const error = readError(payload); + throw new CreativeApiError(response.status, error.message ?? (responseText.trim() || response.statusText || `HTTP ${response.status}`), error.code); + } + if (contentType.includes("application/json")) { + const payload = await response.json(); + if (!isRecord(payload) || typeof payload.audio !== "string") { + throw new CreativeApiError(200, "The TTS response was invalid", "invalid_response"); + } + const mime = typeof payload.content_type === "string" ? payload.content_type : "audio/mpeg"; + const url = `data:${mime};base64,${payload.audio}`; + return { + url, + contentType: mime, + duration: typeof payload.duration === "number" ? payload.duration : undefined, + }; + } + const buffer = await response.arrayBuffer(); + const mime = contentType || "audio/mpeg"; + const blob = new Blob([buffer], { type: mime }); + return { url: URL.createObjectURL(blob), contentType: mime }; +} + +export async function transcribeSpeech(input: { + apiKey: string; + model: string; + file: File; + language?: string; + signal?: AbortSignal; +}): Promise { + const form = new FormData(); + form.append("model", input.model); + if (input.language) form.append("language", input.language); + form.append("format", "true"); + form.append("file", input.file, input.file.name); + const response = await fetch("/v1/stt", { + method: "POST", + headers: new Headers({ Accept: "application/json", Authorization: `Bearer ${input.apiKey}` }), + body: form, + signal: input.signal, + }); + const responseText = await response.text(); + const payload = parseJSON(responseText); + if (!response.ok) { + const error = readError(payload); + throw new CreativeApiError(response.status, error.message ?? (responseText.trim() || response.statusText || `HTTP ${response.status}`), error.code); + } + if (!isRecord(payload) || typeof payload.text !== "string") { + throw new CreativeApiError(200, "The STT response was invalid", "invalid_response"); + } + const words = Array.isArray(payload.words) + ? payload.words.flatMap((item) => { + if (!isRecord(item) || typeof item.text !== "string") return []; + return [{ + text: item.text, + start: typeof item.start === "number" ? item.start : 0, + end: typeof item.end === "number" ? item.end : 0, + speaker: typeof item.speaker === "number" ? item.speaker : undefined, + }]; + }) + : undefined; + return { + text: payload.text, + language: typeof payload.language === "string" ? payload.language : undefined, + duration: typeof payload.duration === "number" ? payload.duration : undefined, + words, + }; +} + async function publicApiRequest(apiKey: string, path: string, options: RequestOptions): Promise { const headers = new Headers({ Accept: "application/json", Authorization: `Bearer ${apiKey}` }); let body: string | undefined; diff --git a/frontend/src/features/creative-console/creative-console-page.tsx b/frontend/src/features/creative-console/creative-console-page.tsx index 51afa3ff..3605c81e 100644 --- a/frontend/src/features/creative-console/creative-console-page.tsx +++ b/frontend/src/features/creative-console/creative-console-page.tsx @@ -1,5 +1,5 @@ import { useMutation, useQuery } from "@tanstack/react-query"; -import { ArrowUp, BrainCircuit, Check, CheckCircle2, Clock3, ExternalLink, Globe, History, ImageIcon, ImagePlus, ImageUpscale, Images, Loader2, MessageSquareText, Pencil, RefreshCw, Sparkle, Square, SquarePen, Trash2, TriangleAlert, TvMinimal, Upload, Video, Wrench, X } from "lucide-react"; +import { ArrowUp, AudioLines, BrainCircuit, Check, CheckCircle2, Clock3, ExternalLink, Globe, History, ImageIcon, ImagePlus, ImageUpscale, Images, Loader2, MessageSquareText, Mic, Pencil, RefreshCw, Sparkle, Square, SquarePen, Trash2, TriangleAlert, TvMinimal, Upload, Video, Wrench, X } from "lucide-react"; import { marked } from "marked"; import { useEffect, useMemo, useRef, useState, type FormEvent, type KeyboardEvent, type ReactNode } from "react"; import { createPortal } from "react-dom"; @@ -22,21 +22,29 @@ import type { ModelRouteDTO } from "@/entities/model/types"; import { createChatResponse, createVideo, + editVideo, + extendVideo, generateImage, getVideo, + listVoices, + synthesizeSpeech, + transcribeSpeech, type ChatMessage, type ChatStreamSnapshot, type ChatToolActivity, type ImageResult, type ReasoningEffort, + type STTResult, + type TTSResult, type VideoStatus, + type VoiceInfo, } from "@/features/creative-console/creative-console-api"; import { getClientKeySecret, listClientKeys, type ClientKeyDTO } from "@/features/client-keys/client-keys-api"; -import { importVideoInputFromURL, uploadVideoInput } from "@/features/media/media-api"; +import { importVideoInputFromURL, uploadMediaInput } from "@/features/media/media-api"; import { PageHeader } from "@/shared/components/page-header"; import { cn } from "@/shared/lib/cn"; -type CreativeMode = "chat" | "image" | "video"; +type CreativeMode = "chat" | "image" | "video" | "voice"; type ConversationMessage = ChatMessage & { id: string; reasoning?: string; @@ -83,6 +91,8 @@ const videoAspectRatios = ["1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3"] as const imageResolutions = ["1k", "2k"] as const; const videoResolutions = ["480p", "720p", "1080p"] as const; const videoDurations = ["6", "10", "15"] as const; +const videoExtendDurations = ["2", "4", "6", "8", "10"] as const; +type VideoAction = "generate" | "edit" | "extend"; const chatHistoryStoragePrefix = "grok2api:creative-console:chat-history:"; const chatHistoryMaxSessions = 50; const chatHistoryMaxBytes = 4 * 1024 * 1024; @@ -94,7 +104,7 @@ export function CreativeConsolePage() { const [selectedKeyId, setSelectedKeyId] = useState(""); const [secretState, setSecretState] = useState(null); const [keyError, setKeyError] = useState(""); - const [selectedModels, setSelectedModels] = useState>({ chat: "", image: "", video: "" }); + const [selectedModels, setSelectedModels] = useState>({ chat: "", image: "", video: "", voice: "" }); const [chatToolbarElement, setChatToolbarElement] = useState(null); const requestedSecretKeyRef = useRef(""); @@ -123,13 +133,20 @@ export function CreativeConsolePage() { const modelGroups = useMemo(() => ({ chat: uniqueModelsByPublicID(permittedModels.filter((model) => model.capability === "chat" || model.capability === "responses")), image: uniqueModelsByPublicID(permittedModels.filter((model) => model.capability === "image")), - video: uniqueModelsByPublicID(permittedModels.filter((model) => model.capability === "video")), + // Keep every route target for VideoPanel. It presents one row per public ID, + // but edit/extend eligibility depends on whether any aggregated target is + // Console/grok-imagine-video, not on the public name chosen by the operator. + video: permittedModels.filter((model) => model.capability === "video"), + // Keep capability-specific routes for VoicePanel so TTS/STT can filter correctly. + voice: permittedModels.filter((model) => model.capability === "tts" || model.capability === "stt" || model.capability === "realtime"), }), [permittedModels]); + const voiceModelChoices = useMemo(() => uniqueModelsByPublicID(modelGroups.voice), [modelGroups.voice]); const effectiveModels = useMemo>(() => ({ chat: modelGroups.chat.some((model) => model.publicId === selectedModels.chat) ? selectedModels.chat : modelGroups.chat[0]?.publicId ?? "", image: modelGroups.image.some((model) => model.publicId === selectedModels.image) ? selectedModels.image : modelGroups.image[0]?.publicId ?? "", video: modelGroups.video.some((model) => model.publicId === selectedModels.video) ? selectedModels.video : modelGroups.video[0]?.publicId ?? "", - }), [modelGroups, selectedModels]); + voice: voiceModelChoices.some((model) => model.publicId === selectedModels.voice) ? selectedModels.voice : voiceModelChoices[0]?.publicId ?? "", + }), [modelGroups, selectedModels, voiceModelChoices]); const secretMutation = useMutation({ mutationFn: (id: string) => getClientKeySecret(id), @@ -193,6 +210,7 @@ export function CreativeConsolePage() { {t("creativeConsole.modes.chat")} {t("creativeConsole.modes.image")} {t("creativeConsole.modes.video")} + {t("creativeConsole.modes.voice")} @@ -220,6 +238,7 @@ export function CreativeConsolePage() { + @@ -853,7 +872,9 @@ function ImagePanel({ apiKey, model, modelOptions, onModelChange }: CreativePane const [count, setCount] = useState("1"); const [aspectRatio, setAspectRatio] = useState("1:1"); const [resolution, setResolution] = useState("1k"); + const [quality, setQuality] = useState<"low" | "medium">("medium"); const [images, setImages] = useState([]); + const supportsQuality = model.toLowerCase().endsWith("grok-imagine-image-2.0"); const mutation = useMutation({ mutationFn: (request: Parameters[0]) => generateImage(request), @@ -864,7 +885,7 @@ function ImagePanel({ apiKey, model, modelOptions, onModelChange }: CreativePane event.preventDefault(); if (!apiKey || !model || !prompt.trim() || mutation.isPending) return; mutation.reset(); - mutation.mutate({ apiKey, model, prompt: prompt.trim(), count: Number(count), aspectRatio, resolution }); + mutation.mutate({ apiKey, model, prompt: prompt.trim(), count: Number(count), aspectRatio, resolution, quality: supportsQuality ? quality : undefined }); } return ( @@ -898,6 +919,7 @@ function ImagePanel({ apiKey, model, modelOptions, onModelChange }: CreativePane } /> } /> } /> + {supportsQuality ? setQuality(value as "low" | "medium")} ariaLabel={t("creativeConsole.quality")} /> : null} {mutation.isPending ? : } @@ -910,34 +932,153 @@ function ImagePanel({ apiKey, model, modelOptions, onModelChange }: CreativePane function VideoPanel({ apiKey, model, modelOptions, onModelChange }: CreativePanelProps) { const { t } = useTranslation(); + const [action, setAction] = useState("generate"); const [prompt, setPrompt] = useState(""); const [imageURL, setImageURL] = useState(""); const [imageFileID, setImageFileID] = useState(""); + const [referenceURL, setReferenceURL] = useState(""); + const [referenceFileID, setReferenceFileID] = useState(""); + const [referenceVoiceId, setReferenceVoiceId] = useState(""); + const [sourceVideoURL, setSourceVideoURL] = useState(""); + const [sourceVideoFileID, setSourceVideoFileID] = useState(""); const [duration, setDuration] = useState("6"); + const [extendDuration, setExtendDuration] = useState("6"); const [aspectRatio, setAspectRatio] = useState("16:9"); const [resolution, setResolution] = useState("720p"); const [job, setJob] = useState<{ requestId: string; apiKey: string } | null>(null); const imageFileInputRef = useRef(null); + const referenceFileInputRef = useRef(null); + const videoFileInputRef = useRef(null); const imageSelectionVersionRef = useRef(0); + const referenceSelectionVersionRef = useRef(0); + const videoSelectionVersionRef = useRef(0); + + const generateModels = useMemo(() => uniqueModelsByPublicID(modelOptions.filter((item) => item.capability === "video")), [modelOptions]); + const editModels = useMemo(() => { + const eligiblePublicIDs = new Set(modelOptions + .filter((item) => item.capability === "video" && item.provider === "grok_console" && item.upstreamModel === "grok-imagine-video") + .map((item) => item.publicId)); + return generateModels.filter((item) => eligiblePublicIDs.has(item.publicId)); + }, [generateModels, modelOptions]); + const activeModels = action === "generate" ? generateModels : editModels; + const activeModel = activeModels.some((item) => item.publicId === model) + ? model + : activeModels[0]?.publicId ?? ""; + + useEffect(() => { + if (activeModel && activeModel !== model) onModelChange(activeModel); + }, [activeModel, model, onModelChange]); + + const voicesQuery = useQuery({ + queryKey: ["creative-console", "video-voices", apiKey], + queryFn: ({ signal }) => listVoices({ apiKey, model: "grok-voice-latest", signal }), + enabled: Boolean(apiKey && action === "generate"), + staleTime: 60_000, + }); + const voices = useMemo(() => voicesQuery.data ?? [], [voicesQuery.data]); + const hasFirstFrame = Boolean(imageURL.trim() || imageFileID); + const hasReferenceImage = Boolean(referenceURL.trim() || referenceFileID); + const hasReferenceAudio = Boolean(referenceVoiceId.trim()); + const isReferenceMode = hasReferenceImage || hasReferenceAudio; + const generateResolutions = isReferenceMode ? videoResolutions.filter((item) => item !== "1080p") : videoResolutions; + const selectedVideoResolution = isReferenceMode && resolution === "1080p" ? "720p" : resolution; const createMutation = useMutation({ - mutationFn: async (request: Parameters[0]) => { - if (!request.imageFileID && request.imageURL && /^https?:\/\//i.test(request.imageURL)) { - const staged = await importVideoInputFromURL(request.imageURL); - return createVideo({ ...request, imageURL: undefined, imageFileID: staged.fileId }); + mutationFn: async () => { + if (!apiKey || !activeModel) throw new Error(t("creativeConsole.errors.noModels")); + if (action === "generate") { + let nextImageURL = imageURL.trim() || undefined; + let nextImageFileID = imageFileID || undefined; + let nextReferenceURL = referenceURL.trim() || undefined; + let nextReferenceFileID = referenceFileID || undefined; + let nextReferenceVoice = referenceVoiceId.trim() || undefined; + if (nextImageFileID || nextImageURL) { + nextReferenceURL = undefined; + nextReferenceFileID = undefined; + nextReferenceVoice = undefined; + } + if (!nextImageFileID && nextImageURL && /^https?:\/\//i.test(nextImageURL)) { + const staged = await importVideoInputFromURL(nextImageURL); + nextImageURL = undefined; + nextImageFileID = staged.fileId; + } + if (!nextReferenceFileID && nextReferenceURL && /^https?:\/\//i.test(nextReferenceURL)) { + const staged = await importVideoInputFromURL(nextReferenceURL); + nextReferenceURL = undefined; + nextReferenceFileID = staged.fileId; + } + return createVideo({ + apiKey, + model: activeModel, + prompt: prompt.trim(), + imageURL: nextImageURL, + imageFileID: nextImageFileID, + referenceImages: nextReferenceFileID + ? [{ fileId: nextReferenceFileID }] + : nextReferenceURL + ? [{ url: nextReferenceURL }] + : undefined, + referenceVoiceIds: nextReferenceVoice ? [nextReferenceVoice] : undefined, + duration: Number(duration), + aspectRatio, + resolution: selectedVideoResolution, + }); } - return createVideo(request); + const videoURL = sourceVideoURL.trim() || undefined; + const videoFileID = sourceVideoFileID || undefined; + if (!videoURL && !videoFileID) throw new Error(t("creativeConsole.errors.noSourceVideo")); + if (action === "edit") { + return editVideo({ apiKey, model: activeModel, prompt: prompt.trim(), videoURL, videoFileID }); + } + return extendVideo({ + apiKey, + model: activeModel, + prompt: prompt.trim(), + videoURL, + videoFileID, + duration: Number(extendDuration), + }); }, - onSuccess: (requestId, request) => setJob({ requestId, apiKey: request.apiKey }), + onSuccess: (requestId) => setJob({ requestId, apiKey }), }); - // 本地图片进入有 TTL 的隐藏临时区;视频任务只持久化短 file_id,不写入图库或公开 URL。 + // 本地媒体进入有 TTL 的隐藏临时区;视频任务只持久化短 file_id,不写入图库或公开 URL。 const uploadMutation = useMutation({ - mutationFn: ({ file }: { file: File; selectionVersion: number }) => uploadVideoInput(file), - onSuccess: (input, request) => { - if (request.selectionVersion !== imageSelectionVersionRef.current) return; - setImageFileID(input.fileId); + mutationFn: async ({ file, kind, selectionVersion }: { file: File; kind: "image" | "reference"; selectionVersion: number }) => { + if (file.type && !file.type.startsWith("image/")) throw new Error(t("creativeConsole.errors.invalidImage")); + const input = await uploadMediaInput(file); + if (input.kind !== "image") throw new Error(t("creativeConsole.errors.invalidImage")); + return { ...input, kind, selectionVersion }; + }, + onSuccess: (input) => { + if (input.kind === "image") { + if (input.selectionVersion !== imageSelectionVersionRef.current) return; + setImageFileID(input.fileId); + setImageURL(""); + setReferenceURL(""); + setReferenceFileID(""); + setReferenceVoiceId(""); + return; + } + if (input.selectionVersion !== referenceSelectionVersionRef.current) return; + setReferenceFileID(input.fileId); + setReferenceURL(""); setImageURL(""); + setImageFileID(""); + }, + }); + + const videoUploadMutation = useMutation({ + mutationFn: async ({ file }: { file: File; selectionVersion: number }) => { + if (file.type && !file.type.startsWith("video/")) throw new Error(t("creativeConsole.errors.invalidVideo")); + const input = await uploadMediaInput(file); + if (input.kind !== "video") throw new Error(t("creativeConsole.errors.invalidVideo")); + return input; + }, + onSuccess: (input, request) => { + if (request.selectionVersion !== videoSelectionVersionRef.current) return; + setSourceVideoFileID(input.fileId); + setSourceVideoURL(""); }, }); @@ -951,26 +1092,47 @@ function VideoPanel({ apiKey, model, modelOptions, onModelChange }: CreativePane function submit(event: FormEvent): void { event.preventDefault(); - if (!apiKey || !model || (!prompt.trim() && !imageURL.trim() && !imageFileID) || !validDuration(duration) || createMutation.isPending || uploadMutation.isPending) return; + if (!apiKey || !activeModel || createMutation.isPending || uploadMutation.isPending || videoUploadMutation.isPending) return; + if (action === "generate") { + if ((!prompt.trim() && !hasFirstFrame && !isReferenceMode) || !validDuration(duration)) return; + if (isReferenceMode && !prompt.trim()) return; + } else { + if (!prompt.trim() || (!sourceVideoURL.trim() && !sourceVideoFileID)) return; + if (action === "extend") { + const value = Number(extendDuration); + if (!Number.isFinite(value) || value < 2 || value > 10) return; + } + } setJob(null); createMutation.reset(); - createMutation.mutate({ - apiKey, - model, - prompt: prompt.trim(), - imageURL: imageURL.trim() || undefined, - imageFileID: imageFileID || undefined, - duration: Number(duration), - aspectRatio, - resolution, - }); + createMutation.mutate(); } + const placeholder = action === "generate" + ? t("creativeConsole.videoPlaceholder") + : action === "edit" + ? t("creativeConsole.videoEditPlaceholder") + : t("creativeConsole.videoExtendPlaceholder"); + const welcome = action === "generate" + ? t("creativeConsole.welcomeVideo") + : action === "edit" + ? t("creativeConsole.welcomeVideoEdit") + : t("creativeConsole.welcomeVideoExtend"); + const submitLabel = action === "generate" + ? t("creativeConsole.generateVideo") + : action === "edit" + ? t("creativeConsole.editVideo") + : t("creativeConsole.extendVideo"); + const canSubmit = Boolean(apiKey && activeModel && !createMutation.isPending && !uploadMutation.isPending && !videoUploadMutation.isPending + && (action === "generate" + ? ((prompt.trim() || hasFirstFrame || isReferenceMode) && (!isReferenceMode || prompt.trim()) && validDuration(duration) && !(hasFirstFrame && isReferenceMode)) + : prompt.trim() && (sourceVideoURL.trim() || sourceVideoFileID) && (action !== "extend" || (Number(extendDuration) >= 2 && Number(extendDuration) <= 10)))); + return ( - {!job && !createMutation.isPending ? : null} + {!job && !createMutation.isPending ? : null} {createMutation.isPending ? : null} {job ? ( - setPrompt(event.target.value)} placeholder={t("creativeConsole.videoPlaceholder")} className="min-h-24 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0" /> + + {([ + ["generate", t("creativeConsole.videoActions.generate")], + ["edit", t("creativeConsole.videoActions.edit")], + ["extend", t("creativeConsole.videoActions.extend")], + ] as const).map(([value, label]) => ( + { + setAction(value); + setJob(null); + createMutation.reset(); + }} + > + {label} + + ))} + + setPrompt(event.target.value)} placeholder={placeholder} className="min-h-24 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0" /> - - - - - {imageURL || imageFileID ? t("creativeConsole.referenceImageAdded") : t("creativeConsole.referenceImageShort")} - - - - {t("creativeConsole.referenceImage")} - - { imageSelectionVersionRef.current += 1; setImageURL(event.target.value); setImageFileID(""); }} placeholder={imageFileID ? t("creativeConsole.referenceImageAdded") : "https://..."} aria-label={t("creativeConsole.referenceImage")} /> - {imageURL || imageFileID ? { imageSelectionVersionRef.current += 1; setImageURL(""); setImageFileID(""); }}> : null} - - { - const file = event.target.files?.[0]; - if (file) { - const selectionVersion = imageSelectionVersionRef.current + 1; - imageSelectionVersionRef.current = selectionVersion; - setImageURL(""); - setImageFileID(""); - uploadMutation.reset(); - uploadMutation.mutate({ file, selectionVersion }); - } - event.target.value = ""; - }} - /> - imageFileInputRef.current?.click()}> - {uploadMutation.isPending ? : } - {t("creativeConsole.uploadImage")} - - {uploadMutation.isError ? {uploadMutation.error.message} : null} - - - } /> - } /> - } /> + + {action === "generate" ? ( + <> + + + + {hasFirstFrame ? t("creativeConsole.firstFrameImageAdded") : t("creativeConsole.firstFrameImageShort")} + + + + {t("creativeConsole.firstFrameImage")} + + { imageSelectionVersionRef.current += 1; referenceSelectionVersionRef.current += 1; setImageURL(event.target.value); setImageFileID(""); setReferenceURL(""); setReferenceFileID(""); setReferenceVoiceId(""); }} placeholder={imageFileID ? t("creativeConsole.firstFrameImageAdded") : "https://..."} aria-label={t("creativeConsole.firstFrameImage")} /> + {hasFirstFrame ? { imageSelectionVersionRef.current += 1; setImageURL(""); setImageFileID(""); }}> : null} + + { + const file = event.target.files?.[0]; + if (file) { + const selectionVersion = imageSelectionVersionRef.current + 1; + imageSelectionVersionRef.current = selectionVersion; + referenceSelectionVersionRef.current += 1; + setImageURL(""); + setImageFileID(""); + setReferenceURL(""); + setReferenceFileID(""); + setReferenceVoiceId(""); + uploadMutation.reset(); + uploadMutation.mutate({ file, kind: "image", selectionVersion }); + } + event.target.value = ""; + }} + /> + imageFileInputRef.current?.click()}> + {uploadMutation.isPending ? : } + {t("creativeConsole.uploadImage")} + + {uploadMutation.isError ? {uploadMutation.error.message} : null} + + + + + + {hasReferenceImage ? t("creativeConsole.referenceImageAdded") : t("creativeConsole.referenceImageShort")} + + + + {t("creativeConsole.referenceImage")} + + { referenceSelectionVersionRef.current += 1; imageSelectionVersionRef.current += 1; setReferenceURL(event.target.value); setReferenceFileID(""); setImageURL(""); setImageFileID(""); }} placeholder={referenceFileID ? t("creativeConsole.referenceImageAdded") : "https://..."} aria-label={t("creativeConsole.referenceImage")} /> + {hasReferenceImage ? { referenceSelectionVersionRef.current += 1; setReferenceURL(""); setReferenceFileID(""); }}> : null} + + { + const file = event.target.files?.[0]; + if (file) { + const selectionVersion = referenceSelectionVersionRef.current + 1; + referenceSelectionVersionRef.current = selectionVersion; + imageSelectionVersionRef.current += 1; + setReferenceURL(""); + setReferenceFileID(""); + setImageURL(""); + setImageFileID(""); + uploadMutation.reset(); + uploadMutation.mutate({ file, kind: "reference", selectionVersion }); + } + event.target.value = ""; + }} + /> + referenceFileInputRef.current?.click()}> + {uploadMutation.isPending ? : } + {t("creativeConsole.uploadImage")} + + {uploadMutation.isError ? {uploadMutation.error.message} : null} + + + { setReferenceVoiceId(value === "__none__" ? "" : value); if (value !== "__none__") { imageSelectionVersionRef.current += 1; setImageURL(""); setImageFileID(""); } }} disabled={hasFirstFrame}> + + + + + + {t("creativeConsole.referenceVoiceNone")} + {(voices.length > 0 ? voices : [{ voiceId: "eve", name: "Eve" }, { voiceId: "ara", name: "Ara" }] as VoiceInfo[]).map((voice) => ( + {voice.name || voice.voiceId} + ))} + + + > + ) : ( + + + + {sourceVideoURL || sourceVideoFileID ? t("creativeConsole.sourceVideoAdded") : t("creativeConsole.sourceVideoShort")} + + + + {t("creativeConsole.sourceVideo")} + + { videoSelectionVersionRef.current += 1; setSourceVideoURL(event.target.value); setSourceVideoFileID(""); }} placeholder={sourceVideoFileID ? t("creativeConsole.sourceVideoAdded") : "https://..."} aria-label={t("creativeConsole.sourceVideo")} /> + {sourceVideoURL || sourceVideoFileID ? { videoSelectionVersionRef.current += 1; setSourceVideoURL(""); setSourceVideoFileID(""); }}> : null} + + { + const file = event.target.files?.[0]; + if (file) { + const selectionVersion = videoSelectionVersionRef.current + 1; + videoSelectionVersionRef.current = selectionVersion; + setSourceVideoURL(""); + setSourceVideoFileID(""); + videoUploadMutation.reset(); + videoUploadMutation.mutate({ file, selectionVersion }); + } + event.target.value = ""; + }} + /> + videoFileInputRef.current?.click()}> + {videoUploadMutation.isPending ? : } + {t("creativeConsole.uploadVideo")} + + {videoUploadMutation.isError ? {videoUploadMutation.error.message} : null} + + + )} + {action === "generate" ? ( + <> + } /> + } /> + } /> + > + ) : null} + {action === "extend" ? ( + } /> + ) : null} - + {createMutation.isPending ? : } @@ -1071,6 +1360,150 @@ function VideoResult({ requestId, status, loading, error, onRetry }: { requestId ); } + +function VoicePanel({ apiKey, model, modelOptions, onModelChange }: CreativePanelProps) { + const { t } = useTranslation(); + const [subMode, setSubMode] = useState<"tts" | "stt">("tts"); + const [prompt, setPrompt] = useState(""); + const [language, setLanguage] = useState("zh"); + const [voiceId, setVoiceId] = useState("eve"); + const [speed, setSpeed] = useState("1.0"); + const [audioFile, setAudioFile] = useState(null); + const [ttsResult, setTtsResult] = useState(null); + const [sttResult, setSttResult] = useState(null); + const fileInputRef = useRef(null); + + const filteredModels = useMemo(() => { + const matched = modelOptions.filter((item) => ( + subMode === "tts" + ? item.capability === "tts" || item.capability === "realtime" + : item.capability === "stt" + )); + return uniqueModelsByPublicID(matched); + }, [modelOptions, subMode]); + const activeModel = filteredModels.some((item) => item.publicId === model) + ? model + : filteredModels[0]?.publicId ?? ""; + + useEffect(() => { + if (activeModel !== model) onModelChange(activeModel); + }, [activeModel, model, onModelChange]); + + const voicesQuery = useQuery({ + queryKey: ["creative-console", "voices", apiKey, activeModel], + queryFn: ({ signal }) => listVoices({ apiKey, model: activeModel || "grok-voice-latest", signal }), + enabled: Boolean(apiKey) && subMode === "tts", + staleTime: 60_000, + }); + const voices = useMemo(() => voicesQuery.data ?? [], [voicesQuery.data]); + const activeVoiceId = voices.some((voice) => voice.voiceId === voiceId) + ? voiceId + : voices[0]?.voiceId ?? voiceId; + + const ttsMutation = useMutation({ + mutationFn: () => synthesizeSpeech({ apiKey, model: activeModel || "grok-voice-latest", text: prompt.trim(), voiceId: activeVoiceId, language, speed: Number(speed) }), + onSuccess: (result) => { + setTtsResult(result); + setSttResult(null); + }, + }); + const sttMutation = useMutation({ + mutationFn: async () => { + if (!audioFile) throw new Error(t("creativeConsole.errors.noAudio")); + return transcribeSpeech({ apiKey, model: activeModel || "grok-stt", file: audioFile, language }); + }, + onSuccess: (result) => { + setSttResult(result); + setTtsResult(null); + }, + }); + + function submit(event: FormEvent) { + event.preventDefault(); + if (!apiKey || !activeModel) return; + if (subMode === "tts") { + if (!prompt.trim() || ttsMutation.isPending) return; + ttsMutation.reset(); + ttsMutation.mutate(); + return; + } + if (!audioFile || sttMutation.isPending) return; + sttMutation.reset(); + sttMutation.mutate(); + } + + const busy = ttsMutation.isPending || sttMutation.isPending; + const languageOptions = ["auto", "zh", "en", "ja", "ko", "fr", "de", "es"] as const; + const speedOptions = ["0.7", "0.8", "0.9", "1.0", "1.1", "1.2", "1.3", "1.4", "1.5"] as const; + + return ( + + + {!ttsResult && !sttResult && !busy ? : null} + {busy ? : null} + {ttsResult ? ( + + + + {ttsResult.contentType}{typeof ttsResult.duration === "number" ? ` · ${ttsResult.duration.toFixed(2)}s` : ""} + {t("creativeConsole.open")} + + + ) : null} + {sttResult ? ( + + {sttResult.text} + + {[sttResult.language, typeof sttResult.duration === "number" ? `${sttResult.duration.toFixed(2)}s` : ""].filter(Boolean).join(" · ")} + + + ) : null} + {ttsMutation.isError ? {ttsMutation.error.message} : null} + {sttMutation.isError ? {sttMutation.error.message} : null} + + + + setSubMode("tts")}>{t("creativeConsole.synthesize")} + setSubMode("stt")}>{t("creativeConsole.transcribe")} + + {subMode === "tts" ? ( + setPrompt(event.target.value)} placeholder={t("creativeConsole.voicePlaceholder")} className="min-h-24 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0" /> + ) : ( + + setAudioFile(event.target.files?.[0] ?? null)} /> + fileInputRef.current?.click()}>{audioFile ? audioFile.name : t("creativeConsole.uploadAudio")} + {audioFile ? setAudioFile(null)}> : null} + + )} + + + + + {subMode === "tts" ? ( + } /> + ) : null} + {subMode === "tts" ? ( + + + + + + {(voices.length > 0 ? voices : [{ voiceId: "eve", name: "eve" } as VoiceInfo]).map((voice) => ( + {voice.name || voice.voiceId} + ))} + + + ) : null} + + + {busy ? : } + + + + + ); +} + function WelcomeState({ title }: { title: string }) { return ( diff --git a/frontend/src/features/docs/api-docs-page.tsx b/frontend/src/features/docs/api-docs-page.tsx index c5096f6d..c3677ca6 100644 --- a/frontend/src/features/docs/api-docs-page.tsx +++ b/frontend/src/features/docs/api-docs-page.tsx @@ -97,6 +97,7 @@ const endpoints: Record = { { name: "n", descriptionKey: "docs.reference.fieldImageCount" }, { name: "aspect_ratio", descriptionKey: "docs.reference.fieldAspectRatio" }, { name: "resolution", descriptionKey: "docs.reference.fieldResolution" }, + { name: "quality", descriptionKey: "docs.reference.fieldQuality" }, { name: "response_format", descriptionKey: "docs.reference.fieldResponseFormat" }, { name: "stream", descriptionKey: "docs.reference.fieldImageStream" }, ], @@ -112,6 +113,7 @@ const endpoints: Record = { { name: "prompt", required: true, descriptionKey: "docs.reference.fieldPrompt" }, { name: "image / images", required: true, descriptionKey: "docs.reference.fieldEditImages" }, { name: "n", descriptionKey: "docs.reference.fieldImageCount" }, + { name: "quality", descriptionKey: "docs.reference.fieldQuality" }, { name: "response_format", descriptionKey: "docs.reference.fieldResponseFormat" }, ], noteKeys: ["docs.reference.noteEditJSON", "docs.reference.noteEditSources", "docs.reference.noteImageStorage"], @@ -129,11 +131,37 @@ const endpoints: Record = { { name: "resolution", descriptionKey: "docs.reference.fieldResolution" }, { name: "image", descriptionKey: "docs.reference.fieldVideoImage" }, { name: "reference_images", descriptionKey: "docs.reference.fieldReferenceImages" }, + { name: "reference_audios", descriptionKey: "docs.reference.fieldReferenceAudios" }, ], - noteKeys: ["docs.reference.noteVideoAsync", "docs.reference.noteVideoStrict"], + noteKeys: ["docs.reference.noteVideoAsync", "docs.reference.noteVideoReference", "docs.reference.noteVideoStrict"], request: (model) => ({ model, prompt: "A paper airplane flying over a city", duration: 8, aspect_ratio: "16:9", resolution: "720p" }), response: { request_id: "video_example" }, }, + "video/edits": { + key: "video/edits", category: "Video", title: "Video edits", method: "POST", path: "/videos/edits", + descriptionKey: "docs.endpointVideoEdit", capabilities: ["video"], + fields: [ + { name: "model", required: true, descriptionKey: "docs.reference.fieldModel" }, + { name: "prompt", required: true, descriptionKey: "docs.reference.fieldVideoEditPrompt" }, + { name: "video", required: true, descriptionKey: "docs.reference.fieldVideoInput" }, + ], + noteKeys: ["docs.reference.noteVideoAsync", "docs.reference.noteVideoEditModel", "docs.reference.noteVideoBilling", "docs.reference.noteVideoStrict"], + request: () => ({ model: "grok-imagine-video", prompt: "Give the woman a silver necklace", video: { url: "https://example.com/source.mp4" } }), + response: { request_id: "video_edit_example" }, + }, + "video/extensions": { + key: "video/extensions", category: "Video", title: "Video extensions", method: "POST", path: "/videos/extensions", + descriptionKey: "docs.endpointVideoExtend", capabilities: ["video"], + fields: [ + { name: "model", required: true, descriptionKey: "docs.reference.fieldModel" }, + { name: "prompt", required: true, descriptionKey: "docs.reference.fieldVideoExtendPrompt" }, + { name: "video", required: true, descriptionKey: "docs.reference.fieldVideoInput" }, + { name: "duration", descriptionKey: "docs.reference.fieldVideoExtendDuration" }, + ], + noteKeys: ["docs.reference.noteVideoAsync", "docs.reference.noteVideoEditModel", "docs.reference.noteVideoBilling", "docs.reference.noteVideoStrict"], + request: () => ({ model: "grok-imagine-video", prompt: "The shot pans to an over the shoulder perspective.", duration: 6, video: { url: "https://example.com/source.mp4" } }), + response: { request_id: "video_extend_example" }, + }, "video/get": { key: "video/get", category: "Video", title: "Get video", method: "GET", path: "/videos/{request_id}", descriptionKey: "docs.endpointVideoGet", capabilities: ["video"], @@ -142,6 +170,103 @@ const endpoints: Record = { request: () => undefined, response: { status: "done", model: "grok-imagine-video", progress: 100, video: { url: "https://example.com/generated.mp4", duration: 8, respect_moderation: true } }, }, + "voice/tts": { + key: "voice/tts", category: "Voice", title: "Text to speech", method: "POST", path: "/tts", + descriptionKey: "docs.endpointTTS", capabilities: ["tts"], + fields: [ + { name: "model", descriptionKey: "docs.reference.fieldVoiceModel" }, + { name: "text", required: true, descriptionKey: "docs.reference.fieldTTSText" }, + { name: "voice_id", descriptionKey: "docs.reference.fieldVoiceId" }, + { name: "language", required: true, descriptionKey: "docs.reference.fieldVoiceLanguage" }, + { name: "output_format", descriptionKey: "docs.reference.fieldTTSOutputFormat" }, + { name: "speed", descriptionKey: "docs.reference.fieldTTSSpeed" }, + { name: "with_timestamps", descriptionKey: "docs.reference.fieldTTSTimestamps" }, + ], + noteKeys: ["docs.reference.noteTTSModels", "docs.reference.noteTTSBinary", "docs.reference.noteVoiceBilling"], + request: (model) => ({ model, text: "Hello from Grok voice.", voice_id: "eve", language: "en", output_format: { codec: "mp3" } }), + response: { content_type: "audio/mpeg", note: "Default responses return raw audio bytes. with_timestamps=true returns a JSON envelope." }, + }, + "voice/audio-speech": { + key: "voice/audio-speech", category: "Voice", title: "OpenAI speech", method: "POST", path: "/audio/speech", + descriptionKey: "docs.endpointAudioSpeech", capabilities: ["tts"], + fields: [ + { name: "model", descriptionKey: "docs.reference.fieldVoiceModel" }, + { name: "input", required: true, descriptionKey: "docs.reference.fieldAudioInput" }, + { name: "voice", descriptionKey: "docs.reference.fieldAudioVoice" }, + { name: "response_format", descriptionKey: "docs.reference.fieldAudioResponseFormat" }, + { name: "speed", descriptionKey: "docs.reference.fieldTTSSpeed" }, + { name: "language", descriptionKey: "docs.reference.fieldVoiceLanguageOptional" }, + ], + noteKeys: ["docs.reference.noteAudioSpeechCompat", "docs.reference.noteTTSModels", "docs.reference.noteTTSBinary", "docs.reference.noteVoiceBilling"], + request: (model) => ({ model, input: "Hello from Grok voice.", voice: "alloy", response_format: "mp3", speed: 1.0, language: "en" }), + response: { content_type: "audio/mpeg", note: "Returns raw audio bytes compatible with OpenAI speech clients." }, + }, + "voice/audio-tasks": { + key: "voice/audio-tasks", category: "Voice", title: "OpenAI audio tasks", method: "POST", path: "/audio/tasks", + descriptionKey: "docs.endpointAudioTasks", capabilities: ["tts"], + fields: [ + { name: "model", descriptionKey: "docs.reference.fieldVoiceModel" }, + { name: "input", required: true, descriptionKey: "docs.reference.fieldAudioInput" }, + { name: "voice", descriptionKey: "docs.reference.fieldAudioVoice" }, + { name: "response_format", descriptionKey: "docs.reference.fieldAudioResponseFormat" }, + { name: "speed", descriptionKey: "docs.reference.fieldTTSSpeed" }, + { name: "language", descriptionKey: "docs.reference.fieldVoiceLanguageOptional" }, + ], + noteKeys: ["docs.reference.noteAudioTasksCompat", "docs.reference.noteTTSModels", "docs.reference.noteVoiceBilling"], + request: (model) => ({ model, input: "Hello from Grok voice.", voice: "alloy", response_format: "mp3", language: "en" }), + response: { content_type: "audio/mpeg", note: "Compatibility path that returns raw audio bytes by default." }, + }, + "voice/audio-transcriptions": { + key: "voice/audio-transcriptions", category: "Voice", title: "OpenAI transcriptions", method: "POST", path: "/audio/transcriptions", + descriptionKey: "docs.endpointAudioTranscriptions", capabilities: ["stt"], + fields: [ + { name: "model", descriptionKey: "docs.reference.fieldSTTModel" }, + { name: "file", descriptionKey: "docs.reference.fieldSTTFile" }, + { name: "url", descriptionKey: "docs.reference.fieldSTTUrl" }, + { name: "language", descriptionKey: "docs.reference.fieldVoiceLanguage" }, + { name: "response_format", descriptionKey: "docs.reference.fieldSTTResponseFormat" }, + ], + noteKeys: ["docs.reference.noteAudioTranscriptionsCompat", "docs.reference.noteSTTInput", "docs.reference.noteSTTModels", "docs.reference.noteVoiceBilling"], + request: (model) => ({ model, url: "https://example.com/sample.wav", language: "en" }), + response: { text: "Hello from Grok voice." }, + }, + "voice/voices": { + key: "voice/voices", category: "Voice", title: "List voices", method: "GET", path: "/tts/voices", + descriptionKey: "docs.endpointTTSVoices", capabilities: ["tts"], + fields: [ + { name: "model", descriptionKey: "docs.reference.fieldVoiceModelQuery" }, + ], + noteKeys: ["docs.reference.noteTTSVoices"], + request: () => undefined, + response: { voices: [{ voice_id: "eve", name: "Eve", language: "en" }, { voice_id: "ara", name: "Ara", language: "en" }] }, + }, + "voice/stt": { + key: "voice/stt", category: "Voice", title: "Speech to text", method: "POST", path: "/stt", + descriptionKey: "docs.endpointSTT", capabilities: ["stt"], + fields: [ + { name: "model", descriptionKey: "docs.reference.fieldSTTModel" }, + { name: "file", descriptionKey: "docs.reference.fieldSTTFile" }, + { name: "url", descriptionKey: "docs.reference.fieldSTTUrl" }, + { name: "language", descriptionKey: "docs.reference.fieldVoiceLanguage" }, + { name: "format", descriptionKey: "docs.reference.fieldSTTFormat" }, + { name: "diarize", descriptionKey: "docs.reference.fieldSTTDiarize" }, + { name: "keyterm", descriptionKey: "docs.reference.fieldSTTKeyterm" }, + ], + noteKeys: ["docs.reference.noteSTTInput", "docs.reference.noteSTTStream", "docs.reference.noteSTTModels", "docs.reference.noteVoiceBilling"], + request: (model) => ({ model, url: "https://example.com/sample.wav", language: "en", format: true }), + response: { text: "Hello from Grok voice.", language: "en", duration: 1.84, words: [{ text: "Hello", start: 0.0, end: 0.42 }] }, + }, + "voice/realtime": { + key: "voice/realtime", category: "Voice", title: "Realtime websocket", method: "GET", path: "/realtime", + descriptionKey: "docs.endpointRealtime", capabilities: ["realtime"], + fields: [ + { name: "model", descriptionKey: "docs.reference.fieldRealtimeModelQuery" }, + { name: "Upgrade", required: true, descriptionKey: "docs.reference.fieldWSUpgrade" }, + ], + noteKeys: ["docs.reference.noteRealtimeEvents", "docs.reference.noteRealtimeProxy", "docs.reference.noteRealtimeAuth", "docs.reference.noteVoiceBilling"], + request: () => undefined, + response: { type: "session.created", session: { model: "grok-voice-latest" } }, + }, }; export function ApiDocsPage() { @@ -235,12 +360,22 @@ function withExampleModel(response: Record, model: string): Rec function fallbackModel(key: string): string { if (key.startsWith("image/")) return key === "image/edits" ? "grok-imagine-image-edit" : "grok-imagine-image-lite"; if (key.startsWith("video/")) return "grok-imagine-video"; + if (key.startsWith("voice/")) { + if (key === "voice/stt" || key === "voice/audio-transcriptions") return "grok-stt"; + return "grok-voice-latest"; + } return "your-enabled-model"; } function createExamples(definition: EndpointDefinition, baseUrl: string, model: string): Record { const request = definition.request(model); - const url = `${baseUrl}${definition.path.replace("{request_id}", "video_example")}`; + const path = definition.path + .replace("{request_id}", "video_example"); + const url = definition.key === "voice/realtime" + ? `${baseUrl}${path}?model=${encodeURIComponent(model)}` + : definition.key === "voice/voices" + ? `${baseUrl}${path}?model=${encodeURIComponent(model)}` + : `${baseUrl}${path}`; const messageHeaders = definition.key === "chat/messages"; const curlHeaders = messageHeaders ? [ diff --git a/frontend/src/features/media/media-api.ts b/frontend/src/features/media/media-api.ts index adeb6274..035348c9 100644 --- a/frontend/src/features/media/media-api.ts +++ b/frontend/src/features/media/media-api.ts @@ -102,6 +102,7 @@ export function deleteVideos(ids: string[]): Promise<{ deleted: number }> { // 临时输入不会进入图库,也不会生成公开 URL;任务只持久化短 file_id。 export type MediaInputDTO = { fileId: string; + kind: string; mimeType: string; sizeBytes: number; expiresAt: string; @@ -109,6 +110,7 @@ export type MediaInputDTO = { const decodeMediaInput = createValidatedDecoder("media input", hasShape({ fileId: isString, + kind: isString, mimeType: isString, sizeBytes: isNumber, expiresAt: isString, @@ -118,9 +120,9 @@ export function importVideoInputFromURL(url: string): Promise { return apiRequest("/api/admin/v1/media/inputs/import", { method: "POST", body: { url } }, decodeMediaInput); } -// 以 multipart/form-data 上传本地图片到有 TTL 的临时输入区。 +// 以 multipart/form-data 上传本地图片或视频到有 TTL 的临时输入区。 // 注意:不要手动设置 Content-Type,浏览器会自动带上 multipart 边界。 -export function uploadVideoInput(file: File): Promise { +export function uploadMediaInput(file: File): Promise { const body = new FormData(); body.append("file", file, file.name); return apiRequest("/api/admin/v1/media/inputs/upload", { method: "POST", body }, decodeMediaInput); diff --git a/frontend/src/features/models/models-page.tsx b/frontend/src/features/models/models-page.tsx index 8895513b..65658356 100644 --- a/frontend/src/features/models/models-page.tsx +++ b/frontend/src/features/models/models-page.tsx @@ -1,7 +1,7 @@ import { zodResolver } from "@hookform/resolvers/zod"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import type { TFunction } from "i18next"; -import { Clapperboard, Image as ImageIcon, MessagesSquare, MessageSquareText, MoreHorizontal, Paintbrush, Pencil, Plus, RefreshCw, Search, SquareTerminal, Trash2 } from "lucide-react"; +import { AudioLines, Clapperboard, Image as ImageIcon, MessagesSquare, MessageSquareText, Mic, MoreHorizontal, Paintbrush, Pencil, Plus, Radio, RefreshCw, Search, SquareTerminal, Trash2 } from "lucide-react"; import { useMemo, useState } from "react"; import { useForm, useWatch } from "react-hook-form"; import { useTranslation } from "react-i18next"; @@ -53,7 +53,7 @@ export function ModelsPage() { publicId: z.string().min(1, t("errors.required")), provider: z.enum(["grok_build", "grok_web", "grok_console"]), upstreamModel: z.string().min(1, t("errors.required")), - capability: z.enum(["responses", "chat", "image", "image_edit", "video"]), + capability: z.enum(["responses", "chat", "image", "image_edit", "video", "tts", "stt", "realtime"]), enabled: z.boolean(), bindingMode: z.boolean(), accountIds: z.array(z.string()), @@ -473,6 +473,9 @@ const endpointCapabilityMetadata = { image: { icon: ImageIcon, method: "POST", path: "/v1/images/generations", color: "text-emerald-600 dark:text-emerald-400" }, image_edit: { icon: Paintbrush, method: "POST", path: "/v1/images/edits", color: "text-amber-700 dark:text-amber-400" }, video: { icon: Clapperboard, method: "POST", path: "/v1/videos/generations", color: "text-rose-600 dark:text-rose-400" }, + tts: { icon: AudioLines, method: "POST", path: "/v1/tts", color: "text-cyan-700 dark:text-cyan-400" }, + stt: { icon: Mic, method: "POST", path: "/v1/stt", color: "text-teal-700 dark:text-teal-400" }, + realtime: { icon: Radio, method: "GET", path: "/v1/realtime", color: "text-sky-700 dark:text-sky-400" }, } as const; type ModelRouteGroup = { @@ -533,5 +536,8 @@ function displayCapabilityLabel(capability: ModelDisplayCapability, t: TFunction image: t("models.capabilityImage"), image_edit: t("models.capabilityImageEdit"), video: t("models.capabilityVideo"), + tts: t("models.capabilityTTS"), + stt: t("models.capabilitySTT"), + realtime: t("models.capabilityRealtime"), }[capability]; } diff --git a/frontend/src/features/settings/egress-operations.tsx b/frontend/src/features/settings/egress-operations.tsx index f1d5ca5e..4002c595 100644 --- a/frontend/src/features/settings/egress-operations.tsx +++ b/frontend/src/features/settings/egress-operations.tsx @@ -30,7 +30,6 @@ import { type EgressFallbackMode, type EgressNodeDTO, type EgressOperationsConfigDTO, - type EgressOperationsConfigInput, type EgressScope, type EgressSourceDTO, type EgressSourceInput, @@ -43,13 +42,9 @@ import { DataTableShell } from "@/shared/components/data-table-shell"; import { Pagination } from "@/shared/components/pagination"; import { VirtualTableBody } from "@/shared/components/virtual-table-body"; -type SourceForm = EgressSourceInput & { url: string }; -type OperationsForm = Omit & { - subscriptionProxyURL: string; - clearSubscriptionProxy: boolean; -}; +type SourceForm = Omit & { url: string; proxyEnabled: boolean; proxyURL: string }; const emptySource: SourceForm = { - name: "", scope: "grok_build", enabled: true, url: "", refreshIntervalSeconds: 900, defaultAccountCapacity: 0, + name: "", scope: "grok_build", enabled: true, url: "", proxyEnabled: false, proxyURL: "", refreshIntervalSeconds: 900, defaultAccountCapacity: 0, }; // Eight nodes run concurrently; each checks IPv4 and IPv6 in parallel with a // 15-second ceiling. Keeping a request to 32 nodes leaves enough headroom for @@ -71,11 +66,11 @@ function defaultFallbacks(): Record { }; } -const defaultOperationsForm: OperationsForm = { - probeProvider: "cloudflare", probeIntervalSeconds: 900, autoAssignEnabled: false, autoBalanceEnabled: false, assignmentIntervalSeconds: 300, fallbacks: defaultFallbacks(), subscriptionProxyURL: "", subscriptionProxyConfigured: false, clearSubscriptionProxy: false, +const defaultOperationsForm: Omit = { + probeProvider: "cloudflare", probeIntervalSeconds: 900, autoAssignEnabled: false, autoBalanceEnabled: false, assignmentIntervalSeconds: 300, fallbacks: defaultFallbacks(), }; -function operationsFormFrom(value?: EgressOperationsConfigDTO): OperationsForm { +function operationsFormFrom(value?: EgressOperationsConfigDTO): Omit { if (!value) return { ...defaultOperationsForm, fallbacks: defaultFallbacks() }; const defaults = defaultFallbacks(); @@ -92,26 +87,9 @@ function operationsFormFrom(value?: EgressOperationsConfigDTO): OperationsForm { grok_web_asset: { ...defaults.grok_web_asset, ...value.fallbacks.grok_web_asset }, grok_console_asset: { ...defaults.grok_console_asset, ...value.fallbacks.grok_console_asset }, }, - subscriptionProxyURL: "", - subscriptionProxyConfigured: value.subscriptionProxyConfigured, - clearSubscriptionProxy: false, }; } -function operationsInputFrom(value: OperationsForm): EgressOperationsConfigInput { - const result: EgressOperationsConfigInput = { - probeProvider: value.probeProvider, - probeIntervalSeconds: value.probeIntervalSeconds, - autoAssignEnabled: value.autoAssignEnabled, - autoBalanceEnabled: value.autoBalanceEnabled, - assignmentIntervalSeconds: value.assignmentIntervalSeconds, - fallbacks: value.fallbacks, - }; - if (value.clearSubscriptionProxy) result.clearSubscriptionProxy = true; - else if (value.subscriptionProxyURL.trim()) result.subscriptionProxyURL = value.subscriptionProxyURL.trim(); - return result; -} - async function testAllEgressNodes() { const nodes = await listAllEgressNodes(); const ids = nodes.items.filter((node) => node.enabled && node.proxyConfigured).map((node) => node.id); @@ -138,8 +116,7 @@ async function testAllEgressNodes() { export function EgressAutomation({ scopeLabel }: { scopeLabel: (scope: EgressScope) => string }) { const { t } = useTranslation(); const queryClient = useQueryClient(); - const [operationsDraft, setOperationsDraft] = useState(null); - const [subscriptionProxyError, setSubscriptionProxyError] = useState(""); + const [operationsDraft, setOperationsDraft] = useState | null>(null); const operationsQuery = useQuery({ queryKey: ["egress-operations"], queryFn: getEgressOperationsConfig }); const nodesQuery = useQuery({ queryKey: ["egress-nodes", "fallback-options"], queryFn: () => listAllEgressNodes() }); const operationsForm = operationsDraft ?? operationsFormFrom(operationsQuery.data); @@ -163,7 +140,7 @@ export function EgressAutomation({ scopeLabel }: { scopeLabel: (scope: EgressSco onError: showError, }); const saveOperations = useMutation({ - mutationFn: () => updateEgressOperationsConfig(operationsInputFrom(operationsForm)), + mutationFn: () => updateEgressOperationsConfig(operationsForm), onSuccess: () => { setOperationsDraft(null); invalidate(); toast.success(t("settings.egress.automationSaved")); }, onError: showError, }); @@ -188,7 +165,7 @@ export function EgressAutomation({ scopeLabel }: { scopeLabel: (scope: EgressSco testAll.mutate()}>{testAll.isPending ? : }{t("settings.egress.testAll")} rebalance.mutate()}>{rebalance.isPending ? : }{t("settings.egress.rebalance")} - saveOperations.mutate()}>{saveOperations.isPending ? : null}{t("common.save")} + saveOperations.mutate()}>{saveOperations.isPending ? : null}{t("common.save")} {operationsQuery.isError ? void operationsQuery.refetch()} /> : operationsQuery.isPending ? : ( @@ -214,43 +191,6 @@ export function EgressAutomation({ scopeLabel }: { scopeLabel: (scope: EgressSco setOperationsDraft({ ...operationsForm, autoBalanceEnabled })} /> - - - - { - const value = event.target.value; - setOperationsDraft({ ...operationsForm, subscriptionProxyURL: value, clearSubscriptionProxy: false }); - setSubscriptionProxyError(value.trim() && !validSubscriptionProxyURL(value) ? t("settings.egress.invalidProxy") : ""); - }} - /> - {operationsForm.subscriptionProxyConfigured ? ( - { - setOperationsDraft({ ...operationsForm, subscriptionProxyURL: "", clearSubscriptionProxy: !operationsForm.clearSubscriptionProxy }); - setSubscriptionProxyError(""); - }} - > - {operationsForm.clearSubscriptionProxy ? t("settings.egress.cancelClearSubscriptionProxy") : t("settings.egress.clearSubscriptionProxy")} - - ) : null} - - {operationsForm.subscriptionProxyConfigured ? ( - - - {operationsForm.clearSubscriptionProxy ? t("settings.egress.subscriptionProxyClearPending") : t("settings.egress.configured")} - - {!operationsForm.clearSubscriptionProxy && !operationsForm.subscriptionProxyURL ? {t("settings.egress.keepConfigured")} : null} - - ) : null} - - {t("settings.egress.fallback")} @@ -319,7 +259,13 @@ export function EgressSources({ scopeLabel }: { scopeLabel: (scope: EgressScope) }; const saveSource = useMutation({ mutationFn: () => { - const input: EgressSourceInput = { ...sourceForm, url: sourceForm.url.trim() || undefined }; + const input: EgressSourceInput = { + name: sourceForm.name, scope: sourceForm.scope, enabled: sourceForm.enabled, + url: sourceForm.url.trim() || undefined, + proxyURL: sourceForm.proxyEnabled ? (sourceForm.proxyURL.trim() || undefined) : undefined, + clearProxyURL: Boolean(sourceEditing?.proxyConfigured && !sourceForm.proxyEnabled), + refreshIntervalSeconds: sourceForm.refreshIntervalSeconds, defaultAccountCapacity: sourceForm.defaultAccountCapacity, + }; return sourceEditing ? updateEgressSource(sourceEditing.id, input) : createEgressSource(input); }, onSuccess: () => { if (!sourceEditing) setPage(1); invalidate(); setSourceEditing(undefined); toast.success(t("settings.egress.sourceSaved")); }, @@ -344,7 +290,7 @@ export function EgressSources({ scopeLabel }: { scopeLabel: (scope: EgressScope) } setSourceForm({ name: value.name, scope: value.scope, enabled: value.enabled, url: "", refreshIntervalSeconds: value.refreshIntervalSeconds, - defaultAccountCapacity: value.defaultAccountCapacity, + proxyEnabled: value.proxyConfigured, proxyURL: "", defaultAccountCapacity: value.defaultAccountCapacity, }); setSourceEditing(value); } @@ -359,6 +305,7 @@ export function EgressSources({ scopeLabel }: { scopeLabel: (scope: EgressScope) const currentPage = Math.min(page, pageCount); const pagedSources = filteredSources.slice((currentPage - 1) * pageSize, currentPage * pageSize); const hasActiveFilters = Boolean(normalizedSearch || scopeFilter); + const sourceProxyInvalid = sourceForm.proxyEnabled && Boolean(sourceForm.proxyURL.trim()) && !validSubscriptionProxyURL(sourceForm.proxyURL); return ( @@ -388,14 +335,15 @@ export function EgressSources({ scopeLabel }: { scopeLabel: (scope: EgressScope) footer={filteredSources.length > 0 ? { setPageSize(value); setPage(1); }} /> : undefined} > {sourcesQuery.isError ? void sourcesQuery.refetch()} /> : null} - {!sourcesQuery.isError ? - {t("settings.egress.source")}{t("settings.egress.scope")}{t("settings.egress.lastSync")}{t("settings.egress.capacity")} - {sourcesQuery.isPending ? : null} - {!sourcesQuery.isPending && pagedSources.length === 0 ? {hasActiveFilters ? t("settings.egress.noSubscriptionMatches") : t("settings.egress.noSources")} : null} - {!sourcesQuery.isPending && pagedSources.length > 0 ? ( + {!sourcesQuery.isError ? + {t("settings.egress.source")}{t("settings.egress.scope")}{t("settings.egress.subscriptionRoute")}{t("settings.egress.lastSync")}{t("settings.egress.capacity")} + {sourcesQuery.isPending ? : null} + {!sourcesQuery.isPending && pagedSources.length === 0 ? {hasActiveFilters ? t("settings.egress.noSubscriptionMatches") : t("settings.egress.noSources")} : null} + {!sourcesQuery.isPending && pagedSources.length > 0 ? ( {source.name}{source.lastSyncError ? : null} {scopeLabel(source.scope)} + {source.proxyConfigured ? t("settings.egress.subscriptionProxyShort") : t("settings.egress.direct")} {source.lastSyncedAt ? formatDateTime(source.lastSyncedAt, i18n.language) : t("settings.egress.never")} {source.defaultAccountCapacity || t("settings.egress.unlimited")} @@ -419,11 +367,13 @@ export function EgressSources({ scopeLabel }: { scopeLabel: (scope: EgressScope) setSourceForm({ ...sourceForm, name: event.target.value })} /> setSourceForm({ ...sourceForm, scope })} scopeLabel={scopeLabel} /> setSourceForm({ ...sourceForm, url: event.target.value })} /> + setSourceForm({ ...sourceForm, proxyEnabled })} /> + {sourceForm.proxyEnabled ? setSourceForm({ ...sourceForm, proxyURL: event.target.value })} />{sourceProxyInvalid ? {t("settings.egress.invalidSubscriptionProxy")} : null} : null} setSourceForm({ ...sourceForm, refreshIntervalSeconds: Number(event.target.value) })} /> setSourceForm({ ...sourceForm, defaultAccountCapacity: Number(event.target.value) })} /> - setSourceEditing(undefined)}>{t("common.cancel")}{saveSource.isPending ? : null}{t("common.save")} + setSourceEditing(undefined)}>{t("common.cancel")}{saveSource.isPending ? : null}{t("common.save")} diff --git a/frontend/src/features/settings/settings-api.ts b/frontend/src/features/settings/settings-api.ts index 22fda831..e05c1c10 100644 --- a/frontend/src/features/settings/settings-api.ts +++ b/frontend/src/features/settings/settings-api.ts @@ -64,7 +64,7 @@ export type EgressNodeListDTO = { defaultUserAgents: Record; }; export type EgressSourceDTO = { - id: string; name: string; scope: EgressScope; enabled: boolean; urlConfigured: boolean; + id: string; name: string; scope: EgressScope; enabled: boolean; urlConfigured: boolean; proxyConfigured: boolean; refreshIntervalSeconds: number; defaultAccountCapacity: number; lastSyncedAt?: string; nextSyncAt?: string; lastSyncImported: number; lastSyncError?: string; }; @@ -76,16 +76,12 @@ export type EgressSourceListDTO = { }; export type EgressSourceInput = { name: string; scope: EgressScope; enabled: boolean; url?: string; clearUrl?: boolean; + proxyURL?: string; clearProxyURL?: boolean; refreshIntervalSeconds: number; defaultAccountCapacity: number; }; export type EgressOperationsConfigDTO = { probeProvider: "ipinfo" | "cloudflare"; probeIntervalSeconds: number; autoAssignEnabled: boolean; autoBalanceEnabled: boolean; assignmentIntervalSeconds: number; fallbacks: Record; updatedAt: string; - subscriptionProxyConfigured: boolean; -}; -export type EgressOperationsConfigInput = Omit & { - subscriptionProxyURL?: string; - clearSubscriptionProxy?: boolean; }; export type EgressImportResultDTO = { imported: number; skipped: number }; export type EgressIPProbeDTO = { status: "unknown" | "healthy" | "unhealthy"; testedAt?: string; latencyMs: number; exitIp?: string; error?: string }; @@ -195,9 +191,9 @@ const egressIPProbeValidator = hasShape({ status: isOneOf("unknown", "healthy", "unhealthy"), testedAt: isOptional(isString), latencyMs: isNumber, exitIp: isOptional(isString), error: isOptional(isString), }); type EgressNodeWireDTO = Omit & { ipv4Probe?: EgressIPProbeDTO; ipv6Probe?: EgressIPProbeDTO }; -type EgressOperationsConfigWireDTO = Omit & { +type EgressSourceWireDTO = Omit & { proxyConfigured?: boolean }; +type EgressOperationsConfigWireDTO = Omit & { probeProvider?: "ipinfo" | "cloudflare"; - subscriptionProxyConfigured?: boolean; }; type EgressProbeResultWireDTO = Omit & { ipv4?: EgressIPProbeDTO; ipv6?: EgressIPProbeDTO }; const unknownEgressIPProbe = (): EgressIPProbeDTO => ({ status: "unknown", latencyMs: 0 }); @@ -206,6 +202,10 @@ const withEgressNodeProbeDefaults = (value: EgressNodeWireDTO): EgressNodeDTO => ipv4Probe: value.ipv4Probe ?? unknownEgressIPProbe(), ipv6Probe: value.ipv6Probe ?? unknownEgressIPProbe(), }); +const withEgressSourceDefaults = (value: EgressSourceWireDTO): EgressSourceDTO => ({ + ...value, + proxyConfigured: value.proxyConfigured ?? false, +}); const egressNodeValidator = hasShape({ id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset", "grok_console_asset"), enabled: isBoolean, proxyConfigured: isBoolean, userAgent: isString, cookieConfigured: isBoolean, accountBoundProxy: isBoolean, proxyPool: isBoolean, health: isNumber, failureCount: isNumber, @@ -253,16 +253,19 @@ const decodeEgressNodeList = (value: unknown): EgressNodeListDTO => { }; const egressSourceValidator = hasShape({ id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset", "grok_console_asset"), enabled: isBoolean, urlConfigured: isBoolean, + proxyConfigured: isOptional(isBoolean), refreshIntervalSeconds: isNumber, defaultAccountCapacity: isNumber, lastSyncedAt: isOptional(isString), nextSyncAt: isOptional(isString), lastSyncImported: isNumber, lastSyncError: isOptional(isString), }); -const decodeEgressSource = createObjectDecoder("egress source", { +const decodeEgressSourceRaw = createObjectDecoder("egress source", { id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset", "grok_console_asset"), enabled: isBoolean, urlConfigured: isBoolean, + proxyConfigured: isOptional(isBoolean), refreshIntervalSeconds: isNumber, defaultAccountCapacity: isNumber, lastSyncedAt: isOptional(isString), nextSyncAt: isOptional(isString), lastSyncImported: isNumber, lastSyncError: isOptional(isString), }); +const decodeEgressSource = (value: unknown) => withEgressSourceDefaults(decodeEgressSourceRaw(value)); type EgressSourceListWireDTO = { - items: EgressSourceDTO[]; + items: EgressSourceWireDTO[]; page?: number; pageSize?: number; total?: number; @@ -274,6 +277,7 @@ const decodeEgressSourceList = (value: unknown): EgressSourceListDTO => { const decoded = decodeEgressSourceListRaw(value); return { ...decoded, + items: decoded.items.map(withEgressSourceDefaults), page: decoded.page ?? 1, pageSize: decoded.pageSize ?? Math.max(20, decoded.items.length), total: decoded.total ?? decoded.items.length, @@ -286,11 +290,10 @@ const egressFallbackConfigValidator = hasShape({ mode: isOneOf("none", "direct", const decodeEgressOperationsConfigRaw = createObjectDecoder("egress operations config", { probeProvider: isOptional(isOneOf("ipinfo", "cloudflare")), probeIntervalSeconds: isNumber, autoAssignEnabled: isBoolean, autoBalanceEnabled: isBoolean, assignmentIntervalSeconds: isNumber, fallbacks: isRecordOf(egressFallbackConfigValidator), updatedAt: isString, - subscriptionProxyConfigured: isOptional(isBoolean), }); const decodeEgressOperationsConfig = (value: unknown): EgressOperationsConfigDTO => { const decoded = decodeEgressOperationsConfigRaw(value); - return { ...decoded, probeProvider: decoded.probeProvider ?? "cloudflare", subscriptionProxyConfigured: decoded.subscriptionProxyConfigured ?? false }; + return { ...decoded, probeProvider: decoded.probeProvider ?? "cloudflare" }; }; const decodeEgressProbeResultRaw = createObjectDecoder("egress probe", { status: isOneOf("unknown", "healthy", "unhealthy"), testedAt: isString, latencyMs: isNumber, exitIp: isOptional(isString), error: isOptional(isString), probeProvider: isOptional(isOneOf("ipinfo", "cloudflare")), @@ -428,7 +431,7 @@ export function getEgressOperationsConfig(): Promise return apiRequest("/api/admin/v1/egress-operations", {}, decodeEgressOperationsConfig); } -export function updateEgressOperationsConfig(input: EgressOperationsConfigInput): Promise { +export function updateEgressOperationsConfig(input: Omit): Promise { return apiRequest("/api/admin/v1/egress-operations", { method: "PUT", body: input }, decodeEgressOperationsConfig); } diff --git a/frontend/src/features/settings/settings-model.ts b/frontend/src/features/settings/settings-model.ts index d31c1411..a35b4420 100644 --- a/frontend/src/features/settings/settings-model.ts +++ b/frontend/src/features/settings/settings-model.ts @@ -351,21 +351,45 @@ function validHTTPURL(value: string): boolean { } } -/** Validates HTTP and SOCKS proxy URLs. Empty is allowed for write-only form fields. */ +/** Performs fast client-side proxy validation; the backend remains authoritative. */ function validProxyURL(value: string): boolean { const trimmed = value.trim(); if (trimmed.length === 0) return true; - if (trimmed.length > 2048 || [...trimmed].some((char) => { + if (trimmed.length > 8192 || [...trimmed].some((char) => { const code = char.charCodeAt(0); return code <= 0x1f || code === 0x7f; })) return false; if ((trimmed.match(/\{account\}/g) ?? []).length > 1) return false; + const scheme = trimmed.slice(0, trimmed.indexOf(":")).toLowerCase(); + if (["trojan", "vless", "ss", "vmess"].includes(scheme) && trimmed.includes("{account}")) return false; + if (scheme === "vmess") return validVMessURL(trimmed); + if (scheme === "ss") return validShadowsocksURL(trimmed); try { const parseValue = trimmed.replaceAll("{account}", "grok2api_account_placeholder"); const parsed = new URL(parseValue); if (!parsed.host || !parsed.hostname) return false; - const scheme = parsed.protocol.replace(/:$/, "").toLowerCase(); - if (!["http", "https", "socks4", "socks4a", "socks5", "socks5h"].includes(scheme)) return false; + const parsedScheme = parsed.protocol.replace(/:$/, "").toLowerCase(); + if (["trojan", "vless"].includes(parsedScheme)) { + if (!parsed.username || parsed.password || !parsed.port) return false; + const transport = (parsed.searchParams.get("type") ?? parsed.searchParams.get("network") ?? "tcp").toLowerCase(); + if (!["tcp", "none", "ws", "websocket"].includes(transport)) return false; + const security = (parsed.searchParams.get("security") ?? "").toLowerCase(); + if (!["", "none", "tls"].includes(security)) return false; + if (parsed.searchParams.get("flow")) return false; + if (parsedScheme === "vless" && !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(parsed.username)) return false; + if (parsedScheme === "vless" && !["", "none"].includes((parsed.searchParams.get("encryption") ?? "").toLowerCase())) return false; + if (!["", "none"].includes((parsed.searchParams.get("headerType") ?? "").toLowerCase())) return false; + if (!validTunnelBoolean(parsed.searchParams, ["allowInsecure", "insecure", "skip-cert-verify"])) return false; + if (parsed.pathname !== "" && parsed.pathname !== "/") return false; + const webSocket = transport === "ws" || transport === "websocket"; + if (!webSocket && (parsed.searchParams.has("host") || parsed.searchParams.has("path"))) return false; + if (webSocket) { + const host = parsed.searchParams.get("host") ?? parsed.searchParams.get("sni") ?? parsed.searchParams.get("peer") ?? parsed.hostname; + if (!validWebSocketHost(host)) return false; + } + return true; + } + if (!["http", "https", "socks4", "socks4a", "socks5", "socks5h"].includes(parsedScheme)) return false; if (parsed.search || parsed.hash || (parsed.pathname !== "" && parsed.pathname !== "/")) return false; if (trimmed.includes("{account}")) { if (!parsed.username.includes("grok2api_account_placeholder")) return false; @@ -376,7 +400,101 @@ function validProxyURL(value: string): boolean { } } -/** Subscription fetch proxies are global and must never use per-account lease placeholders. */ +function validShadowsocksURL(value: string): boolean { + try { + let payload = value.slice("ss://".length).split("#", 1)[0]; + const queryIndex = payload.indexOf("?"); + if (queryIndex >= 0) { + if ([...new URLSearchParams(payload.slice(queryIndex + 1)).keys()].length !== 0) return false; + payload = payload.slice(0, queryIndex); + } + let credentials: string; + let server: string; + const separator = payload.lastIndexOf("@"); + if (separator >= 0) { + credentials = decodeURIComponent(payload.slice(0, separator)); + if (!credentials.includes(":")) credentials = decodeBase64Text(credentials); + server = payload.slice(separator + 1); + } else { + const decoded = decodeBase64Text(payload); + const legacySeparator = decoded.lastIndexOf("@"); + if (legacySeparator < 0) return false; + credentials = decoded.slice(0, legacySeparator); + server = decoded.slice(legacySeparator + 1); + } + const credentialSeparator = credentials.indexOf(":"); + if (credentialSeparator <= 0 || credentialSeparator === credentials.length - 1) return false; + const method = credentials.slice(0, credentialSeparator).trim().toLowerCase(); + if (!["aes-128-gcm", "aes-256-gcm", "chacha20-ietf-poly1305"].includes(method)) return false; + const parsed = new URL(`ss://${server}`); + return parsed.username === "" && parsed.password === "" && parsed.hostname !== "" && parsed.port !== "" + && (parsed.pathname === "" || parsed.pathname === "/") && parsed.search === "" && parsed.hash === ""; + } catch { + return false; + } +} + +function decodeBase64Text(value: string): string { + let payload = value.replaceAll("-", "+").replaceAll("_", "/"); + payload += "=".repeat((4 - (payload.length % 4)) % 4); + const bytes = Uint8Array.from(atob(payload), (character) => character.charCodeAt(0)); + return new TextDecoder().decode(bytes); +} + +function validTunnelBoolean(query: URLSearchParams, names: string[]): boolean { + for (const name of names) { + if (!query.has(name)) continue; + return ["", "0", "1", "false", "true", "no", "yes"].includes((query.get(name) ?? "").trim().toLowerCase()); + } + return true; +} + +function validWebSocketHost(value: string): boolean { + try { + const parsed = new URL(`http://${value.trim()}`); + return parsed.hostname !== "" && parsed.username === "" && parsed.password === "" + && (parsed.pathname === "" || parsed.pathname === "/") && parsed.search === "" && parsed.hash === ""; + } catch { + return false; + } +} + +function validVMessURL(value: string): boolean { + try { + let payload = value.slice("vmess://".length).split("#", 1)[0].replaceAll("-", "+").replaceAll("_", "/"); + payload += "=".repeat((4 - (payload.length % 4)) % 4); + const bytes = Uint8Array.from(atob(payload), (character) => character.charCodeAt(0)); + const config = JSON.parse(new TextDecoder().decode(bytes)) as Record; + const id = String(config.id ?? ""); + const port = Number(config.port); + const network = String(config.net ?? "tcp").toLowerCase(); + const tls = String(config.tls ?? "").toLowerCase(); + const cipher = String(config.scy ?? config.security ?? "auto").toLowerCase(); + const headerType = String(config.type ?? "").toLowerCase(); + const alterID = Number(config.aid ?? 0); + const webSocket = network === "ws" || network === "websocket"; + const host = String(config.host ?? config.sni ?? config.add ?? ""); + return typeof config.add === "string" && config.add.trim() !== "" && Number.isInteger(port) && port > 0 && port <= 65535 + && /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(id) + && Number.isInteger(alterID) && alterID >= 0 && alterID <= 65535 + && ["tcp", "ws", "websocket"].includes(network) && ["", "none", "tls"].includes(tls) + && ["auto", "aes-128-gcm", "chacha20-poly1305", "none"].includes(cipher) + && ["", "none"].includes(headerType) + && validJSONTunnelBoolean(config.allowInsecure) + && (webSocket ? validWebSocketHost(host) : String(config.path ?? "") === "" && String(config.host ?? "") === ""); + } catch { + return false; + } +} + +function validJSONTunnelBoolean(value: unknown): boolean { + if (value == null || typeof value === "boolean") return true; + if (typeof value === "number") return value === 0 || value === 1; + if (typeof value === "string") return ["", "0", "1", "false", "true", "no", "yes"].includes(value.trim().toLowerCase()); + return false; +} + +/** Subscription fetch proxies must never use per-account lease placeholders. */ export function validSubscriptionProxyURL(value: string): boolean { return !value.includes("{account}") && validProxyURL(value); } diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index bef6f887..1a21a816 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -182,12 +182,12 @@ const resources = { }, creativeConsole: { title: "创作控制台", - description: "使用已创建的客户端密钥直接测试聊天、图片和视频生成。", + description: "使用已创建的客户端密钥直接测试聊天、图片、视频和语音。", promotion: "想要更完整的 AI 创作体验?试试我开发的另一个项目 {{product}}:开箱即用的轻量 Web Chat,支持多模型对话与图片生成,静态运行时仅约 34 MB。", promotionAction: "了解 DEEIX Chat", clientKey: "客户端密钥", selectKey: "选择客户端密钥", - modes: { chat: "聊天", image: "图片", video: "视频" }, + modes: { chat: "聊天", image: "图片", video: "视频", voice: "语音" }, welcome: "今天想创作什么?", welcomeImage: "描述你的想法,生成一幅图片", welcomeVideo: "描述你的想法,生成一段视频", @@ -210,6 +210,31 @@ const resources = { chatPlaceholder: "输入要发送给模型的内容。", imagePlaceholder: "描述要生成的画面、主体、风格和细节。", videoPlaceholder: "描述视频画面、动作、镜头和节奏。", + videoEditPlaceholder: "描述希望如何修改原视频。", + videoExtendPlaceholder: "描述视频接下来应发生的内容。", + welcomeVideoEdit: "提供源视频并开始编辑", + welcomeVideoExtend: "提供源视频并开始延长", + videoActions: { generate: "生成", edit: "编辑", extend: "延长" }, + sourceVideo: "源视频 URL", + sourceVideoShort: "源视频", + sourceVideoAdded: "已添加源视频", + clearSourceVideo: "移除源视频", + editVideo: "编辑视频", + extendVideo: "延长视频", + extendDuration: "延长时长(秒)", + voicePlaceholder: "输入要合成的文本,或上传音频进行识别。", + welcomeVoice: "选择音色并开始语音创作", + synthesizing: "正在合成语音…", + transcribing: "正在识别语音…", + uploadAudio: "上传音频", + clearAudio: "清除音频", + + synthesize: "合成语音", + transcribe: "识别语音", + voiceLanguage: "语言", + voiceId: "音色", + voiceSpeed: "语速", + send: "发送", messageList: "对话消息", scrollToLatest: "滚动到最新消息", @@ -235,16 +260,25 @@ const resources = { count: "数量", aspectRatio: "宽高比", resolution: "分辨率", + quality: "质量", generateImage: "生成图片", generatingImage: "正在生成图片...", generatedImageAlt: "生成图片 {{index}}", imageNumber: "图片 {{index}}", open: "打开", + firstFrameImage: "首帧图片 URL", + firstFrameImageShort: "首帧图", + firstFrameImageAdded: "已添加首帧", + clearFirstFrameImage: "移除首帧图", referenceImage: "参考图片 URL", - referenceImageShort: "参考图片", - referenceImageAdded: "已添加图片", - clearReferenceImage: "移除参考图片", + referenceImageShort: "参考图", + referenceImageAdded: "已添加参考图", + clearReferenceImage: "移除参考图", + referenceVoice: "参考音色", + referenceVoiceShort: "音色", + referenceVoiceNone: "不使用参考音色", uploadImage: "上传本地图片", + uploadVideo: "上传本地视频", duration: "时长(秒)", generateVideo: "生成视频", submittingVideo: "正在提交视频任务...", @@ -260,6 +294,10 @@ const resources = { noKeys: "没有可用的已启用客户端密钥,请先创建或启用密钥。", noModels: "当前模式没有可用模型,请确认模型已启用且账号池可服务。", videoFailed: "视频生成失败", + noSourceVideo: "请先填写源视频 URL 或上传本地视频", + invalidImage: "请选择有效的图片文件", + invalidVideo: "请选择有效的 MP4、WebM 或 QuickTime 视频文件", + noAudio: "请先选择音频文件", }, }, media: { @@ -517,6 +555,13 @@ const resources = { webModeQuotaRemaining: "{{mode}} 剩余可调用 {{remaining}} 次", webWeeklyQuotaUsage: "周额度剩余 {{remaining}}%", paidQuotaDetails: "剩余 {{remaining}} credits", + imagineQuota: "Imagine 配额", + imagineQuotaRemaining: "剩余 {{remaining}} 次", + imagineQuotaExhausted: "已耗尽,冷却中", + imagineModeImagePro: "生图", + imagineModeImageEdit: "图片编辑", + imagineModeVideo: "视频", + imagineModeVideo720p: "视频 720p", created: "账号接入成功", createdWithSyncFailure: "账号已接入,但额度或模型初始同步失败", updated: "账号已更新", @@ -808,7 +853,7 @@ const resources = { statusServerError: "服务端错误", statusOtherError: "其它错误", errorLabel: "错误", - operations: { responses: "Responses", compaction: "上下文压缩", chat: "Chat", messages: "Messages", image: "图像生成", image_edit: "图像编辑", video: "视频生成" }, + operations: { responses: "Responses", compaction: "上下文压缩", chat: "Chat", messages: "Messages", image: "图像生成", image_edit: "图像编辑", video: "视频生成", tts: "语音合成", stt: "语音识别", realtime: "实时语音", voice: "语音" }, compactionUsageUnavailable: "上游未返回用量", usageSummary: "用量统计", totalRequests: "总请求", @@ -819,6 +864,7 @@ const resources = { successRate: "成功率", averageDuration: "平均耗时 {{duration}}", estimatedCost: "估算费用", + unbilled: "未计费", exactBilling: "完整数值", billingSource: "计费来源", billingSourceUpstream: "上游实报费用", @@ -829,13 +875,13 @@ const resources = { billingLongContextTier: "长上下文", billingFormula: "计算公式", billingUpstreamFormula: "由上游直接返回最终费用,本地不重复按费率估算。", - billingStoredFormulaUnavailable: "该记录使用历史或未知费率版本,仅保留最终估算值,无法用当前费率可靠重建。", + billingStoredFormulaUnavailable: "该记录仅保留最终计费结果,未保存可安全重建公式的完整计量明细。", billingZeroFormula: "本次可计费用量为 0,公式结果为 $0。", billingConclusion: "最终费用", billingComponents: { uncached_input: "输入", cached_input: "缓存", output: "输出", input_image: "输入图片", output_image: "输出图片", output_second: "视频输出" }, billingUnits: { token: "Token", image: "张", second: "秒" }, - pricingCoverage: "已计价 {{priced}} · 未计价 {{unpriced}}", - pricingDescription: "基于 xAI 官方模型最新价格计算,未收录价格的模型不计入费用。", + pricingCoverage: "已计费 {{priced}} · 未计费 {{unpriced}}", + pricingDescription: "基于 xAI 官方价格和可验证用量计费;缺少可靠计量依据的请求标记为未计费。", total: "总计", input: "输入", output: "输出", @@ -895,7 +941,7 @@ const resources = { console: { baseURLHelp: "Grok Console 请求与账号操作使用的基础端点。", chatTimeoutHelp: "Grok Console 聊天请求完成前允许等待的最长时间。", streamIdleTimeout: "流式空闲超时", streamIdleTimeoutHelp: "仅文本 SSE 连续无上游数据时允许等待的最长时间;不影响媒体和非流式请求。" }, batch: { title: "批量任务", importConcurrency: "导入同步并发", importConcurrencyHelp: "批量导入后并行执行账号初始化与信息同步的任务数。", conversionConcurrency: "账号转换并发", conversionConcurrencyHelp: "跨 Provider 转换账号时允许同时处理的任务数。", syncConcurrency: "数据同步并发", syncConcurrencyHelp: "批量同步账号额度、状态与能力时允许同时处理的任务数。", refreshConcurrency: "凭据刷新并发", refreshConcurrencyHelp: "批量刷新账号凭据时允许同时处理的任务数。", randomDelay: "随机延迟上限(ms)", randomDelayHelp: "批量任务启动前增加的随机延迟上限,用于平滑上游请求峰值。" }, media: { title: "媒体存储", maxImageSize: "单张图片上限", maxImageSizeHelp: "单个图片文件允许写入本地媒体存储的最大大小。", maxTotalSize: "媒体存储上限", maxTotalSizeHelp: "本地图片与视频文件允许占用的总存储空间。", cleanupThresholdPercent: "自动清理阈值", cleanupThresholdPercentHelp: "存储使用率达到该比例后,系统按时间清理较早的媒体文件。", cleanupInterval: "容量检查间隔", cleanupIntervalHelp: "后台检查媒体存储使用量并触发清理的时间间隔。", sizeUnit: "存储单位", publicApiBaseURL: "公共 API 地址", publicApiBaseURLHelp: "用于生成图片公开 URL 与文档示例地址。留空时回退到服务启动值,默认为 http://127.0.0.1:8000。" }, - egress: { title: "出口代理", description: "节点按 Grok Build、Grok Web、Grok Console 或 Web 资源独立管理代理和健康状态。Build 沿用 Provider 的 User-Agent;Web 与 Console 节点单独管理浏览器 User-Agent 和 Cookie。代理地址和 Cloudflare Cookie 仅写入。", add: "添加节点", saved: "代理节点已保存", deleted: "代理节点已删除", name: "名称", scope: "作用域", proxy: "代理", clearance: "Clearance", health: "健康度", directFallback: "未配置节点时使用直连", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web(仅资源)", configured: "已配置", direct: "直连", none: "无", editTitle: "编辑代理节点", addTitle: "添加代理节点", dialogDescription: "Build 节点只配置代理并沿用 Provider 的 User-Agent;Web 与 Console 节点使用各自的浏览器 User-Agent 和 Cloudflare Cookie。", enabled: "启用", proxyURL: "代理地址", proxyProtocols: "支持 HTTP、HTTPS、SOCKS4、SOCKS4A、SOCKS5、SOCKS5H\nResin 可在用户名中使用 {account} 绑定账号租约。", proxyPool: "代理池模式", proxyPoolHelp: "共享代理池的单次连接失败不会使整个出口节点进入冷却;包含 {account} 的代理会自动启用此策略。", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "已配置,留空保持不变", operationFailed: "操作失败", refreshClearance: "刷新 Clearance", clearanceRefreshed: "Clearance 已刷新", clearanceManaged: "Cloudflare Cookie 与 User-Agent 由 FlareSolverr 自动维护;Resin 等账号粘性代理会按账号隔离。", accounts: "已绑定", probe: "探测", healthy: "可用", unhealthy: "不可用", notTested: "未测试", test: "测试代理", testedOne: "代理测试完成", operations: "代理运营", automation: "自动任务", subscriptions: "代理订阅", testAll: "测试全部", rebalance: "立即调配", importText: "导入文本", addSource: "添加订阅", source: "订阅源", sync: "同步", capacity: "账号容量", noSources: "暂无订阅源", never: "从未", unlimited: "无限制", sourceSaved: "订阅源已保存", sourceDeleted: "订阅源已删除", sourceSynced: "订阅同步完成:导入 {{imported}},跳过 {{skipped}}", imported: "代理导入完成:导入 {{imported}},跳过 {{skipped}}", tested: "代理测试完成:可用 {{healthy}},不可用 {{unhealthy}}", rebalanced: "账号调配完成:新增 {{assigned}},均衡 {{rebalanced}},未分配 {{unplaced}}", automationSaved: "自动任务已保存", editSource: "编辑订阅", subscriptionURL: "订阅地址", sourceDialogDescription: "配置订阅来源、作用域、刷新周期和单节点账号容量。", importDialogDescription: "支持明文或 Base64 代理列表,每行一个 HTTP 或 SOCKS 地址。", probeInterval: "探测间隔(秒)", probeIntervalHelp: "后台重新测试已启用代理节点的间隔。", assignmentInterval: "调配间隔(秒)", assignmentIntervalHelp: "后台检查自动分配与节点容量的间隔。", autoAssign: "自动分配未绑定账号", autoAssignHelp: "将可调度且未绑定的账号分配到近期探测可用的节点。", autoBalance: "自动均衡自动绑定账号", autoBalanceHelp: "在健康节点之间调整自动绑定;手工绑定始终保持不变。", refreshInterval: "订阅刷新间隔(秒)", proxyList: "代理列表" }, + egress: { title: "出口代理", description: "节点按 Grok Build、Grok Web、Grok Console 或 Web 资源独立管理代理和健康状态。Build 沿用 Provider 的 User-Agent;Web 与 Console 节点单独管理浏览器 User-Agent 和 Cookie。代理地址和 Cloudflare Cookie 仅写入。", add: "添加节点", saved: "代理节点已保存", deleted: "代理节点已删除", name: "名称", scope: "作用域", proxy: "代理", clearance: "Clearance", health: "健康度", directFallback: "未配置节点时使用直连", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web(仅资源)", configured: "已配置", direct: "直连", none: "无", editTitle: "编辑代理节点", addTitle: "添加代理节点", dialogDescription: "Build 节点只配置代理并沿用 Provider 的 User-Agent;Web 与 Console 节点使用各自的浏览器 User-Agent 和 Cloudflare Cookie。", enabled: "启用", proxyURL: "代理地址", proxyProtocols: "支持 HTTP、HTTPS、SOCKS4/4A、SOCKS5/5H、Trojan、VLESS、Shadowsocks 和 VMess。\n隧道协议支持 TCP、WebSocket 与 TLS;Resin 可在用户名中使用 {account}。", proxyPool: "代理池模式", proxyPoolHelp: "共享代理池的单次连接失败不会使整个出口节点进入冷却;包含 {account} 的代理会自动启用此策略。", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "已配置,留空保持不变", operationFailed: "操作失败", refreshClearance: "刷新 Clearance", clearanceRefreshed: "Clearance 已刷新", clearanceManaged: "Cloudflare Cookie 与 User-Agent 由 FlareSolverr 自动维护;Resin 等账号粘性代理会按账号隔离。", accounts: "已绑定", probe: "探测", healthy: "可用", unhealthy: "不可用", notTested: "未测试", test: "测试代理", testedOne: "代理测试完成", operations: "代理运营", automation: "自动任务", subscriptions: "代理订阅", testAll: "测试全部", rebalance: "立即调配", importText: "导入文本", addSource: "添加订阅", source: "订阅源", sync: "同步", capacity: "账号容量", noSources: "暂无订阅源", never: "从未", unlimited: "无限制", sourceSaved: "订阅源已保存", sourceDeleted: "订阅源已删除", sourceSynced: "订阅同步完成:导入 {{imported}},跳过 {{skipped}}", imported: "代理导入完成:导入 {{imported}},跳过 {{skipped}}", tested: "代理测试完成:可用 {{healthy}},不可用 {{unhealthy}}", rebalanced: "账号调配完成:新增 {{assigned}},均衡 {{rebalanced}},未分配 {{unplaced}}", automationSaved: "自动任务已保存", editSource: "编辑订阅", subscriptionURL: "订阅地址", sourceDialogDescription: "配置订阅来源、作用域、刷新周期和单节点账号容量。", importDialogDescription: "支持明文或 Base64 代理列表,每行一个 HTTP、SOCKS、Trojan、VLESS、SS 或 VMess 地址。", probeInterval: "探测间隔(秒)", probeIntervalHelp: "后台重新测试已启用代理节点的间隔。", assignmentInterval: "调配间隔(秒)", assignmentIntervalHelp: "后台检查自动分配与节点容量的间隔。", autoAssign: "自动分配未绑定账号", autoAssignHelp: "将可调度且未绑定的账号分配到近期探测可用的节点。", autoBalance: "自动均衡自动绑定账号", autoBalanceHelp: "在健康节点之间调整自动绑定;手工绑定始终保持不变。", refreshInterval: "订阅刷新间隔(秒)", proxyList: "代理列表" }, routing: { title: "路由策略", stickyTTL: "会话粘性时长", stickyTTLHelp: "同一会话优先复用已选账号的有效时长;到期后重新参与调度。", cooldownBase: "基础冷却时间", cooldownBaseHelp: "账号发生可恢复故障后首次进入冷却的时长。", cooldownMax: "最大冷却时间", cooldownMaxHelp: "连续故障触发指数退避时允许达到的最长冷却时间。", capacityWait: "账号满载等待", capacityWaitHelp: "全部候选账号并发已满时,切换或失败前等待容量释放的时间。", maxAttempts: "最大尝试次数", maxAttemptsHelp: "单次请求在可用账号之间切换并重试的最大次数,范围为 1–200。", preferFreeBuild: "Grok Build Free 账号优先", preferFreeBuildHelp: "启用后优先选择已确认可用的 Free 账号,其他路由条件保持不变。", accountIsolatedConnections: "按账号隔离上游连接", accountIsolatedConnectionsHelp: "开启后,不同账号使用各自的上游 TCP/HTTP 连接池,便于外部 L4 或按连接哈希的负载均衡器分散流量;同一账号仍可复用连接。适用于 Build / Web / Console 出站及 Web 转 Build。会增加连接数、TLS 握手、内存和文件描述符占用,建议仅在确有外部连接级负载均衡需求时开启。" }, audit: { title: "请求审计", bufferSize: "队列容量", bufferSizeHelp: "审计记录进入持久化前可在内存队列中等待的最大数量。", batchSize: "批量写入数", batchSizeHelp: "每次数据库事务最多写入的审计记录数量。", flushInterval: "刷新间隔", flushIntervalHelp: "队列未达到批量写入数时,强制提交待处理审计记录的间隔。", commitDelay: "提交聚合等待(毫秒)", commitDelayHelp: "需要确认提交的请求进入原子批次前允许等待的最长时间。" }, clientKeys: { title: "密钥默认限制", rpmLimit: "默认 RPM", rpmLimitHelp: "新建客户端密钥默认允许的每分钟请求数。", maxConcurrent: "默认并发数", maxConcurrentHelp: "新建客户端密钥默认允许同时执行的请求数。" }, @@ -973,7 +1019,16 @@ const resources = { endpointImageEdit: "Grok Web 图片编辑,使用官方 JSON 图片 URL 协议。", endpointMediaImage: "读取已归档到本地媒体存储的不可变生成图片。", endpointVideoCreate: "按 xAI 官方协议创建异步视频生成任务并返回 request_id。", + endpointVideoEdit: "按 xAI 官方协议编辑已有视频,并返回 request_id。", + endpointVideoExtend: "按 xAI 官方协议延长已有视频,并返回 request_id。", endpointVideoGet: "按 request_id 查询 pending、done 或 failed 状态及生成结果。", + endpointTTS: "Console 文本转语音,返回音频二进制或带时间戳的 JSON 封装。", + endpointAudioSpeech: "OpenAI 兼容文本转语音接口,接受 input/voice/response_format 并返回音频字节。", + endpointAudioTasks: "OpenAI 风格音频任务兼容路径,默认返回音频字节。", + endpointAudioTranscriptions: "OpenAI 兼容语音转文字接口,复用现有 STT 能力。", + endpointTTSVoices: "列出 Console 当前可用的内置音色。", + endpointSTT: "Console 语音转文字,支持文件上传或音频 URL,可返回词级时间戳。", + endpointRealtime: "Realtime 语音 WebSocket,由网关代持 Console 账号完成上游鉴权与双向转发。", streaming: "流式响应", streamingDescription: "设置 stream: true 后,上游 SSE 数据会逐块写入并立即 Flush,不会等待完整响应后模拟输出。账号故障切换只发生在流开始前。", streamingProxyNote: "部署在 Nginx 或 CDN 后需关闭响应缓冲,否则应用层虽为真实流式,客户端仍可能批量收到事件。客户端断开会取消上游请求并释放并发租约。", @@ -1046,13 +1101,19 @@ const resources = { fieldImageCount: "需要返回的图片数量;网关会选择可满足数量的最小上游批次。", fieldAspectRatio: "输出媒体的宽高比,例如 1:1、2:3 或 16:9。", fieldResolution: "输出分辨率;图片支持 1k/2k,视频按模型能力校验。", + fieldQuality: "Image 2.0 的生成质量,可选 low 或 medium;默认 medium。", fieldResponseFormat: "图片返回格式,支持 url 或 b64_json。", fieldImageStream: "是否使用图片生成扩展 SSE 流;默认 false。", fieldEditImages: "待编辑图片,使用 image 或 images 传入 URL、Data URL 或已支持的图片引用。", fieldVideoPrompt: "视频描述;使用图片输入时可作为运动或镜头指令。", fieldDuration: "视频时长,按上游模型支持范围校验。", fieldVideoImage: "可选首帧图片引用,用于图生视频。", - fieldReferenceImages: "可选参考图片数组,用于支持的参考图视频任务。", + fieldVideoEditPrompt: "描述希望如何修改原视频。", + fieldVideoExtendPrompt: "描述视频接下来应发生的内容。", + fieldVideoInput: "输入视频,支持 url 或本地上传后的 file_id。", + fieldVideoExtendDuration: "延长片段时长,单位秒,范围 2 到 10,默认 6。", + fieldReferenceImages: "可选参考图片数组,用于参考图视频;每项提供 url 或 file_id,不可与 image 同时使用。", + fieldReferenceAudios: "可选参考音频数组,最多 3 个内置 voice_id;可单独使用或与 reference_images 组合。", fieldRequestId: "创建视频任务时返回的 request_id。", noteChatProviders: "Build、Web 与 Console 使用独立账号池和上游协议,但向客户端返回统一的 Chat Completions 结构。", noteChatImages: "对话图片会先完成校验与上传,再绑定到本次选择的账号;不会在流开始后切换账号。", @@ -1063,17 +1124,55 @@ const resources = { noteMessagesAuth: "Messages 使用 x-api-key,并携带 anthropic-version: 2023-06-01。", noteMessagesEvents: "流式响应输出 Anthropic Messages 事件,不混用 OpenAI SSE 事件名。", noteMessagesLimits: "仅适配当前聊天模型共有的 Messages 能力,Provider 不支持的扩展字段会被拒绝。", - noteImageModels: "grok-imagine-image-lite 与 grok-imagine-image-quality-lite 使用统一图片接口,模型决定上游生成链路与计费。", + noteImageModels: "Web 使用 grok-imagine-image-lite 与 grok-imagine-image-quality-lite 生成图片,并通过独立的 grok-imagine-image-edit 编辑图片;Console 的三个图片模型分别聚合展示生成与编辑能力。", noteImageCount: "客户端按 n 获取结果;网关可使用 4、8、12 张上游批次,并只返回请求数量。", noteImageStorage: "生成结果统一归档到媒体存储;url 返回网关资源地址,b64_json 返回编码后的图片内容。", noteEditJSON: "图片编辑采用 JSON 请求体,不提供 multipart 兼容层。", noteEditSources: "远程图片会经过 SSRF、防体积超限和内容类型校验后再上传到上游。", noteVideoAsync: "创建接口只返回 request_id;生成过程异步执行并持久化任务状态。", noteVideoDuration: "时长、比例、分辨率和图片输入按当前视频模型能力校验。", + noteVideoReference: "参考图视频走 /videos/generations + reference_images;不可与 image 同用,resolution 最高 720p;reference_audios 使用内置 voice_id。", noteVideoStrict: "视频接口严格使用当前官方字段,不保留旧项目的兼容别名。", + noteVideoEditModel: "视频编辑与延长的实际路由必须指向 Console/grok-imagine-video;对外模型名可以自定义。", + noteVideoBilling: "视频编辑与延长暂未返回可可靠结算的输入视频时长,因此保持可调用,并在请求审计中标记为未计费;不会消耗 API Key 的金额额度。", noteVideoPolling: "使用创建接口返回的 request_id 轮询任务状态。", noteVideoStatus: "响应状态为 pending、done 或 failed;完成后 video 中包含结果信息。", noteVideoBoundAccount: "媒体任务始终绑定创建它的账号,查询与资源读取不会换号拼接。", + fieldVoiceModel: "语音模型公开 ID,例如 grok-voice-latest 或 grok-voice-think-fast-2.0。", + fieldVoiceModelQuery: "可选模型查询参数,用于选择音色列表所对应的语音模型。", + fieldSTTModel: "转写模型公开 ID,通常为 grok-stt。", + fieldRealtimeModel: "Realtime 会话模型,例如 grok-voice-latest。", + fieldRealtimeModelQuery: "WebSocket 连接的 model 查询参数。", + fieldTTSText: "需要合成的文本内容。", + fieldAudioInput: "OpenAI 风格待合成文本,对应原生 text 字段。", + fieldAudioVoice: "OpenAI 音色名或 Console voice_id;常见 OpenAI 音色会自动映射。", + fieldAudioResponseFormat: "输出格式,如 mp3、opus、aac、flac、wav、pcm。", + fieldVoiceId: "音色 ID;可使用内置音色或自定义音色 voice_id。", + fieldVoiceLanguage: "语言代码,例如 en、zh;TTS 必填。", + fieldVoiceLanguageOptional: "语言代码,例如 en、zh;OpenAI 兼容接口未提供时默认 en。", + fieldTTSOutputFormat: "输出格式对象,可指定 codec、sample_rate、bit_rate。", + fieldTTSSpeed: "语速倍率;按上游支持范围校验。", + fieldTTSTimestamps: "为 true 时返回含 base64 音频与时间戳的 JSON,而不是原始音频流。", + fieldSTTFile: "multipart 上传的音频文件字段名 file。", + fieldSTTUrl: "可公开访问的音频 URL;与 file 二选一。", + fieldSTTResponseFormat: "响应格式:json(默认)、verbose_json 或 text;未实现的 srt/vtt 会明确拒绝。", + fieldSTTFormat: "是否返回格式化文本与词级时间戳。", + fieldSTTDiarize: "是否启用说话人分离。", + fieldSTTKeyterm: "提升识别优先级的关键词,可重复提交。", + fieldWSUpgrade: "必须携带标准 WebSocket Upgrade 头;普通 HTTP GET 会被拒绝。", + noteTTSModels: "Console 语音模型包括 grok-voice-latest、grok-voice-think-fast-2.0 与 grok-voice-think-fast-1.0。", + noteAudioSpeechCompat: "兼容 OpenAI /v1/audio/speech:input→text,voice→voice_id,response_format→codec;也可继续传 language 等扩展字段。", + noteAudioTasksCompat: "部分客户端使用 /v1/audio/tasks;本网关按 speech 同步处理,默认返回音频字节。", + noteAudioTranscriptionsCompat: "兼容 OpenAI /v1/audio/transcriptions,支持 json、verbose_json 与 text 响应,底层复用 /v1/stt;prompt、非零 temperature 和 timestamp_granularities 暂无法无损转换,将明确拒绝。", + noteTTSBinary: "默认响应为 audio/mpeg 等音频字节流;with_timestamps=true 时改为 JSON。", + noteTTSVoices: "GET /v1/tts/voices 返回内置音色;GET /v1/tts/voices/{voice_id} 可查询单个音色。", + noteVoiceBilling: "TTS 按输入字符数预留并结算;REST 与流式 STT 按成功响应返回的实际时长结算。Realtime 当前标记为未计费,不消耗 API Key 金额额度。", + noteSTTInput: "支持 multipart 文件上传或 JSON url 引用;至少提供其中一种音频输入。", + noteSTTStream: "对 /v1/stt 发起 WebSocket Upgrade 可进行实时转写,客户端发送音频帧并接收 JSON 事件。", + noteSTTModels: "转写模型使用 grok-stt;词级时间戳与说话人分离按请求参数返回。", + noteRealtimeProxy: "推荐通过本网关的 /v1/realtime WebSocket 代理连接,由 Console 账号完成上游 DPoP 鉴权。", + noteRealtimeEvents: "连接后按官方 Realtime 事件协议交换 session、音频缓冲与响应事件。", + noteRealtimeAuth: "服务端 WebSocket 客户端需在 Upgrade 请求中携带 Authorization Bearer 或 X-API-Key;网关不会向调用方暴露上游 Console 凭据。", }, }, errors: { @@ -1252,12 +1351,12 @@ const resources = { nav: { dashboard: "Dashboard", accounts: "Accounts", models: "Models", clientKeys: "Client keys", creativeConsole: "Creative console", gallery: "Gallery", videoGallery: "Video Gallery", audits: "Request audits", qualityGuard: "Quality guard", docs: "Documentation", settings: "Settings" }, creativeConsole: { title: "Creative console", - description: "Use an existing client key to test chat, image, and video generation directly.", + description: "Use an existing client key to test chat, image, video, and voice directly.", promotion: "Looking for a more complete AI creation experience? Try another project I built, {{product}}: a lightweight, ready-to-deploy Web Chat for multi-model conversations and image generation with a static runtime footprint of about 34 MB.", promotionAction: "Explore DEEIX Chat", clientKey: "Client key", selectKey: "Select a client key", - modes: { chat: "Chat", image: "Image", video: "Video" }, + modes: { chat: "Chat", image: "Image", video: "Video", voice: "Voice" }, welcome: "What would you like to create today?", welcomeImage: "Describe an idea and create an image", welcomeVideo: "Describe an idea and create a video", @@ -1280,6 +1379,29 @@ const resources = { chatPlaceholder: "Enter the message to send to the model.", imagePlaceholder: "Describe the scene, subject, style, and details to generate.", videoPlaceholder: "Describe the video scene, motion, camera, and pacing.", + videoEditPlaceholder: "Describe how the source video should change.", + videoExtendPlaceholder: "Describe what should happen next in the video.", + welcomeVideoEdit: "Provide a source video and start editing", + welcomeVideoExtend: "Provide a source video and start extending", + videoActions: { generate: "Generate", edit: "Edit", extend: "Extend" }, + sourceVideo: "Source video URL", + sourceVideoShort: "Source video", + sourceVideoAdded: "Source video added", + clearSourceVideo: "Remove source video", + editVideo: "Edit video", + extendVideo: "Extend video", + extendDuration: "Extend duration (seconds)", + voicePlaceholder: "Enter text to synthesize, or upload audio for transcription.", + welcomeVoice: "Choose a voice and start creating audio", + synthesizing: "Synthesizing speech…", + transcribing: "Transcribing speech…", + uploadAudio: "Upload audio", + clearAudio: "Clear audio", + synthesize: "Synthesize", + transcribe: "Transcribe", + voiceLanguage: "Language", + voiceId: "Voice", + voiceSpeed: "Speed", send: "Send", messageList: "Conversation messages", scrollToLatest: "Scroll to latest message", @@ -1305,16 +1427,25 @@ const resources = { count: "Count", aspectRatio: "Aspect ratio", resolution: "Resolution", + quality: "Quality", generateImage: "Generate image", generatingImage: "Generating images...", generatedImageAlt: "Generated image {{index}}", imageNumber: "Image {{index}}", open: "Open", + firstFrameImage: "First-frame image URL", + firstFrameImageShort: "First frame", + firstFrameImageAdded: "First frame added", + clearFirstFrameImage: "Remove first frame", referenceImage: "Reference image URL", - referenceImageShort: "Reference image", - referenceImageAdded: "Image added", + referenceImageShort: "Reference", + referenceImageAdded: "Reference added", clearReferenceImage: "Remove reference image", + referenceVoice: "Reference voice", + referenceVoiceShort: "Voice", + referenceVoiceNone: "No reference voice", uploadImage: "Upload local image", + uploadVideo: "Upload local video", duration: "Duration (seconds)", generateVideo: "Generate video", submittingVideo: "Submitting video job...", @@ -1330,6 +1461,10 @@ const resources = { noKeys: "No enabled client keys are available. Create or enable a key first.", noModels: "No model is available for this mode. Confirm that models are enabled and the account pool can serve them.", videoFailed: "Video generation failed", + noSourceVideo: "Enter a source video URL or upload a local video", + invalidImage: "Choose a valid image file", + invalidVideo: "Choose a valid MP4, WebM, or QuickTime video file", + noAudio: "Choose an audio file first", }, }, media: { images: { title: "Gallery", description: "Browse generated image assets", search: "Search ID, type, or hash", empty: "No images", noMatches: "No matching images", totalImages: "Total images", totalBytes: "Storage", pageSummary: "Showing {{count}} / {{total}}", openImage: "Open image {{id}}", deleteTitle: "Delete {{count}} selected images?", deleteDescription: "The image files and gallery records will be permanently removed, and existing image links will stop working. This cannot be undone.", deleted: "Deleted {{count}} images" }, videos: { title: "Video Gallery", description: "View video generation job records", search: "Search prompt or ID", empty: "No video jobs", statusFilter: "Status filter", totalJobs: "Total jobs", queued: "Queued", inProgress: "In progress", completed: "Completed", failed: "Failed", prompt: "Prompt", model: "Model", status: "Status", progress: "Progress", statusProgress: "Status / progress", spec: "Spec", owner: "Owner", createdAt: "Created", completedAt: "Completed", time: "Time", createdShort: "Created", completedShort: "Done", preview: "Preview video", previewTitle: "Video preview", previewUnavailable: "Local video unavailable", deleteTitle: "Delete {{count}} video records?", deleteDescription: "The task records and their local videos will be permanently removed, and existing video links will stop working. This cannot be undone.", deleted: "Deleted {{count}} video records", seconds: "{{count}} sec", pageSummary: "Showing {{count}} / {{total}}" }, videoStatus: { queued: "Queued", in_progress: "In progress", completed: "Completed", failed: "Failed" } }, @@ -1340,7 +1475,7 @@ const resources = { accountQuotaTask: { title: "Process quota for {{count}} selected accounts", description: "Choose the quota task to run for the selected Grok Build accounts.", allTitle: "Process quota for all accounts", allDescription: "Choose the quota task to run for all enabled Grok Build accounts.", syncDescription: "Request upstream Billing and update local quota snapshots, account tiers, and recovery state.", resetAllDescription: "Clear local waiting-reset and exhausted-quota blocks for all enabled Grok Build accounts without changing upstream Billing or audit history.", execute: "Run task" }, accountExport: { countDescription: "Exports accounts in stable order, up to 10,000 per batch.", batchProgress: "Exported {{count}} accounts; the next download is batch {{batch}}.", nextBatch: "Export next batch", batchCompleted: "Exported {{count}} accounts in this batch", completed: "Export complete: {{count}} accounts" }, dashboard: { title: "Dashboard", subtitle: "Welcome, {{name}}", lastUpdated: "Updated {{time}}", welcome: "Welcome, {{name}}", gatewayOnline: "Gateway healthy", gatewayOffline: "Unavailable", gatewayReady: "The gateway is ready to process API requests.", gatewayNeedsAccount: "Connect an available account to process API requests.", manageAccounts: "Manage accounts", usage: "Usage overview", seeAll: "View audits", activeAccounts: "Available accounts", accountCapacity: "{{total}} accounts · {{rate}}% success", manage: "Manage", tokens: "Total tokens", requests: "Requests", successRate: "Success rate", accountCount: "Accounts", accountDistribution: "Build {{build}} · Web {{web}} · Console {{console}}", requestSuccessRate: "{{rate}}% success", averageRequestCost: "{{cost}} per request", availableSummary: "{{active}} / {{total}} available", requestBreakdown: "{{success}} succeeded · {{failed}} failed", requestQualitySummary: "{{success}}% success · {{failed}} failed", periodSummary: "Current {{period}} range", successSummary: "{{success}} / {{total}} requests succeeded", trend: "Usage trend", trendRequests: "Requests", trendTokens: "Tokens", trendSummary: "{{requests}} requests · {{rate}}% success", resourcesTitle: "Resource availability", availability: "Account availability", unavailableAccounts: "Unavailable accounts", unavailableSummary: "{{unavailable}} / {{total}} unavailable", enabledModels: "Enabled models", modelsAvailableSummary: "{{enabled}} / {{total}} enabled", activeClientKeys: "Available keys", keysAvailableSummary: "{{active}} / {{total}} available", allTimeRequests: "All-time requests", allTimeRequestsSummary: "Since the first recorded request", qualityTitle: "Request quality", successfulRequests: "Successful requests", failedRequests: "Failed requests", topModels: "Top 10 model billing", model: "Model", share: "Call share", noTopModels: "No model calls in this period", noTrendData: "No usage data in this period", billing: "Billing", billingSummary: "Accumulated in the current {{period}} range", inputTokens: "Input", cachedTokens: "Cached", outputTokens: "Output", reasoningTokens: "Reasoning", uncachedInput: "Uncached input", visibleOutput: "Visible output", otherModels: "Other models", providerDistribution: "Provider distribution", providerDetail: "{{rate}}% success · {{tokens}} tokens", providerStripeDetail: "{{provider}} · {{requests}} requests · {{share}}%", providerNoRequests: "No provider requests", activityTitle: "Request activity", lastDays: "Last {{count}} days", activityDay: "{{date}} · {{requests}} requests", activityLess: "Less", activityMore: "More", tokenBreakdown: "Input {{input}} · Cached {{cached}} · Output {{output}} · Reasoning {{reasoning}}", tokenEfficiency: "Cache hit rate {{rate}}%", explore: "Manage resources", accountsProduct: "Upstream accounts", accountsProductDescription: "Manage OAuth credentials, health, quota, and concurrency.", keysProduct: "Client keys", keysProductDescription: "Create downstream API keys and control models, RPM, and concurrency.", modelsProduct: "Model routes", modelsProductDescription: "Manage public model IDs, upstream mappings, and availability.", auditsProduct: "Request audits", auditsProductDescription: "Inspect status, latency, and token usage records.", gatewayFooter: "A lightweight API gateway", learnMore: "View models", unknown: "Unknown" }, - accounts: { title: "Upstream accounts", description: "Manage separate Grok Build OAuth and Grok Web SSO pools, health, concurrency, and quotas.", add: "Connect account", connectAccount: "Connect account", convertToBuild: "Convert to Build", convertToBuildTitle: "Convert Grok Web accounts to Build?", convertToBuildDescription: "Choose the conversion scope for the selected {{count}} Web accounts. Conversion may take a moment.", convertingProgress: "Converting {{completed}} / {{total}}", syncingProgress: "Syncing {{completed}} / {{total}}", conversionCompleted: "Conversion complete: {{created}} created, {{linked}} linked, {{skipped}} skipped, {{failed}} failed", linkedAccountTooltip: "Linked account: {{name}}", syncAll: "Sync all", renewAll: "Renew all", syncAllTitle: "Sync all accounts?", syncAllDescription: "Refresh quota data for every enabled Grok Build account.", syncAllWebDescription: "Refresh real quota data for every enabled Grok Web account.", renewAllTitle: "Renew all accounts?", renewAllDescription: "Refresh every renewable Grok Build credential. Accounts without automatic renewal will be skipped.", search: "Search accounts", deviceLogin: "Device OAuth", importAuth: "Import account files", importSSO: "Import SSO JSON", quickImportSSO: "Quick import SSO", importWebFile: "Import account files", quickImportTitle: "Quick import Grok Web accounts", quickImportDescription: "Paste multiple SSO tokens or upload a TXT file with one token per line. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", uploadTXT: "Upload TXT", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export account file", exported: "Account credentials exported", exportTitle: "Export {{provider}} accounts?", exportDescription: "The JSON contains credentials for the current provider and any configured Cloudflare cookies, and can be imported back into this project. Store it only in a trusted location.", exportCount: "Export count", exportCountDescription: "Exports newest accounts first, up to 10,000 per batch.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", buildAccountCount: "Grok Build accounts", webAccountCount: "Grok Web accounts", consoleAccountCount: "Grok Console accounts", abnormalAccountCount: "Abnormal accounts", routableAccountCount: "{{count}} routable", abnormalAccountBreakdown: "Recovering {{recovering}} · Needs attention {{attention}}", riskAccountCount: "Risk {{count}}", riskFilter: "Risk", riskNormal: "Normal", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", updatedWithModelSyncFailure: "Account updated, but model capability sync failed. Run model sync again later.", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", botRisk: "Risk", botRiskTooltip: "Bot risk control.", botRiskTooltipSource1: "Bot risk control (bot_flag_source/bfs=1).", botRiskTooltipSource2: "Bot risk control (bot_flag_source/bfs=2).", nsfwEnabledMark: "NSFW", nsfwEnabledTooltip: "NSFW enabled · {{time}}", agreementFilter: "Account agreements", agreementNsfwEnabled: "NSFW enabled", agreementNsfwDisabled: "NSFW not enabled", agreementTermsAccepted: "Terms accepted", agreementTermsNotAccepted: "Terms not accepted", agreementAllAccepted: "All accepted", agreementAllNotAccepted: "All not accepted", associationFilter: "Account links", associationWebLinked: "Web linked", associationWebUnlinked: "Web not linked", associationBuildLinked: "Build linked", associationBuildUnlinked: "Build not linked", associationConsoleLinked: "Console linked", associationConsoleUnlinked: "Console not linked", associationAllLinked: "All linked", associationAllUnlinked: "All not linked", buildRouteMode: { label: "Upstream endpoint", auto: "Automatic", build: "Build", xai: "XAI", autoDescription: "Selects an upstream based on account tier and risk status.", buildDescription: "Routes all requests to Build with XAI fallback disabled.", xaiDescription: "Routes all inference and video requests to XAI.", xaiUnconfirmedWarning: "This account has not been confirmed for XAI access; the upstream may reject requests." }, buildSuperEntitled: { label: "Mark as Super manually", description: "Use only when automatic tier detection is inaccurate. Enabled accounts sync models with Super access." }, quotaFree: "Free", quotaSuper: "Super", quotaPaid: "Super", quotaUnknown: "Unknown", paidQuotaUsage: "Upstream quota usage", weeklyQuota: "Weekly", monthlyQuota: "Monthly", weeklyLimit: "Weekly limit {{percent}}% remaining", freeObservedUsage: "{{used}} tokens observed in the last 24 hours", freeEstimatedUsage: "About {{used}} / {{limit}} tokens", freeEstimatedDescription: "Estimated from observed Grok Build Free characteristics; upstream exhaustion data takes precedence", observedRolling: "Free accounts use this proxy's rolling observation and may differ from upstream billing data", upstreamConfirmed: "Exhaustion confirmed by upstream", waitingReset: "Waiting reset", waitingResetUntil: "Waiting for reset · probe after {{time}} on real traffic", paidWaitingResetUntil: "Waiting for reset · check the upstream Billing period after {{time}}", probing: "Probing", probingQuota: "Checking quota recovery with real traffic", paidProbingQuota: "Checking whether the upstream Billing period has recovered", upstreamBilling: "Upstream billing data", deviceTitle: "Connect Grok Build", deviceDescription: "Complete authorization in a new window. This page will check status automatically.", userCode: "Device code", openVerification: "Continue to authorization", waiting: "Waiting for authorization", expiresAt: "Expires {{time}}", deleteTitle: "Delete account?", deleteDescription: "Credentials and quota snapshots will be removed. This cannot be undone.", deleteConfirm: "Delete", linkedDeleteTitle: "Also delete linked accounts?", linkedDeleteSelectAll: "Select all linked", linkedDeleteClearAll: "Clear linked selection", linkedDeleteExtra: "+{{count}}", linkedDeleteExtraPending: "+—", linkedDeleteExtraFailed: "!", linkedDeleteHint: "Only linked accounts are deleted; unlinked accounts remain unchanged.", linkedDeletePreviewFailed: "Failed to load linked counts. Uncheck and retry, or delete later.", batchUpdated: "Selected accounts updated", batchSetConcurrency: "Set concurrency", batchConcurrencyTitle: "Set concurrency for {{count}} selected accounts?", batchConcurrencyDescription: "Sets the number of simultaneous requests per account from 1 to 256. Large pools can start at 1 to reduce per-account pressure.", batchConcurrencyUpdated: "Concurrency updated for selected accounts", batchBillingRefreshed: "Quota sync complete: {{succeeded}} succeeded, {{failed}} failed", batchDeleteTitle: "Delete {{count}} selected accounts?", cleanupAction: "Clean up accounts", cleanupTitle: "Clean up {{provider}} accounts", cleanupDescription: "Delete accounts in the selected states from this provider, including their quota data. Normal accounts are never affected. This cannot be undone.", cleanupCompleted: "Deleted {{deleted}} accounts", deletedWithSkipped: "Deleted {{deleted}} accounts, skipped {{skipped}} groups with active video jobs", cleanupCompletedDetailed: "Deleted {{deleted}} accounts ({{linked}} linked), skipped {{skipped}} groups", cleanupLinkedWarning: "Warning: linked accounts are not limited to the selected states and may include healthy accounts; they will be deleted too.", cleanupPreviewFailed: "Failed to load estimated counts. Adjust selection and retry, or clean up later.", cleanupPreviewTotal: "About {{total}} accounts will be deleted", cleanupStart: "Start cleanup" }, + accounts: { title: "Upstream accounts", description: "Manage separate Grok Build OAuth and Grok Web SSO pools, health, concurrency, and quotas.", add: "Connect account", connectAccount: "Connect account", convertToBuild: "Convert to Build", convertToBuildTitle: "Convert Grok Web accounts to Build?", convertToBuildDescription: "Choose the conversion scope for the selected {{count}} Web accounts. Conversion may take a moment.", convertingProgress: "Converting {{completed}} / {{total}}", syncingProgress: "Syncing {{completed}} / {{total}}", conversionCompleted: "Conversion complete: {{created}} created, {{linked}} linked, {{skipped}} skipped, {{failed}} failed", linkedAccountTooltip: "Linked account: {{name}}", syncAll: "Sync all", renewAll: "Renew all", syncAllTitle: "Sync all accounts?", syncAllDescription: "Refresh quota data for every enabled Grok Build account.", syncAllWebDescription: "Refresh real quota data for every enabled Grok Web account.", renewAllTitle: "Renew all accounts?", renewAllDescription: "Refresh every renewable Grok Build credential. Accounts without automatic renewal will be skipped.", search: "Search accounts", deviceLogin: "Device OAuth", importAuth: "Import account files", importSSO: "Import SSO JSON", quickImportSSO: "Quick import SSO", importWebFile: "Import account files", quickImportTitle: "Quick import Grok Web accounts", quickImportDescription: "Paste multiple SSO tokens or upload a TXT file with one token per line. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", uploadTXT: "Upload TXT", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export account file", exported: "Account credentials exported", exportTitle: "Export {{provider}} accounts?", exportDescription: "The JSON contains credentials for the current provider and any configured Cloudflare cookies, and can be imported back into this project. Store it only in a trusted location.", exportCount: "Export count", exportCountDescription: "Exports newest accounts first, up to 10,000 per batch.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", buildAccountCount: "Grok Build accounts", webAccountCount: "Grok Web accounts", consoleAccountCount: "Grok Console accounts", abnormalAccountCount: "Abnormal accounts", routableAccountCount: "{{count}} routable", abnormalAccountBreakdown: "Recovering {{recovering}} · Needs attention {{attention}}", riskAccountCount: "Risk {{count}}", riskFilter: "Risk", riskNormal: "Normal", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", imagineQuota: "Imagine quota", imagineQuotaRemaining: "{{remaining}} remaining", imagineQuotaExhausted: "Exhausted, cooling down", imagineModeImagePro: "Image", imagineModeImageEdit: "Image edit", imagineModeVideo: "Video", imagineModeVideo720p: "Video 720p", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", updatedWithModelSyncFailure: "Account updated, but model capability sync failed. Run model sync again later.", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", botRisk: "Risk", botRiskTooltip: "Bot risk control.", botRiskTooltipSource1: "Bot risk control (bot_flag_source/bfs=1).", botRiskTooltipSource2: "Bot risk control (bot_flag_source/bfs=2).", nsfwEnabledMark: "NSFW", nsfwEnabledTooltip: "NSFW enabled · {{time}}", agreementFilter: "Account agreements", agreementNsfwEnabled: "NSFW enabled", agreementNsfwDisabled: "NSFW not enabled", agreementTermsAccepted: "Terms accepted", agreementTermsNotAccepted: "Terms not accepted", agreementAllAccepted: "All accepted", agreementAllNotAccepted: "All not accepted", associationFilter: "Account links", associationWebLinked: "Web linked", associationWebUnlinked: "Web not linked", associationBuildLinked: "Build linked", associationBuildUnlinked: "Build not linked", associationConsoleLinked: "Console linked", associationConsoleUnlinked: "Console not linked", associationAllLinked: "All linked", associationAllUnlinked: "All not linked", buildRouteMode: { label: "Upstream endpoint", auto: "Automatic", build: "Build", xai: "XAI", autoDescription: "Selects an upstream based on account tier and risk status.", buildDescription: "Routes all requests to Build with XAI fallback disabled.", xaiDescription: "Routes all inference and video requests to XAI.", xaiUnconfirmedWarning: "This account has not been confirmed for XAI access; the upstream may reject requests." }, buildSuperEntitled: { label: "Mark as Super manually", description: "Use only when automatic tier detection is inaccurate. Enabled accounts sync models with Super access." }, quotaFree: "Free", quotaSuper: "Super", quotaPaid: "Super", quotaUnknown: "Unknown", paidQuotaUsage: "Upstream quota usage", weeklyQuota: "Weekly", monthlyQuota: "Monthly", weeklyLimit: "Weekly limit {{percent}}% remaining", freeObservedUsage: "{{used}} tokens observed in the last 24 hours", freeEstimatedUsage: "About {{used}} / {{limit}} tokens", freeEstimatedDescription: "Estimated from observed Grok Build Free characteristics; upstream exhaustion data takes precedence", observedRolling: "Free accounts use this proxy's rolling observation and may differ from upstream billing data", upstreamConfirmed: "Exhaustion confirmed by upstream", waitingReset: "Waiting reset", waitingResetUntil: "Waiting for reset · probe after {{time}} on real traffic", paidWaitingResetUntil: "Waiting for reset · check the upstream Billing period after {{time}}", probing: "Probing", probingQuota: "Checking quota recovery with real traffic", paidProbingQuota: "Checking whether the upstream Billing period has recovered", upstreamBilling: "Upstream billing data", deviceTitle: "Connect Grok Build", deviceDescription: "Complete authorization in a new window. This page will check status automatically.", userCode: "Device code", openVerification: "Continue to authorization", waiting: "Waiting for authorization", expiresAt: "Expires {{time}}", deleteTitle: "Delete account?", deleteDescription: "Credentials and quota snapshots will be removed. This cannot be undone.", deleteConfirm: "Delete", linkedDeleteTitle: "Also delete linked accounts?", linkedDeleteSelectAll: "Select all linked", linkedDeleteClearAll: "Clear linked selection", linkedDeleteExtra: "+{{count}}", linkedDeleteExtraPending: "+—", linkedDeleteExtraFailed: "!", linkedDeleteHint: "Only linked accounts are deleted; unlinked accounts remain unchanged.", linkedDeletePreviewFailed: "Failed to load linked counts. Uncheck and retry, or delete later.", batchUpdated: "Selected accounts updated", batchSetConcurrency: "Set concurrency", batchConcurrencyTitle: "Set concurrency for {{count}} selected accounts?", batchConcurrencyDescription: "Sets the number of simultaneous requests per account from 1 to 256. Large pools can start at 1 to reduce per-account pressure.", batchConcurrencyUpdated: "Concurrency updated for selected accounts", batchBillingRefreshed: "Quota sync complete: {{succeeded}} succeeded, {{failed}} failed", batchDeleteTitle: "Delete {{count}} selected accounts?", cleanupAction: "Clean up accounts", cleanupTitle: "Clean up {{provider}} accounts", cleanupDescription: "Delete accounts in the selected states from this provider, including their quota data. Normal accounts are never affected. This cannot be undone.", cleanupCompleted: "Deleted {{deleted}} accounts", deletedWithSkipped: "Deleted {{deleted}} accounts, skipped {{skipped}} groups with active video jobs", cleanupCompletedDetailed: "Deleted {{deleted}} accounts ({{linked}} linked), skipped {{skipped}} groups", cleanupLinkedWarning: "Warning: linked accounts are not limited to the selected states and may include healthy accounts; they will be deleted too.", cleanupPreviewFailed: "Failed to load estimated counts. Adjust selection and retry, or clean up later.", cleanupPreviewTotal: "About {{total}} accounts will be deleted", cleanupStart: "Start cleanup" }, models: { title: "Model routes", description: "Configure multiple independent upstream targets for one client-facing model name. Requests remain session-sticky across schedulable targets and avoid unavailable targets automatically. Multiple public names may also target the same upstream model.", sync: "Sync models", search: "Search models", model: "Public model name", publicId: "Public model name", upstream: "Upstream model", provider: "Model source", providerGrokBuild: "Grok Build", providerGrokWeb: "Grok Web", accountSupport: "Supported accounts", lastSyncedAt: "Last synced", capability: "Account model capabilities", supportSummary: "{{supported}} available / {{total}} total", awaitingCapabilitySync: "Awaiting model capability sync", unknownCapability: "Pending sync", partialCapability: "Awaiting remaining accounts", available: "Available", unavailable: "Unavailable", status: "Status", create: "Add model", createTitle: "Add model route", createDescription: "Add a Grok Build route target. Public names are customizable and may be duplicated; targets with the same name form a scheduling pool. Public names omit the source prefix, while upstream models use Build/.", editTitle: "Edit model route", bindAccounts: "Bind specific accounts", boundAccounts: "Bound accounts", bindAccountsDescription: "Route only through selected accounts; when disabled, use synchronized model capabilities.", enabledDescription: "Controls whether this route participates in model discovery and request scheduling.", searchAccounts: "Search account name or ID", selectedAccounts: "{{count}} accounts selected", selectAccountRequired: "Select at least one account", noBindableAccounts: "No accounts from this provider can be bound", deleteTitle: "Delete model route?", deleteDescription: "This removes {{name}} and its client-key permissions. A later sync recreates it if upstream accounts still support the model.", batchDeleteTitle: "Delete {{count}} selected model routes?", batchDeleteDescription: "This removes the selected routes and their client-key permissions. Models still supported by upstream accounts are recreated on a later sync.", synced: "Synced {{count}} models", created: "Model route created", updated: "Model route updated", deleted: "Model route deleted", batchDeleted: "Deleted {{count}} model routes", batchUpdated: "Selected models updated" }, keys: { title: "Client keys", description: "Control downstream model access, RPM, concurrency, billed usage, and expiration.", search: "Search keys", create: "Create key", name: "Name", prefix: "Key", limits: "Limits", rpmLimit: "RPM limit", concurrencyLimit: "Concurrency limit", rpmShort: "RPM", concurrencyShort: "Concurrency", billingLimit: "Usage limit", models: "Allowed models", status: "Status", statusActive: "Active", statusExpired: "Expired", modelScope: "Model scope", restrictedModels: "Selected models", expires: "Expires", lastUsed: "Last used", rpm: "Requests per minute", maxConcurrent: "Max concurrency", accountScope: "Routing scope", providerScope: "Provider scope", tierScope: "Subscription scope", allProviders: "All providers", allTiers: "All subscriptions", allTiersIncludingUnknown: "All, including unknown", accountScopeDescription: "The model list follows the provider and subscription scope, and routing never falls back outside it. All subscriptions include unknown accounts; Free + Super excludes unknown accounts. Console ignores subscription restrictions.", rpmValue: "{{value}} RPM", concurrentValue: "{{value}} concurrent", unlimited: "Unlimited", billedUsage: "{{value}} billed", billingLimitDescription: "Accumulates billed request audits, preferring upstream-reported cost and otherwise using the official price estimate.", enabledDescription: "Controls whether this key can make API requests.", modelAliases: "Model aliases", modelAliasesDescription: "Suffix aliases are generated only for available models with multiple supported reasoning levels.", modelAliasesBuildSupport: "Grok Build: grok-4.5, grok-3-mini, and grok-3-mini-fast support low / medium / high.", modelAliasesConsoleSupport: "Grok Console: grok-4.3 supports none / low / medium / high; grok-4.20-0309-reasoning uses fixed reasoning and does not accept effort controls; grok-4.20-multi-agent-0309 also supports xhigh.", modelAliasesUnsupported: "Grok Web, image models, and video models do not generate reasoning-effort suffixes.", modelAliasesOn: "On: discover and call the reasoning aliases supported by available models.", modelAliasesOff: "Off: dynamic reasoning aliases are disabled; existing Console compatibility aliases remain available.", allModels: "All models", modelSearch: "Search models", selectedModels: "{{count}} models selected", selectModelRequired: "Select at least one model, or switch to All models.", modelsClearedForScopeChange: "The routing scope changed. Select the allowed models again.", neverExpires: "Never expires", selectExpiry: "Select expiration date", clearExpiry: "Clear expiration", expiryTime: "Expiration time", createTitle: "Create client key", editTitle: "Edit client key", secretTitle: "Client key created", secretDescription: "Store this key securely.", secretLabel: "Key", copySecret: "Copy", copySecretTitle: "Copy key", copySecretDescription: "Use the button below to copy your key.", secretReady: "Ready", created: "Client key created", updated: "Client key updated", deleted: "Client key deleted", deleteTitle: "Delete client key?", deleteDescription: "All downstream requests using this key will stop immediately.", batchUpdated: "Selected keys updated", batchDeleteTitle: "Delete {{count}} selected keys?" }, audits: { @@ -1388,7 +1523,7 @@ const resources = { statusServerError: "Server error", statusOtherError: "Other error", errorLabel: "Error", - operations: { responses: "Responses", compaction: "Context compaction", chat: "Chat", messages: "Messages", image: "Image generation", image_edit: "Image edit", video: "Video generation" }, + operations: { responses: "Responses", compaction: "Context compaction", chat: "Chat", messages: "Messages", image: "Image generation", image_edit: "Image edit", video: "Video generation", tts: "Text to speech", stt: "Speech to text", realtime: "Realtime voice", voice: "Voice" }, compactionUsageUnavailable: "Upstream usage unavailable", usageSummary: "Usage summary", totalRequests: "Total requests", @@ -1399,6 +1534,7 @@ const resources = { successRate: "Success rate", averageDuration: "Average duration {{duration}}", estimatedCost: "Estimated cost", + unbilled: "Unbilled", exactBilling: "Full value", billingSource: "Billing source", billingSourceUpstream: "Upstream-reported cost", @@ -1409,13 +1545,13 @@ const resources = { billingLongContextTier: "Long context", billingFormula: "Formula", billingUpstreamFormula: "The upstream returned the final cost directly; no local rate estimate was applied.", - billingStoredFormulaUnavailable: "This record uses a historical or unknown rate version. Its final estimate is retained, but the formula cannot be reconstructed reliably with current rates.", + billingStoredFormulaUnavailable: "Only the final billed amount is retained; the complete metering details required to reconstruct the formula were not stored.", billingZeroFormula: "Billable usage is 0, so the formula result is $0.", billingConclusion: "Final cost", billingComponents: { uncached_input: "Input", cached_input: "Cache", output: "Output", input_image: "Input images", output_image: "Output images", output_second: "Video output" }, billingUnits: { token: "token", image: "image", second: "second" }, - pricingCoverage: "{{priced}} priced · {{unpriced}} unpriced", - pricingDescription: "Calculated using the latest official xAI model prices. Models without a listed price are excluded.", + pricingCoverage: "{{priced}} billed · {{unpriced}} unbilled", + pricingDescription: "Billing uses official xAI prices and verifiable usage. Requests without a reliable metering basis are marked unbilled.", total: "Total", input: "Input", output: "Output", @@ -1513,7 +1649,16 @@ const resources = { endpointImageEdit: "Edit Grok Web images with the official JSON image URL protocol.", endpointMediaImage: "Read an immutable generated image archived in local media storage.", endpointVideoCreate: "Create an asynchronous video generation request using the official xAI protocol.", + endpointVideoEdit: "Edit an existing video using the official xAI protocol and return a request_id.", + endpointVideoExtend: "Extend an existing video using the official xAI protocol and return a request_id.", endpointVideoGet: "Poll pending, done, or failed status and the generated video by request_id.", + endpointTTS: "Console text-to-speech that returns raw audio bytes or a timestamped JSON envelope.", + endpointAudioSpeech: "OpenAI-compatible text-to-speech endpoint that accepts input/voice/response_format and returns audio bytes.", + endpointAudioTasks: "OpenAI-style audio task compatibility path that returns audio bytes by default.", + endpointAudioTranscriptions: "OpenAI-compatible speech-to-text endpoint backed by the existing STT pipeline.", + endpointTTSVoices: "List the built-in voices currently available from Console.", + endpointSTT: "Console speech-to-text for uploaded files or audio URLs, with optional word timestamps.", + endpointRealtime: "Realtime voice WebSocket proxied by the gateway with Console account authentication.", streaming: "Streaming", streamingDescription: "With stream: true, upstream SSE chunks are written and flushed immediately instead of buffering a complete response and simulating output. Account failover occurs only before streaming begins.", streamingProxyNote: "Disable response buffering in Nginx or your CDN; otherwise a genuinely streaming application may still deliver events in batches. Client disconnects cancel the upstream request and release concurrency leases.", @@ -1586,13 +1731,19 @@ const resources = { fieldImageCount: "Number of images to return. The gateway selects the smallest upstream batch that can satisfy it.", fieldAspectRatio: "Output aspect ratio such as 1:1, 2:3, or 16:9.", fieldResolution: "Output resolution. Images support 1k/2k; video values are validated by model capability.", + fieldQuality: "Generation quality for Image 2.0: low or medium. Defaults to medium.", fieldResponseFormat: "Image response format: url or b64_json.", fieldImageStream: "Enable the image-generation SSE extension. Defaults to false.", fieldEditImages: "Source image or images supplied as URLs, data URLs, or another supported image reference.", fieldVideoPrompt: "Video description, or motion and camera instructions when an image is supplied.", fieldDuration: "Video duration validated against the upstream model's supported range.", fieldVideoImage: "Optional first-frame image reference for image-to-video generation.", - fieldReferenceImages: "Optional reference image array for supported reference-video tasks.", + fieldVideoEditPrompt: "Describe how the source video should change.", + fieldVideoExtendPrompt: "Describe what should happen next in the video.", + fieldVideoInput: "Source video input. Provide either url or an uploaded file_id.", + fieldVideoExtendDuration: "Extension length in seconds. Allowed range is 2 to 10; defaults to 6.", + fieldReferenceImages: "Optional reference image array for reference-to-video. Each item uses url or file_id and cannot be combined with image.", + fieldReferenceAudios: "Optional reference audio array of up to 3 built-in voice_id values. Can be used alone or with reference_images.", fieldRequestId: "The request_id returned when the video job is created.", noteChatProviders: "Build, Web, and Console use separate account pools and upstream protocols while returning the same Chat Completions shape.", noteChatImages: "Conversation images are validated and uploaded before being bound to the selected account. Accounts never switch after streaming begins.", @@ -1603,17 +1754,55 @@ const resources = { noteMessagesAuth: "Messages uses x-api-key with anthropic-version: 2023-06-01.", noteMessagesEvents: "Streaming emits Anthropic Messages events rather than OpenAI SSE event names.", noteMessagesLimits: "Only the common Messages capabilities of the current chat models are adapted; unsupported provider extensions are rejected.", - noteImageModels: "grok-imagine-image-lite and grok-imagine-image-quality-lite share this endpoint; the model selects the upstream path and pricing.", + noteImageModels: "Web generates images with grok-imagine-image-lite and grok-imagine-image-quality-lite, and edits them through the separate grok-imagine-image-edit model. Each of the three Console image models groups generation and edit capabilities.", noteImageCount: "Clients receive exactly n results. The gateway may use an upstream batch of 4, 8, or 12 and trim the response.", noteImageStorage: "Generated images are archived in media storage. url returns a gateway asset URL; b64_json returns encoded image data.", noteEditJSON: "Image edits use a JSON request body and do not provide a multipart compatibility layer.", noteEditSources: "Remote images pass SSRF, size, and content-type checks before upload to the upstream service.", noteVideoAsync: "Creation returns only request_id. Generation runs asynchronously with persistent job state.", noteVideoDuration: "Duration, aspect ratio, resolution, and image inputs are validated against the selected video model.", + noteVideoReference: "Reference-to-video uses /videos/generations with reference_images. Do not combine with image; resolution tops out at 720p. reference_audios accepts built-in voice_id values.", noteVideoStrict: "Video endpoints use the current official fields without non-standard aliases.", + noteVideoEditModel: "The resolved route for video edits and extensions must target Console/grok-imagine-video; the public model name may be customized.", + noteVideoBilling: "Video edits and extensions do not yet expose a reliably billable input-video duration. They remain callable, are audited as unpriced, and do not consume the API key spend limit.", noteVideoPolling: "Poll the job with the request_id returned by the creation endpoint.", noteVideoStatus: "Status is pending, done, or failed. Completed responses include result details in video.", noteVideoBoundAccount: "Media jobs remain bound to their creating account; status and asset reads never splice across accounts.", + fieldVoiceModel: "Public voice model ID such as grok-voice-latest or grok-voice-think-fast-2.0.", + fieldVoiceModelQuery: "Optional model query parameter used when listing voices for a voice model.", + fieldSTTModel: "Public transcription model ID, usually grok-stt.", + fieldRealtimeModel: "Realtime session model such as grok-voice-latest.", + fieldRealtimeModelQuery: "model query parameter for the WebSocket connection.", + fieldTTSText: "Text content to synthesize.", + fieldAudioInput: "OpenAI-style text to synthesize. Maps to the native text field.", + fieldAudioVoice: "OpenAI voice name or a Console voice_id. Common OpenAI voices are mapped automatically.", + fieldAudioResponseFormat: "Output format such as mp3, opus, aac, flac, wav, or pcm.", + fieldVoiceId: "Voice ID from built-in voices or a custom voice_id.", + fieldVoiceLanguage: "Language code such as en or zh. Required for TTS.", + fieldVoiceLanguageOptional: "Language code such as en or zh. OpenAI-compatible endpoints default to en when omitted.", + fieldTTSOutputFormat: "Output format object with optional codec, sample_rate, and bit_rate.", + fieldTTSSpeed: "Speech rate multiplier validated against upstream limits.", + fieldTTSTimestamps: "When true, return a JSON envelope with base64 audio and timestamps instead of raw audio.", + fieldSTTFile: "Multipart audio upload field named file.", + fieldSTTUrl: "Publicly reachable audio URL. Provide either file or url.", + fieldSTTResponseFormat: "Response format: json (default), verbose_json, or text. Unsupported srt/vtt formats are rejected explicitly.", + fieldSTTFormat: "Whether to return formatted text and word-level timestamps.", + fieldSTTDiarize: "Enable speaker diarization.", + fieldSTTKeyterm: "Priority keywords; the field may be repeated.", + fieldWSUpgrade: "Requires a standard WebSocket Upgrade header. Plain HTTP GET is rejected.", + noteTTSModels: "Console voice models include grok-voice-latest, grok-voice-think-fast-2.0, and grok-voice-think-fast-1.0.", + noteAudioSpeechCompat: "Compatible with OpenAI /v1/audio/speech: input→text, voice→voice_id, response_format→codec. Extra fields such as language remain accepted.", + noteAudioTasksCompat: "Some clients call /v1/audio/tasks. This gateway handles it synchronously like speech and returns audio bytes by default.", + noteAudioTranscriptionsCompat: "Compatible with OpenAI /v1/audio/transcriptions with json, verbose_json, and text responses, backed by /v1/stt. prompt, non-zero temperature, and timestamp_granularities are rejected because Console STT cannot preserve their semantics.", + noteTTSBinary: "Default responses are raw audio bytes such as audio/mpeg. with_timestamps=true switches to JSON.", + noteTTSVoices: "GET /v1/tts/voices lists built-in voices; GET /v1/tts/voices/{voice_id} returns one voice.", + noteVoiceBilling: "TTS is reserved and settled by input characters. REST and streaming STT are settled from the actual duration returned on success. Realtime is currently unbilled and does not consume the API key spend limit.", + noteSTTInput: "Accepts multipart file uploads or a JSON url reference; at least one audio input is required.", + noteSTTStream: "Upgrade /v1/stt to a WebSocket for realtime transcription; clients stream audio frames and receive JSON events.", + noteSTTModels: "Transcription uses grok-stt. Word timestamps and diarization follow the request parameters.", + noteRealtimeProxy: "Prefer the gateway /v1/realtime WebSocket proxy so Console DPoP authentication stays server-side.", + noteRealtimeEvents: "After connect, exchange official Realtime events for session setup, audio buffers, and responses.", + noteRealtimeAuth: "Server-side WebSocket clients must send Authorization Bearer or X-API-Key with the Upgrade request; the gateway never exposes upstream Console credentials.", }, }, quotaProducts: { thirdParty: "Third Party", api: "API", build: "Grok Build", plugins: "Grok Plugins", chat: "Chat", imagine: "Imagine", voice: "Voice", unknown: "Product {{code}}" }, @@ -1696,6 +1885,9 @@ Object.assign(resources["zh-CN"].translation.models as unknown as Record, { description: "节点按 Grok Build、Grok Web、Grok Console、Web 资源和 Console 资源独立管理代理与健康状态。Console 资源节点仅使用代理与 User-Agent,不发送账号或 Cloudflare Cookie。代理地址和 Cookie 仅写入。", dialogDescription: "配置节点作用域、代理地址和浏览器身份;Console 资源节点用于匿名媒体下载,不使用 Clearance Cookie。", + proxyProtocols: "支持 HTTP、HTTPS、SOCKS4/4A、SOCKS5/5H、Trojan、VLESS、Shadowsocks 和 VMess。\n隧道协议支持 TCP、WebSocket 与 TLS;Resin 可在用户名中使用 {account}。", scopeConsoleAsset: "Grok Console(仅资源)", health: "请求健康", healthHelp: "由真实 Grok 请求的成功、连接失败和反爬拒绝累计得出,与连通探测独立。", @@ -1737,6 +1933,7 @@ Object.assign(resources["zh-CN"].translation.settings.egress as unknown as Recor Object.assign(resources.en.translation.settings.egress as unknown as Record, { description: "Nodes manage proxy and health independently for Grok Build, Grok Web, Grok Console, Web assets, and Console assets. Console asset nodes use only the proxy and User-Agent and never send account or Cloudflare cookies. Proxy URLs and cookies are write-only.", dialogDescription: "Configure the node scope, proxy address, and browser identity. Console asset nodes are for anonymous media downloads and do not use clearance cookies.", + proxyProtocols: "Supports HTTP, HTTPS, SOCKS4/4A, SOCKS5/5H, Trojan, VLESS, Shadowsocks, and VMess.\nTunnel protocols support TCP, WebSocket, and TLS; Resin users can put {account} in the username.", scopeConsoleAsset: "Grok Console (assets only)", accounts: "Bound", health: "Request health", healthHelp: "Accumulated from real Grok request successes, transport failures, and anti-bot rejections; independent of the connectivity probe.", addManually: "Form entry", @@ -1753,8 +1950,9 @@ Object.assign(resources.en.translation.settings.egress as unknown as Record, { @@ -1816,7 +2008,12 @@ Object.assign(resources["zh-CN"].translation.settings.egress as unknown as Recor sourceDeleted: "代理订阅已删除", sourceSynced: "代理订阅同步完成:导入 {{imported}},跳过 {{skipped}}", editSource: "编辑订阅", - sourceDialogDescription: "配置订阅地址、作用域、同步间隔和单节点账号容量。", + sourceDialogDescription: "配置订阅地址、拉取线路、作用域、同步间隔和单节点账号容量。", + subscriptionProxy: "使用代理拉取", + subscriptionProxyURL: "订阅拉取代理地址", + subscriptionRoute: "拉取线路", + subscriptionProxyShort: "代理", + invalidSubscriptionProxy: "请输入有效的 HTTP、SOCKS、Trojan、VLESS、SS 或 VMess 代理地址;此处不支持 {account}", refreshInterval: "同步间隔(秒)", noSources: "暂无代理订阅", probeInterval: "节点检测间隔", @@ -1864,12 +2061,6 @@ Object.assign(resources["zh-CN"].translation.settings.egress as unknown as Recor cleanupSubscriptionHint: "订阅管理的节点可能在下次订阅同步时重新创建。", cleanupUnavailableConfirm: "删除不可用节点", cleanupUnavailableComplete: "已删除 {{deleted}} 个不可用代理节点", - subscriptionProxy: "订阅拉取代理", - subscriptionProxyHelp: "用于拉取代理订阅内容。许多订阅源不支持国外网络,可填写 HTTP/HTTPS/SOCKS 代理地址。", - clearSubscriptionProxy: "清除", - cancelClearSubscriptionProxy: "保留", - subscriptionProxyClearPending: "保存后清除", - invalidProxy: "请输入有效的代理地址(http/https/socks4/socks4a/socks5/socks5h);此处不支持 {account}", }); Object.assign(resources["zh-CN"].translation.accounts as unknown as Record, {
{t(`audits.operations.${audit.operation}`)}
{(audit.durationMs / 1000).toFixed(2)}s
{uploadMutation.error.message}
{videoUploadMutation.error.message}
{sttResult.text}
{t("settings.egress.invalidSubscriptionProxy")}