From beed4c858465c33e1aafed69a5e6f873f6af195c Mon Sep 17 00:00:00 2001 From: WuxiVIP Date: Mon, 10 Aug 2026 14:51:41 +0800 Subject: [PATCH 01/48] feat(egress): support trojan/vless/ss/vmess/hysteria/tuic in proxy subscription validation --- backend/internal/application/egress/service.go | 16 ++++++++++++---- .../internal/application/egress/service_test.go | 6 ++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/backend/internal/application/egress/service.go b/backend/internal/application/egress/service.go index 4ab205dc..c76e7010 100644 --- a/backend/internal/application/egress/service.go +++ b/backend/internal/application/egress/service.go @@ -855,12 +855,20 @@ func NormalizeProxyURL(value string) (string, error) { return "", errors.New("代理地址格式无效") } switch strings.ToLower(parsed.Scheme) { - case "http", "https", "socks4", "socks4a", "socks5", "socks5h": + case "http", "https", "socks4", "socks4a", "socks5", "socks5h", + "trojan", "vless", "ss", "vmess", "hysteria", "hysteria2", "tuic", "tuicv5": default: - return "", errors.New("代理地址协议必须是 HTTP、HTTPS、SOCKS4 或 SOCKS5") + return "", errors.New("代理地址协议需为 HTTP、HTTPS、SOCKS4、SOCKS5,或 Trojan、VLESS、SS、VMess、Hysteria 等主流隧道协议。") } - if parsed.RawQuery != "" || parsed.Fragment != "" || (parsed.Path != "" && parsed.Path != "/") { - return "", errors.New("代理地址不能包含路径、查询参数或片段") + tunnelSchemes := map[string]bool{ + "trojan": true, "vless": true, "ss": true, "vmess": true, + "hysteria": true, "hysteria2": true, "tuic": true, "tuicv5": true, + } + scheme := strings.ToLower(parsed.Scheme) + if !tunnelSchemes[scheme] { + if parsed.RawQuery != "" || parsed.Fragment != "" || (parsed.Path != "" && parsed.Path != "/") { + return "", errors.New("代理地址不能包含路径、查询参数或片段") + } } if hasAccountPlaceholder { if parsed.User == nil || !strings.Contains(parsed.User.Username(), proxyAccountSentinel) { diff --git a/backend/internal/application/egress/service_test.go b/backend/internal/application/egress/service_test.go index d848d6cd..4dad16ec 100644 --- a/backend/internal/application/egress/service_test.go +++ b/backend/internal/application/egress/service_test.go @@ -25,6 +25,12 @@ func TestNormalizeProxyURLValidatesStructure(t *testing.T) { "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@127.0.0.1:8443?allowInsecure=0#remark", + "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", + "tuic://user:pass@127.0.0.1:443", } { value, err := NormalizeProxyURL(raw) if err != nil || value == "" { From 4cfa751c0fc39a111192d6debfd5c5abe6c7d1c5 Mon Sep 17 00:00:00 2001 From: WuxiVIP Date: Mon, 10 Aug 2026 17:01:58 +0800 Subject: [PATCH 02/48] fix(egress): add real tunnel proxy dialers Parse and normalize Trojan, VLESS, Shadowsocks, and VMess share links, then route Build, browser, pinned HTTPS, and subscription fetch traffic through embedded dialers. Update validation, UI help, redaction, docs, and protocol coverage tests. Hysteria and TUIC remain unsupported and are intentionally deferred. --- README.md | 7 +- README.zh-CN.md | 7 +- backend/go.mod | 13 + backend/go.sum | 34 +- .../internal/application/egress/service.go | 35 +- .../application/egress/service_test.go | 34 +- .../application/egress/subscription.go | 9 +- .../application/egress/subscription_test.go | 24 + backend/internal/infra/egress/buildclient.go | 7 + .../internal/infra/egress/buildclient_test.go | 35 + backend/internal/infra/egress/flaresolverr.go | 6 + .../infra/egress/flaresolverr_test.go | 11 +- backend/internal/infra/egress/pinnedclient.go | 7 + backend/internal/infra/egress/tlsclient.go | 16 +- .../internal/pkg/tunnelproxy/tunnelproxy.go | 651 ++++++++++++++++++ .../pkg/tunnelproxy/tunnelproxy_test.go | 132 ++++ .../src/features/settings/settings-model.ts | 42 +- frontend/src/shared/i18n/index.ts | 14 +- 18 files changed, 1042 insertions(+), 42 deletions(-) create mode 100644 backend/internal/pkg/tunnelproxy/tunnelproxy.go create mode 100644 backend/internal/pkg/tunnelproxy/tunnelproxy_test.go diff --git a/README.md b/README.md index 38208957..79c166a0 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 @@ -330,7 +330,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 +339,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..79ad456a 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 边界 @@ -331,7 +331,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 +340,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/go.mod b/backend/go.mod index 7cdc90a9..f30e3898 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -3,15 +3,18 @@ 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/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 +33,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 +69,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..7699ea4e 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,8 +85,8 @@ 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/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= @@ -125,11 +131,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 +155,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 +200,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 +223,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 +234,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 +245,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 +273,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/application/egress/service.go b/backend/internal/application/egress/service.go index c76e7010..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,24 +852,30 @@ 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) { - case "http", "https", "socks4", "socks4a", "socks5", "socks5h", - "trojan", "vless", "ss", "vmess", "hysteria", "hysteria2", "tuic", "tuicv5": - default: - return "", errors.New("代理地址协议需为 HTTP、HTTPS、SOCKS4、SOCKS5,或 Trojan、VLESS、SS、VMess、Hysteria 等主流隧道协议。") - } - tunnelSchemes := map[string]bool{ - "trojan": true, "vless": true, "ss": true, "vmess": true, - "hysteria": true, "hysteria2": true, "tuic": true, "tuicv5": true, - } scheme := strings.ToLower(parsed.Scheme) - if !tunnelSchemes[scheme] { - if parsed.RawQuery != "" || parsed.Fragment != "" || (parsed.Path != "" && parsed.Path != "/") { - return "", errors.New("代理地址不能包含路径、查询参数或片段") + 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、Trojan、VLESS、SS 或 VMess") + } + if parsed.RawQuery != "" || parsed.Fragment != "" || (parsed.Path != "" && parsed.Path != "/") { + return "", errors.New("代理地址不能包含路径、查询参数或片段") } if hasAccountPlaceholder { if parsed.User == nil || !strings.Contains(parsed.User.Username(), proxyAccountSentinel) { diff --git a/backend/internal/application/egress/service_test.go b/backend/internal/application/egress/service_test.go index 4dad16ec..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,29 +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@127.0.0.1:8443?allowInsecure=0#remark", - "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", - "tuic://user:pass@127.0.0.1:443", + "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..ec20f7a3 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 } diff --git a/backend/internal/application/egress/subscription_test.go b/backend/internal/application/egress/subscription_test.go index 4ee997c5..51c0c6c2 100644 --- a/backend/internal/application/egress/subscription_test.go +++ b/backend/internal/application/egress/subscription_test.go @@ -46,6 +46,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", 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/pkg/tunnelproxy/tunnelproxy.go b/backend/internal/pkg/tunnelproxy/tunnelproxy.go new file mode 100644 index 00000000..4b35809c --- /dev/null +++ b/backend/internal/pkg/tunnelproxy/tunnelproxy.go @@ -0,0 +1,651 @@ +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 +} + +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" { + if _, err := uuid.Parse(credential); err != nil { + return Config{}, errors.New("VLESS UUID 无效") + } + 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") + } + parsed.Scheme = scheme + parsed.Host = server + parsed.User = url.User(credential) + parsed.Path = "" + parsed.RawPath = "" + parsed.Fragment = "" + parsed.RawFragment = "" + parsed.RawQuery = query.Encode() + 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, + CanonicalProxyURL: parsed.String(), + } + if err := validateConfig(config); err != nil { + return Config{}, fmt.Errorf("创建 %s 隧道配置: %w", strings.ToUpper(scheme), err) + } + return config, nil +} + +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) + } + userID := jsonString(raw, "id") + if _, err := uuid.Parse(userID); err != nil { + return Config{}, errors.New("VMess UUID 无效") + } + 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 = "/" + } + 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 vless.NewClient(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("不支持的隧道代理协议") + } +} + +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()) + if err := tlsConnection.HandshakeContext(ctx); 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), + } + connection, _, err := websocket.Dial(ctx, 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 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..33ffc121 --- /dev/null +++ b/backend/internal/pkg/tunnelproxy/tunnelproxy_test.go @@ -0,0 +1,132 @@ +package tunnelproxy + +import ( + "context" + "encoding/base64" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Asutorufa/yuhaiin/pkg/net/netapi" + "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 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) + } +} diff --git a/frontend/src/features/settings/settings-model.ts b/frontend/src/features/settings/settings-model.ts index d31c1411..239c4e70 100644 --- a/frontend/src/features/settings/settings-model.ts +++ b/frontend/src/features/settings/settings-model.ts @@ -351,21 +351,35 @@ 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 /^ss:\/\/[^\s#]+(?:#[^\r\n]*)?$/.test(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) 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; + return parsed.pathname === "" || parsed.pathname === "/"; + } + 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 +390,25 @@ function validProxyURL(value: string): boolean { } } -/** Subscription fetch proxies are global and must never use per-account lease placeholders. */ +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(); + 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) + && ["tcp", "ws", "websocket"].includes(network) && ["", "none", "tls"].includes(tls); + } catch { + 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..6fd6b5fa 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -895,7 +895,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: "新建客户端密钥默认允许同时执行的请求数。" }, @@ -1725,6 +1725,7 @@ Object.assign(resources.en.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 +1738,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", @@ -1754,7 +1756,7 @@ Object.assign(resources.en.translation.settings.egress as unknown as Record, { @@ -1865,11 +1867,11 @@ Object.assign(resources["zh-CN"].translation.settings.egress as unknown as Recor cleanupUnavailableConfirm: "删除不可用节点", cleanupUnavailableComplete: "已删除 {{deleted}} 个不可用代理节点", subscriptionProxy: "订阅拉取代理", - subscriptionProxyHelp: "用于拉取代理订阅内容。许多订阅源不支持国外网络,可填写 HTTP/HTTPS/SOCKS 代理地址。", + subscriptionProxyHelp: "用于拉取代理订阅内容,支持 HTTP、SOCKS、Trojan、VLESS、SS 和 VMess。", clearSubscriptionProxy: "清除", cancelClearSubscriptionProxy: "保留", subscriptionProxyClearPending: "保存后清除", - invalidProxy: "请输入有效的代理地址(http/https/socks4/socks4a/socks5/socks5h);此处不支持 {account}", + invalidProxy: "请输入有效的 HTTP、SOCKS、Trojan、VLESS、SS 或 VMess 代理地址;此处不支持 {account}", }); Object.assign(resources["zh-CN"].translation.accounts as unknown as Record, { From dd9183e2b02e6a3f59439adb6e8237a355bc77c5 Mon Sep 17 00:00:00 2001 From: noxenys Date: Tue, 11 Aug 2026 23:02:56 +0800 Subject: [PATCH 03/48] feat: forward x_search time range and image search in console provider Console path normalizeConsoleTools currently strips every x_search field except type/enable_video_understanding and every web_search field except type/enable_image_understanding, dropping from_date/to_date and enable_image_search that clients legitimately send. - web_search: pass through enable_image_search (image search toggle) - x_search: pass through from_date/to_date (YYYY-MM-DD) with format and order validation; invalid values are dropped instead of erroring, matching the console provider's tolerate-and-drop style. The cli provider already validates these fields the same way. Behavior is unchanged for requests that do not set the new fields. --- .../infra/provider/console/normalize.go | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) 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) From 8b16d6d0b197173a44778e14c6062c1659c22fa8 Mon Sep 17 00:00:00 2001 From: noxenys Date: Tue, 11 Aug 2026 23:13:37 +0800 Subject: [PATCH 04/48] test: cover console x_search date bounds and web_search image search forwarding Add table-style subtests for normalizeConsoleTools: - forward enable_image_search on web_search; omit when unset - strip unknown web_search fields - forward valid x_search from_date/to_date - drop invalid formats and inverted ranges - keep single-sided from_date Keeps Console's tolerate-and-drop style (unlike CLI which returns 400). --- .../infra/provider/console/console_test.go | 134 ++++++++++++++++++ 1 file changed, 134 insertions(+) diff --git a/backend/internal/infra/provider/console/console_test.go b/backend/internal/infra/provider/console/console_test.go index bb88af56..2219b2ed 100644 --- a/backend/internal/infra/provider/console/console_test.go +++ b/backend/internal/infra/provider/console/console_test.go @@ -185,6 +185,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) { From 2e7379dd3b3f9d0256092bba007e7ec2b24e1a61 Mon Sep 17 00:00:00 2001 From: EmmaStoneX <241554625+EmmaStoneX@users.noreply.github.com> Date: Wed, 12 Aug 2026 13:46:48 +0000 Subject: [PATCH 05/48] feat: add on-demand clearance refresh mode Avoid scheduled browser solves for Console-only deployments while retaining automatic recovery after an upstream rejection invalidates the current clearance. --- backend/internal/infra/config/config.go | 5 +- backend/internal/infra/config/config_test.go | 11 ++++ backend/internal/infra/egress/manager.go | 11 +++- backend/internal/infra/egress/manager_test.go | 61 +++++++++++++++++++ 4 files changed, 83 insertions(+), 5 deletions(-) diff --git a/backend/internal/infra/config/config.go b/backend/internal/infra/config/config.go index 8438971c..a87ce043 100644 --- a/backend/internal/infra/config/config.go +++ b/backend/internal/infra/config/config.go @@ -25,6 +25,7 @@ const ( StatsigModeURL = "url" ClearanceModeManual = "manual" ClearanceModeFlareSolverr = "flaresolverr" + ClearanceModeOnDemand = "on_demand" DefaultStatsigSignerURL = "https://grok.wodf.de/sign" DefaultFlareSolverrURL = "http://flaresolverr:8191" RecommendedBuildClientVersion = "0.2.119" @@ -567,12 +568,12 @@ func (c Config) Validate() error { } switch c.Provider.Web.ClearanceMode { case ClearanceModeManual: - case ClearanceModeFlareSolverr: + case ClearanceModeFlareSolverr, ClearanceModeOnDemand: if err := validateFlareSolverrURL(c.Provider.Web.FlareSolverrURL); err != nil { return fmt.Errorf("provider.web FlareSolverr URL 无效: %w", err) } default: - return errors.New("provider.web Clearance 模式必须是 manual 或 flaresolverr") + return errors.New("provider.web Clearance 模式必须是 manual、flaresolverr 或 on_demand") } if c.Provider.Web.ClearanceTimeout.Value() < 10*time.Second || c.Provider.Web.ClearanceTimeout.Value() > 5*time.Minute { return errors.New("provider.web Clearance 超时必须在 10 秒到 5 分钟之间") diff --git a/backend/internal/infra/config/config_test.go b/backend/internal/infra/config/config_test.go index 4b84ffbb..f1c3b56b 100644 --- a/backend/internal/infra/config/config_test.go +++ b/backend/internal/infra/config/config_test.go @@ -501,6 +501,17 @@ func TestValidateStatsigModes(t *testing.T) { } } +func TestValidateOnDemandClearance(t *testing.T) { + base := defaultConfig() + base.Secrets.JWTSecret = "12345678901234567890123456789012" + base.Secrets.CredentialEncryptionKey = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" + base.Provider.Web.ClearanceMode = ClearanceModeOnDemand + base.Provider.Web.FlareSolverrURL = "http://flaresolverr:8191" + if err := base.Validate(); err != nil { + t.Fatalf("valid on-demand Clearance rejected: %v", err) + } +} + func TestValidateFlareSolverrClearance(t *testing.T) { base := defaultConfig() base.Secrets.JWTSecret = "12345678901234567890123456789012" diff --git a/backend/internal/infra/egress/manager.go b/backend/internal/infra/egress/manager.go index 12c5cc7d..09b8e360 100644 --- a/backend/internal/infra/egress/manager.go +++ b/backend/internal/infra/egress/manager.go @@ -812,7 +812,8 @@ func decodeProbeIP(body []byte) (string, error) { func (m *Manager) acquire(ctx context.Context, scope domain.Scope, affinity string, allowDirect bool, encryptedCredentialCookies string, boundNodeID uint64) (*Lease, bool, error) { now := time.Now().UTC() - managedClearance := isGrokWebScope(scope) && m.clearanceMode() == "flaresolverr" + clearanceMode := m.clearanceMode() + managedClearance := isGrokWebScope(scope) && (clearanceMode == "flaresolverr" || clearanceMode == "on_demand") configured := false var available []domain.Node if boundNodeID != 0 { @@ -1817,7 +1818,11 @@ func (m *Manager) ensureClearance(ctx context.Context, node domain.Node, proxyUR state.lastUsedAt = now m.clearances[key] = state } - if cfg.Mode != "flaresolverr" { + if cfg.Mode == "on_demand" && !forceRefresh { + m.clearanceMu.Unlock() + return existingCookies, existingUserAgent, nil + } + if cfg.Mode != "flaresolverr" && cfg.Mode != "on_demand" { m.clearanceMu.Unlock() return existingCookies, existingUserAgent, nil } @@ -1843,7 +1848,7 @@ func (m *Manager) refreshNode(ctx context.Context, node domain.Node, proxyURL, k solver := m.solver lock := m.clearanceLock m.clearanceMu.Unlock() - if cfg.Mode != "flaresolverr" { + if cfg.Mode != "flaresolverr" && cfg.Mode != "on_demand" { return clearanceSolution{}, errors.New("FlareSolverr Clearance 未启用") } timeout := cfg.Timeout diff --git a/backend/internal/infra/egress/manager_test.go b/backend/internal/infra/egress/manager_test.go index 6ec555b9..9fd88863 100644 --- a/backend/internal/infra/egress/manager_test.go +++ b/backend/internal/infra/egress/manager_test.go @@ -1846,6 +1846,67 @@ func TestWebForbiddenStillRebuildsBrowserSession(t *testing.T) { } } +func TestOnDemandClearanceRefreshesOnlyAfterRejection(t *testing.T) { + cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") + if err != nil { + t.Fatal(err) + } + cookies, err := cipher.Encrypt("cf_clearance=existing") + if err != nil { + t.Fatal(err) + } + repository := &mutableEgressRepository{node: domain.Node{ + ID: 1, Name: "console", Scope: domain.ScopeConsole, Enabled: true, Health: 1, + EncryptedCloudflareCookie: cookies, UserAgent: "Chrome/existing", + }} + solver := &clearanceSolverStub{} + manager := NewManager(repository, cipher) + manager.solver = solver + manager.UpdateClearanceConfig(ClearanceConfig{Mode: "on_demand", FlareSolverrURL: "http://solver", TargetURL: "https://grok.com", Timeout: time.Second, RefreshInterval: time.Hour}) + + first, err := manager.Acquire(context.Background(), domain.ScopeConsole, "account") + if err != nil { + t.Fatal(err) + } + if solver.calls != 0 || first.CFCookies != "cf_clearance=existing" { + t.Fatalf("initial calls=%d cookies=%q", solver.calls, first.CFCookies) + } + first.InvalidateClearance() + first.Release() + + second, err := manager.Acquire(context.Background(), domain.ScopeConsole, "account") + if err != nil { + t.Fatal(err) + } + defer second.Release() + if solver.calls != 1 || second.CFCookies != "cf_clearance=value-1" { + t.Fatalf("refresh calls=%d cookies=%q", solver.calls, second.CFCookies) + } + stored, err := cipher.Decrypt(repository.node.EncryptedCloudflareCookie) + if err != nil || stored != "cf_clearance=value-1" { + t.Fatalf("stored cookies=%q err=%v", stored, err) + } +} + +func TestOnDemandClearanceSkipsBackgroundRefresh(t *testing.T) { + cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") + if err != nil { + t.Fatal(err) + } + repository := &mutableEgressRepository{node: domain.Node{ID: 1, Name: "console", Scope: domain.ScopeConsole, Enabled: true, Health: 1}} + solver := &clearanceSolverStub{} + manager := NewManager(repository, cipher) + manager.solver = solver + manager.UpdateClearanceConfig(ClearanceConfig{Mode: "on_demand", FlareSolverrURL: "http://solver", TargetURL: "https://grok.com", Timeout: time.Second, RefreshInterval: time.Nanosecond}) + + if err := manager.RefreshDueClearances(context.Background(), false); err != nil { + t.Fatal(err) + } + if solver.calls != 0 { + t.Fatalf("background refresh called solver %d times", solver.calls) + } +} + func TestFlareSolverrRefreshesRejectedNodeBeforeNextLease(t *testing.T) { cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") if err != nil { From 58a6850a671777c94fed63ad7d8327aeedc9c48d Mon Sep 17 00:00:00 2001 From: mcheiyue <2267610721@qq.com> Date: Thu, 13 Aug 2026 00:50:41 +0800 Subject: [PATCH 06/48] =?UTF-8?q?fix(models):=20=E5=90=8C=E6=AD=A5?= =?UTF-8?q?=E6=A8=A1=E5=9E=8B=E6=94=B9=E4=B8=BA=E5=BC=82=E6=AD=A5=E8=A7=A6?= =?UTF-8?q?=E5=8F=91=EF=BC=8C=E9=81=BF=E5=85=8D=20CF=20100s=20=E8=B6=85?= =?UTF-8?q?=E6=97=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/application/model/service.go | 7 +++++++ backend/internal/transport/http/model/handler.go | 10 ++++------ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/backend/internal/application/model/service.go b/backend/internal/application/model/service.go index 79b3b4eb..706b359d 100644 --- a/backend/internal/application/model/service.go +++ b/backend/internal/application/model/service.go @@ -412,6 +412,13 @@ func (s *Service) Sync(ctx context.Context) (int, error) { } } +// SyncAsync 异步触发全量模型同步,不阻塞调用方。用 context.Background 避免请求超时导致同步中断。 +func (s *Service) SyncAsync(_ context.Context) { + s.syncAll.DoChan("all", func() (any, error) { + return s.syncAllAccounts(context.Background()) + }) +} + func (s *Service) syncAllAccounts(ctx context.Context) (int, error) { if s.providers == nil { return 0, fmt.Errorf("Provider 注册表未初始化") diff --git a/backend/internal/transport/http/model/handler.go b/backend/internal/transport/http/model/handler.go index 6fc6060d..ab24a95c 100644 --- a/backend/internal/transport/http/model/handler.go +++ b/backend/internal/transport/http/model/handler.go @@ -234,12 +234,10 @@ func (h *Handler) batchDelete(c *gin.Context) { } func (h *Handler) sync(c *gin.Context) { - count, err := h.service.Sync(c.Request.Context()) - if err != nil { - response.Error(c, http.StatusBadGateway, "modelSyncFailed", "同步上游模型失败") - return - } - response.Success(c, http.StatusOK, gin.H{"synced": count}) + // 异步触发全量同步,不阻塞 HTTP 响应。 + // 同步需要 2min+,Cloudflare 免费版 100s 超时,直接同步会 524 → 浏览器 Failed to fetch。 + go h.service.SyncAsync(c.Request.Context()) + response.Success(c, http.StatusOK, gin.H{"synced": 0, "async": true}) } func (h *Handler) update(c *gin.Context) { From 0b39b67f37513c0a4236260913bd084f763dfb6c Mon Sep 17 00:00:00 2001 From: RIERS <50164130+RIERS@users.noreply.github.com> Date: Thu, 13 Aug 2026 09:04:25 +0800 Subject: [PATCH 07/48] feat: add grok-4.6 xhigh reasoning effort Grok 4.6 accepts xhigh as a real thinking level. Keep it on the Build request path and generate grok-4.6-xhigh aliases instead of downgrading unknown-model xhigh to high. Unverified max stays guarded. --- backend/internal/domain/model/reasoning.go | 2 ++ backend/internal/domain/model/reasoning_test.go | 13 +++++++++++++ backend/internal/infra/provider/cli/normalize.go | 3 ++- .../internal/infra/provider/cli/normalize_test.go | 3 +++ .../transport/http/inference/model_list_test.go | 3 ++- frontend/src/shared/i18n/index.ts | 4 ++-- 6 files changed, 24 insertions(+), 4 deletions(-) diff --git a/backend/internal/domain/model/reasoning.go b/backend/internal/domain/model/reasoning.go index 35fcac5b..8caeb974 100644 --- a/backend/internal/domain/model/reasoning.go +++ b/backend/internal/domain/model/reasoning.go @@ -37,12 +37,14 @@ var reasoningEffortSuffixes = []string{ // generally accepted by the model family. Provider-specific wire restrictions are // applied by providerReasoningEffortOverrides: // - grok-4.5: low/medium/high (reasoning cannot be disabled; no xhigh/max) +// - grok-4.6: low/medium/high/xhigh (xhigh is a real upstream effort; max stays guarded) // - grok-4.3: none/low/medium/high // - grok-4.20-multi-agent: low/medium/high/xhigh (effort controls agent count) // // Unknown models default to none-only and never expand into effort aliases. var grokReasoningCapabilities = map[string][]string{ "grok-4.5": {ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh}, + "grok-4.6": {ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh, ReasoningEffortXHigh}, "grok-4.3": {ReasoningEffortNone, ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh}, "grok-build-0.1": {ReasoningEffortNone}, "grok-4.20-0309-reasoning": {ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh}, diff --git a/backend/internal/domain/model/reasoning_test.go b/backend/internal/domain/model/reasoning_test.go index 3e42599f..0ed814d1 100644 --- a/backend/internal/domain/model/reasoning_test.go +++ b/backend/internal/domain/model/reasoning_test.go @@ -17,6 +17,8 @@ func TestSupportedReasoningEffortsPerModel(t *testing.T) { {model: "grok-4.20-0309-reasoning", want: []string{"low", "medium", "high"}}, {model: "Console/grok-4.20-0309-reasoning", want: []string{}}, {model: "grok-4.20-multi-agent-0309", want: []string{"low", "medium", "high", "xhigh"}}, + {model: "grok-4.6", want: []string{"low", "medium", "high", "xhigh"}}, + {model: "Build/grok-4.6", want: []string{"low", "medium", "high", "xhigh"}}, {model: "grok-build-0.1", want: []string{"none"}}, {model: GrokComposer25Fast, want: []string{"none"}}, {model: "unknown-model", want: []string{"none"}}, @@ -38,6 +40,12 @@ func TestSupportedReasoningEffortsPerModel(t *testing.T) { if !SupportsReasoningEffort("grok-4.3", "none") || SupportsReasoningEffort("grok-4.3", "xhigh") { t.Fatal("grok-4.3 effort support mismatch") } + if !SupportsReasoningEffort("grok-4.6", "xhigh") || !SupportsReasoningEffort("Build/grok-4.6-xhigh", "xhigh") { + t.Fatal("grok-4.6 must advertise xhigh") + } + if SupportsReasoningEffort("grok-4.6", "none") || SupportsReasoningEffort("grok-4.6", "max") { + t.Fatal("grok-4.6 must not advertise none/max") + } if SupportsReasoningEffortForProvider(account.ProviderConsole, "grok-4.20-0309-reasoning", "low") || !SupportsReasoningEffortForProvider(account.ProviderBuild, "grok-4.20-0309-reasoning", "low") { t.Fatal("grok-4.20 reasoning effort restriction must remain Console-specific") @@ -74,6 +82,8 @@ func TestParseReasoningModelAlias(t *testing.T) { {name: "grok-4.5 rejects xhigh", input: "grok-4.5-xhigh", wantOK: false}, {name: "grok-4.3 none", input: "grok-4.3-none", wantBase: "grok-4.3", wantLevel: "none", wantOK: true}, {name: "xhigh before high", input: "grok-4.20-multi-agent-0309-xhigh", wantBase: "grok-4.20-multi-agent-0309", wantLevel: "xhigh", wantOK: true}, + {name: "grok-4.6 xhigh", input: "grok-4.6-xhigh", wantBase: "grok-4.6", wantLevel: "xhigh", wantOK: true}, + {name: "grok-4.6 rejects max", input: "grok-4.6-max", wantOK: false}, {name: "prefixed base", input: "Build/grok-4.5-medium", wantBase: "Build/grok-4.5", wantLevel: "medium", wantOK: true}, {name: "base model not alias", input: "grok-4.5", wantOK: false}, {name: "single-level model no alias", input: "grok-build-0.1-none", wantOK: false}, @@ -94,6 +104,9 @@ func TestReasoningAliasPublicIDs(t *testing.T) { if got := ReasoningAliasPublicIDs("grok-4.5"); len(got) != 3 || got[0] != "grok-4.5-low" || got[2] != "grok-4.5-high" { t.Fatalf("grok-4.5 aliases = %#v", got) } + if got := ReasoningAliasPublicIDs("grok-4.6"); len(got) != 4 || got[0] != "grok-4.6-low" || got[3] != "grok-4.6-xhigh" { + t.Fatalf("grok-4.6 aliases = %#v", got) + } if got := ReasoningAliasPublicIDs("Build/grok-4.3"); len(got) != 4 || got[0] != "grok-4.3-none" { t.Fatalf("grok-4.3 aliases = %#v", got) } diff --git a/backend/internal/infra/provider/cli/normalize.go b/backend/internal/infra/provider/cli/normalize.go index 624b7c1b..b1d6b15f 100644 --- a/backend/internal/infra/provider/cli/normalize.go +++ b/backend/internal/infra/provider/cli/normalize.go @@ -118,7 +118,8 @@ func applyBuildResponseDefaults(payload map[string]json.RawMessage) (bool, error // normalizeBuildReasoningEffortPayload maps client aliases to levels accepted by // the selected Grok model. Grok 4.5 and unknown models retain the proven defensive -// xhigh/max -> high behavior; explicitly supported xhigh models keep their value. +// xhigh/max -> high behavior; grok-4.6 and other explicitly supported xhigh models +// keep their value. Unverified max remains guarded. func normalizeBuildReasoningEffortPayload(payload map[string]json.RawMessage, model string) bool { raw, exists := payload["reasoning"] if !exists || isEmptyJSON(raw) { diff --git a/backend/internal/infra/provider/cli/normalize_test.go b/backend/internal/infra/provider/cli/normalize_test.go index 9e5ee18b..2b1331c6 100644 --- a/backend/internal/infra/provider/cli/normalize_test.go +++ b/backend/internal/infra/provider/cli/normalize_test.go @@ -53,6 +53,9 @@ func TestNormalizeBuildReasoningEffort(t *testing.T) { {name: "multi-agent xhigh", model: "grok-4.20-multi-agent-0309", effort: "xhigh", want: "xhigh"}, {name: "multi-agent uppercase xhigh", model: "grok-4.20-multi-agent-0309", effort: "XHIGH", want: "xhigh"}, {name: "multi-agent max remains guarded", model: "grok-4.20-multi-agent-0309", effort: "max", want: "high"}, + {name: "4.6 xhigh", model: "grok-4.6", effort: "xhigh", want: "xhigh"}, + {name: "4.6 uppercase xhigh", model: "grok-4.6", effort: "XHIGH", want: "xhigh"}, + {name: "4.6 max remains guarded", model: "grok-4.6", effort: "max", want: "high"}, {name: "unknown xhigh remains guarded", model: "future-model", effort: "xhigh", want: "high"}, {name: "high", model: "grok-4.5", effort: "high", want: "high"}, {name: "medium", model: "grok-4.5", effort: "medium", want: "medium"}, diff --git a/backend/internal/transport/http/inference/model_list_test.go b/backend/internal/transport/http/inference/model_list_test.go index 8af1ac50..9301d21b 100644 --- a/backend/internal/transport/http/inference/model_list_test.go +++ b/backend/internal/transport/http/inference/model_list_test.go @@ -44,6 +44,7 @@ func TestAppendReasoningModelAliasesUsesRealSupportedLevels(t *testing.T) { now := time.Unix(100, 0).UTC() base := newModelListItems([]modeldomain.Route{ {PublicID: "Build/grok-4.5", Provider: account.ProviderBuild, Capability: modeldomain.CapabilityResponses, CreatedAt: now}, + {PublicID: "Build/grok-4.6", Provider: account.ProviderBuild, Capability: modeldomain.CapabilityResponses, CreatedAt: now}, {PublicID: "Console/grok-4.3", Provider: account.ProviderConsole, Capability: modeldomain.CapabilityResponses, CreatedAt: now}, {PublicID: "Console/grok-4.20-0309-reasoning", Provider: account.ProviderConsole, Capability: modeldomain.CapabilityResponses, CreatedAt: now}, {PublicID: "Build/grok-build-0.1", Provider: account.ProviderBuild, Capability: modeldomain.CapabilityResponses, CreatedAt: now}, @@ -53,7 +54,7 @@ func TestAppendReasoningModelAliasesUsesRealSupportedLevels(t *testing.T) { for _, item := range expanded { ids[item.ID] = true } - for _, want := range []string{"grok-4.5", "grok-4.5-low", "grok-4.5-medium", "grok-4.5-high", "grok-4.3-none", "grok-4.3-low", "grok-4.3-medium", "grok-4.3-high", "grok-build-0.1"} { + for _, want := range []string{"grok-4.5", "grok-4.5-low", "grok-4.5-medium", "grok-4.5-high", "grok-4.6", "grok-4.6-low", "grok-4.6-medium", "grok-4.6-high", "grok-4.6-xhigh", "grok-4.3-none", "grok-4.3-low", "grok-4.3-medium", "grok-4.3-high", "grok-build-0.1"} { if !ids[want] { t.Fatalf("missing model %q in %#v", want, expanded) } diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index bef6f887..45e81c9c 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -732,7 +732,7 @@ const resources = { enabledDescription: "控制该密钥是否允许发起 API 请求。", modelAliases: "模型别名", modelAliasesDescription: "仅为当前可用且支持多个推理等级的模型生成后缀别名。", - modelAliasesBuildSupport: "Grok Build:grok-4.5、grok-3-mini、grok-3-mini-fast 支持 low / medium / high。", + modelAliasesBuildSupport: "Grok Build:grok-4.6 支持 low / medium / high / xhigh;grok-4.5、grok-3-mini、grok-3-mini-fast 支持 low / medium / high。", modelAliasesConsoleSupport: "Grok Console:grok-4.3 支持 none / low / medium / high;grok-4.20-0309-reasoning 为固定推理模式,不支持调节 effort;grok-4.20-multi-agent-0309 额外支持 xhigh。", modelAliasesUnsupported: "Grok Web、图片模型和视频模型不生成推理等级后缀。", modelAliasesOn: "已开启:可发现并调用当前模型支持的推理等级别名。", @@ -1342,7 +1342,7 @@ const resources = { 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" }, 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?" }, + 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.6 supports low / medium / high / xhigh; 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: { title: "Request audits", description: "Successful requests store metadata only. Failed requests retain a redacted and size-limited diagnostic snapshot.", From ee744275964eb6d517008fda3742b942547b1968 Mon Sep 17 00:00:00 2001 From: RIERS <50164130+RIERS@users.noreply.github.com> Date: Thu, 13 Aug 2026 10:08:29 +0800 Subject: [PATCH 08/48] fix: recover Grok Web Statsig meta from index 404 grok.com/index now returns HTTP 404 while still serving HTML that contains grok-site-verification. Parse that body instead of aborting on the status code, and fall back to / when the index page has no usable meta token. --- .../internal/infra/provider/web/statsig.go | 63 ++++++++++++++++--- .../infra/provider/web/statsig_test.go | 61 ++++++++++++++++++ 2 files changed, 114 insertions(+), 10 deletions(-) diff --git a/backend/internal/infra/provider/web/statsig.go b/backend/internal/infra/provider/web/statsig.go index 3f3e85fd..c313eff9 100644 --- a/backend/internal/infra/provider/web/statsig.go +++ b/backend/internal/infra/provider/web/statsig.go @@ -272,9 +272,46 @@ func fetchStatsigMetaContent(ctx context.Context, baseURL, token string, lease * if lease == nil { return "", fmt.Errorf("Statsig 获取缺少出口租约") } + return fetchStatsigMetaContentWithDo(ctx, baseURL, token, lease, lease.Do) +} + +func fetchStatsigMetaContentWithDo(ctx context.Context, baseURL, token string, lease *infraegress.Lease, do func(*http.Request) (*http.Response, error)) (string, error) { + if do == nil { + return "", fmt.Errorf("Statsig 获取缺少出口租约") + } + var indexErr error + for _, path := range []string{"/index", "/"} { + content, err := fetchStatsigMetaContentPath(ctx, baseURL, token, lease, path, do) + if err == nil { + return content, nil + } + if path == "/index" { + indexErr = err + if !shouldFallbackStatsigMeta(err) { + return "", err + } + continue + } + return "", err + } + if indexErr != nil { + return "", indexErr + } + return "", fmt.Errorf("Grok index 缺少 grok-site-verification") +} + +func shouldFallbackStatsigMeta(err error) bool { + if err == nil { + return false + } + message := err.Error() + return strings.Contains(message, "缺少 grok-site-verification") || strings.Contains(message, "Grok index 返回 ") +} + +func fetchStatsigMetaContentPath(ctx context.Context, baseURL, token string, lease *infraegress.Lease, path string, do func(*http.Request) (*http.Response, error)) (string, error) { requestCtx, cancel := context.WithTimeout(infraegress.WithPhysicalCallStage(ctx, "statsig_meta"), 15*time.Second) defer cancel() - request, err := http.NewRequestWithContext(requestCtx, http.MethodGet, strings.TrimRight(baseURL, "/")+"/index", nil) + request, err := http.NewRequestWithContext(requestCtx, http.MethodGet, strings.TrimRight(baseURL, "/")+path, nil) if err != nil { return "", err } @@ -287,16 +324,15 @@ func fetchStatsigMetaContent(ctx context.Context, baseURL, token string, lease * request.Header.Set("Sec-Fetch-Mode", "navigate") request.Header.Set("Sec-Fetch-Site", "same-origin") request.Header.Set("Upgrade-Insecure-Requests", "1") - request.Header.Set("User-Agent", lease.UserAgent) - request.Header.Set("Cookie", infraegress.BuildSSOCookie(token, lease.CFCookies)) - response, err := lease.Do(request) + if lease != nil { + request.Header.Set("User-Agent", lease.UserAgent) + request.Header.Set("Cookie", infraegress.BuildSSOCookie(token, lease.CFCookies)) + } + response, err := do(request) if err != nil { return "", err } defer response.Body.Close() - if response.StatusCode < 200 || response.StatusCode >= 300 { - return "", fmt.Errorf("Grok index 返回 %d", response.StatusCode) - } body, err := io.ReadAll(io.LimitReader(response.Body, statsigMetaBodyLimit+1)) if err != nil { return "", err @@ -304,11 +340,18 @@ func fetchStatsigMetaContent(ctx context.Context, baseURL, token string, lease * if len(body) > statsigMetaBodyLimit { return "", fmt.Errorf("Grok index 超过安全上限") } + return statsigMetaFromHTTP(response.StatusCode, body) +} + +func statsigMetaFromHTTP(status int, body []byte) (string, error) { content, err := extractStatsigMetaContent(body) - if err != nil { - return "", err + if err == nil { + return content, nil } - return content, nil + if status < 200 || status >= 300 { + return "", fmt.Errorf("Grok index 返回 %d", status) + } + return "", err } func extractStatsigMetaContent(body []byte) (string, error) { diff --git a/backend/internal/infra/provider/web/statsig_test.go b/backend/internal/infra/provider/web/statsig_test.go index d4c0298f..0ac543d3 100644 --- a/backend/internal/infra/provider/web/statsig_test.go +++ b/backend/internal/infra/provider/web/statsig_test.go @@ -19,6 +19,67 @@ type roundTripFunc func(*http.Request) (*http.Response, error) func (f roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) { return f(request) } +func TestStatsigMetaFromHTTPAcceptsIndexNotFoundWithVerification(t *testing.T) { + body := []byte(``) + value, err := statsigMetaFromHTTP(http.StatusNotFound, body) + if err != nil || value != "meta-value" { + t.Fatalf("value=%q err=%v", value, err) + } +} + +func TestStatsigMetaFromHTTPKeepsMissingVerificationErrorOnSuccessStatus(t *testing.T) { + if _, err := statsigMetaFromHTTP(http.StatusOK, []byte(``)); err == nil || !strings.Contains(err.Error(), "缺少 grok-site-verification") { + t.Fatalf("err=%v", err) + } +} + +func TestStatsigMetaFromHTTPPreservesStatusWhenVerificationMissing(t *testing.T) { + if _, err := statsigMetaFromHTTP(http.StatusNotFound, []byte(``)); err == nil || !strings.Contains(err.Error(), "Grok index 返回 404") { + t.Fatalf("err=%v", err) + } +} + +func TestFetchStatsigMetaContentFallsBackToRootWhenIndexHasNoVerification(t *testing.T) { + var paths []string + do := func(request *http.Request) (*http.Response, error) { + paths = append(paths, request.URL.Path) + switch request.URL.Path { + case "/index": + return &http.Response{StatusCode: http.StatusNotFound, Body: io.NopCloser(strings.NewReader(``)), Header: http.Header{}}, nil + case "/": + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(``)), Header: http.Header{}}, nil + default: + t.Fatalf("unexpected path %q", request.URL.Path) + return nil, nil + } + } + value, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do) + if err != nil || value != "root-meta" { + t.Fatalf("value=%q err=%v paths=%v", value, err, paths) + } + if len(paths) != 2 || paths[0] != "/index" || paths[1] != "/" { + t.Fatalf("paths=%v", paths) + } +} + +func TestFetchStatsigMetaContentDoesNotFallbackWhenIndex404HasVerification(t *testing.T) { + var paths []string + do := func(request *http.Request) (*http.Response, error) { + paths = append(paths, request.URL.Path) + if request.URL.Path != "/index" { + t.Fatalf("unexpected fallback to %q", request.URL.Path) + } + return &http.Response{StatusCode: http.StatusNotFound, Body: io.NopCloser(strings.NewReader(``)), Header: http.Header{}}, nil + } + value, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do) + if err != nil || value != "index-meta" { + t.Fatalf("value=%q err=%v", value, err) + } + if len(paths) != 1 || paths[0] != "/index" { + t.Fatalf("paths=%v", paths) + } +} + func TestExtractStatsigMetaContentAcceptsCurrentMetaName(t *testing.T) { for _, name := range []string{"grok-site―verification", "grok-site-verification"} { body := []byte(``) From 9316fa3ea49183d297347077cf3ef5df52e55583 Mon Sep 17 00:00:00 2001 From: RIERS <50164130+RIERS@users.noreply.github.com> Date: Thu, 13 Aug 2026 12:16:05 +0800 Subject: [PATCH 09/48] fix(accounts): serialize Build detect item observers DetectBuildAccountsWithProgress invoked itemObserver from batch workers. A lock-free observer could race or drop results; serialize callbacks like progress updates. --- .../application/account/build_detect_test.go | 67 +++++++++++++++++++ .../internal/application/account/service.go | 7 +- 2 files changed, 72 insertions(+), 2 deletions(-) diff --git a/backend/internal/application/account/build_detect_test.go b/backend/internal/application/account/build_detect_test.go index 898de2cf..9fec90f7 100644 --- a/backend/internal/application/account/build_detect_test.go +++ b/backend/internal/application/account/build_detect_test.go @@ -8,7 +8,11 @@ import ( "io" "net/http" "path/filepath" + "strconv" "testing" + "time" + + "github.com/chenyme/grok2api/backend/internal/pkg/batch" accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" "github.com/chenyme/grok2api/backend/internal/infra/persistence/relational" @@ -288,3 +292,66 @@ func TestDetectBuildAccountsStreamsInvalidOnlyForAll(t *testing.T) { _ = okAccount _ = invalidAccount } + +func TestDetectBuildAccountsSerializesItemObserver(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "detect-observer.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + accessToken, err := cipher.Encrypt("access-token") + if err != nil { + t.Fatal(err) + } + repo := relational.NewAccountRepository(database) + const accountCount = 8 + for index := range accountCount { + if _, _, err := repo.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderBuild, Name: "invalid-" + strconv.Itoa(index), UserID: "user-invalid-" + strconv.Itoa(index), + SourceKey: "detect-invalid-" + strconv.Itoa(index), EncryptedAccessToken: accessToken, + Enabled: true, AuthStatus: accountdomain.AuthStatusActive, RefreshPermanent: true, Priority: 1, MaxConcurrent: 1, + }); err != nil { + t.Fatal(err) + } + } + service := NewService(repo, nil, nil, nil, provider.NewRegistry(detectResponsesAdapter{ + status: http.StatusUnauthorized, + }), cipher, nil) + service.SetDetectPool(batch.NewPool(accountCount)) + + started := make(chan struct{}, accountCount) + release := make(chan struct{}) + var items []BuildDetectItemResult + errCh := make(chan error, 1) + go func() { + _, _, detectErr := service.DetectBuildAccountsWithProgress(ctx, nil, true, nil, func(item BuildDetectItemResult) error { + started <- struct{}{} + <-release + items = append(items, item) + return nil + }) + errCh <- detectErr + }() + + deadline := time.After(2 * time.Second) + select { + case <-started: + case <-deadline: + t.Fatal("itemObserver was not invoked") + } + close(release) + if detectErr := <-errCh; detectErr != nil { + t.Fatal(detectErr) + } + if len(items) != accountCount { + t.Fatalf("serialized items = %d, want %d", len(items), accountCount) + } +} diff --git a/backend/internal/application/account/service.go b/backend/internal/application/account/service.go index 62931634..4261c6c7 100644 --- a/backend/internal/application/account/service.go +++ b/backend/internal/application/account/service.go @@ -3684,7 +3684,7 @@ func (s *Service) BatchRefreshBilling(ctx context.Context, ids []uint64) (int, i // DetectBuildAccountsWithProgress 对指定或全部 Grok Build 账号发起探测请求;all 与 ids 必须且只能提供一个。 // 该方法同时上报批量进度与单账号明细。 -// itemObserver 在每个账号完成后调用:选中检测会推送全部结果,全量检测仅推送已确认失效账号。 +// itemObserver 在每个账号完成后串行调用:选中检测会推送全部结果,全量检测仅推送已确认失效账号。 func (s *Service) DetectBuildAccountsWithProgress(ctx context.Context, ids []uint64, all bool, progress BatchProgressObserver, itemObserver BuildDetectItemObserver) (int, int, error) { if all == (len(ids) > 0) { return 0, 0, invalidInput("必须明确选择全部账号或提供非空账号 ID") @@ -3725,7 +3725,10 @@ func (s *Service) DetectBuildAccountsWithProgress(ctx context.Context, ids []uin summary, err := batch.ForEachObserved(runCtx, ids, batch.Options{Workers: pool.Limit(), Pool: pool}, func(workCtx context.Context, id uint64) (BuildDetectItemResult, error) { item := s.detectBuildAccount(workCtx, id) if itemObserver != nil && (selectedMode || item.Outcome == BuildDetectOutcomeInvalid) { - if notifyErr := itemObserver(item); notifyErr != nil { + progressMu.Lock() + notifyErr := itemObserver(item) + progressMu.Unlock() + if notifyErr != nil { return item, notifyErr } } From d90fb041899783382da2a37a84faf7f0752d5532 Mon Sep 17 00:00:00 2001 From: "Clove." <2164312714@qq.com> Date: Thu, 13 Aug 2026 12:41:21 +0800 Subject: [PATCH 10/48] fix(build): preserve grok-4.5 capability with grok-4.6 Build OAuth sessions can continue serving grok-4.5 even when the sparse upstream catalog only reports grok-4.6. Keep the compatibility capability scoped to Build and deduplicate it during normalization. Refs #905 --- .../internal/infra/provider/cli/adapter.go | 19 +++++++++++++++--- .../infra/provider/cli/adapter_test.go | 20 +++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/backend/internal/infra/provider/cli/adapter.go b/backend/internal/infra/provider/cli/adapter.go index f172208c..763c278f 100644 --- a/backend/internal/infra/provider/cli/adapter.go +++ b/backend/internal/infra/provider/cli/adapter.go @@ -44,6 +44,8 @@ type Config struct { const ( subscriptionTierTimeout = 10 * time.Second buildControlTimeout = 30 * time.Second + buildGrok45Model = "grok-4.5" + buildGrok46Model = "grok-4.6" ) // Adapter implements the Grok Build CLI Responses, model, Billing, and OAuth protocols. @@ -618,15 +620,17 @@ func (a *Adapter) ListModels(ctx context.Context, credential account.Credential) // NormalizeAccountModelCapabilities normalizes capabilities that the OAuth // session contract exposes independently of the account's sparse /models list. -// Composer is available to Build OAuth sessions even though the live catalog can -// return only grok-4.5. Super always includes video 1.5; Free and Unknown remove -// video 1.5 exactly. BuildAPIFallback is ignored. +// Composer is available to Build OAuth sessions independently of the sparse +// live catalog. Grok 4.6 sessions retain the still-supported Grok 4.5 route for +// backwards compatibility. Super always includes video 1.5; Free and Unknown +// remove video 1.5 exactly. BuildAPIFallback is ignored. func (a *Adapter) NormalizeAccountModelCapabilities(models []string, billing *account.Billing, credential account.Credential) []string { super := account.IsBuildSuper(credential, billing) composer := credential.Provider == account.ProviderBuild && credential.AuthType == account.AuthTypeOAuth result := make([]string, 0, len(models)+2) seen := make(map[string]struct{}, len(models)+2) hasVideo15 := false + hasGrok46 := false for _, model := range models { model = strings.TrimSpace(model) if model == "" { @@ -641,9 +645,18 @@ func (a *Adapter) NormalizeAccountModelCapabilities(models []string, billing *ac } hasVideo15 = true } + if model == buildGrok46Model { + hasGrok46 = true + } seen[model] = struct{}{} result = append(result, model) } + if credential.Provider == account.ProviderBuild && hasGrok46 { + if _, exists := seen[buildGrok45Model]; !exists { + seen[buildGrok45Model] = struct{}{} + result = append(result, buildGrok45Model) + } + } if super && !hasVideo15 { result = append(result, buildVideoModel) } diff --git a/backend/internal/infra/provider/cli/adapter_test.go b/backend/internal/infra/provider/cli/adapter_test.go index f0cac0c2..27e89378 100644 --- a/backend/internal/infra/provider/cli/adapter_test.go +++ b/backend/internal/infra/provider/cli/adapter_test.go @@ -628,6 +628,26 @@ func TestNormalizeAccountModelCapabilitiesAddsComposerOnlyForBuildOAuth(t *testi } } +func TestNormalizeAccountModelCapabilitiesKeepsGrok45ForBuildGrok46(t *testing.T) { + adapter := &Adapter{} + build := account.Credential{Provider: account.ProviderBuild} + got := adapter.NormalizeAccountModelCapabilities([]string{buildGrok46Model}, nil, build) + if len(got) != 2 || got[0] != buildGrok46Model || got[1] != buildGrok45Model { + t.Fatalf("Build Grok 4.6 compatibility capabilities = %#v", got) + } + + got = adapter.NormalizeAccountModelCapabilities([]string{buildGrok45Model, buildGrok46Model, buildGrok45Model}, nil, build) + if len(got) != 2 || got[0] != buildGrok45Model || got[1] != buildGrok46Model { + t.Fatalf("Build Grok 4.5 compatibility was not deduplicated: %#v", got) + } + + console := account.Credential{Provider: account.ProviderConsole} + got = adapter.NormalizeAccountModelCapabilities([]string{buildGrok46Model}, nil, console) + if len(got) != 1 || got[0] != buildGrok46Model { + t.Fatalf("Build compatibility leaked to Console: %#v", got) + } +} + func TestGrokSessionIDFollowsConversationIdentity(t *testing.T) { explicit := "019f6b02-5bae-7cf3-b26e-73e85c861749" if value, err := grokSessionID(explicit); err != nil || value != explicit { From 211aa83634c6bd2c5b2f3a510997eb90bc1c31d7 Mon Sep 17 00:00:00 2001 From: lij768423-svg Date: Thu, 13 Aug 2026 13:25:54 +0800 Subject: [PATCH 11/48] feat: add degraded-account monitor to quality guard Surface streaming TPS anomalies by account on the quality-guard page so operators can filter repeat offenders and mute them with the existing account batch API. Classification matches the panel formula: output tokens over generation time, with buffered_burst for short windows. --- backend/internal/application/audit/degrade.go | 331 ++++++++++++++++++ .../application/audit/degrade_test.go | 64 ++++ backend/internal/domain/audit/degrade.go | 36 ++ backend/internal/domain/audit/degrade_test.go | 27 ++ .../relational/audit_repository.go | 62 ++++ backend/internal/repository/audit.go | 26 ++ .../internal/transport/http/audit/handler.go | 100 ++++++ .../transport/http/audit/handler_test.go | 37 ++ .../quality-guard/degrade-accounts-panel.tsx | 262 ++++++++++++++ .../quality-guard/quality-guard-api.ts | 69 +++- .../quality-guard/quality-guard-page.tsx | 13 + frontend/src/shared/i18n/index.ts | 35 +- 12 files changed, 1060 insertions(+), 2 deletions(-) create mode 100644 backend/internal/application/audit/degrade.go create mode 100644 backend/internal/application/audit/degrade_test.go create mode 100644 backend/internal/domain/audit/degrade.go create mode 100644 backend/internal/domain/audit/degrade_test.go create mode 100644 frontend/src/features/quality-guard/degrade-accounts-panel.tsx diff --git a/backend/internal/application/audit/degrade.go b/backend/internal/application/audit/degrade.go new file mode 100644 index 00000000..96758715 --- /dev/null +++ b/backend/internal/application/audit/degrade.go @@ -0,0 +1,331 @@ +package audit + +import ( + "context" + "math" + "sort" + "time" + + auditdomain "github.com/chenyme/grok2api/backend/internal/domain/audit" + "github.com/chenyme/grok2api/backend/internal/repository" +) + +const ( + degradeWindow1h = "1h" + degradeWindow6h = "6h" + degradeWindow24h = "24h" + degradeWindow7d = "7d" + degradeEventLimit = 20_000 + degradeRecentEventCap = 80 +) + +type DegradeThresholds struct { + SoftTPS float64 + HardTPS float64 + MinGenMS int64 + MinOut int64 +} + +type DegradeSummary struct { + Window string + GeneratedAt time.Time + Thresholds DegradeThresholds + Totals DegradeTotals + Series []DegradeBucket + Nodes []DegradeNode + Accounts []DegradeAccount + Events []DegradeEventView +} + +type DegradeTotals struct { + Hits int + Accounts int + StillEnabled int + Disabled int + Hard int + Soft int + Burst int + MaxTPS float64 +} + +type DegradeBucket struct { + Label string `json:"label"` + Count int `json:"count"` + Severe int `json:"severe"` +} + +type DegradeNode struct { + Name string `json:"name"` + Hits int `json:"hits"` + Accounts int `json:"accounts"` + MaxTPS float64 `json:"maxTPS"` +} + +type DegradeAccount struct { + ID uint64 + Name string + Email string + Hits int + MaxTPS float64 + Classes map[string]int + Nodes []string + Last time.Time + Enabled bool + BFS int + Found bool +} + +type DegradeEventView struct { + ID uint64 + RequestID string + AccountID *uint64 + AccountName string + NodeName string + OutputTokens int64 + TPS float64 + Class string + CreatedAt time.Time + Model string +} + +func (s *Service) DegradeSummary(ctx context.Context, window string, thresholds DegradeThresholds) (DegradeSummary, error) { + window, start, end, err := resolveDegradeWindow(window, s.now().UTC()) + if err != nil { + return DegradeSummary{}, err + } + thresholds = normalizeDegradeThresholds(thresholds) + events, err := s.audits.ListDegradeEvents(ctx, repository.DegradeEventQuery{ + Start: start, End: end, MinOutputTokens: thresholds.MinOut, Limit: degradeEventLimit, + }) + if err != nil { + return DegradeSummary{}, err + } + return buildDegradeSummary(window, end, thresholds, events), nil +} + +func resolveDegradeWindow(value string, now time.Time) (string, time.Time, time.Time, error) { + if value == "" { + value = degradeWindow24h + } + var duration time.Duration + switch value { + case degradeWindow1h: + duration = time.Hour + case degradeWindow6h: + duration = 6 * time.Hour + case degradeWindow24h: + duration = 24 * time.Hour + case degradeWindow7d: + duration = 7 * 24 * time.Hour + default: + return "", time.Time{}, time.Time{}, ErrInvalidPeriod + } + return value, now.Add(-duration), now, nil +} + +func normalizeDegradeThresholds(value DegradeThresholds) DegradeThresholds { + if value.SoftTPS <= 0 || math.IsNaN(value.SoftTPS) || math.IsInf(value.SoftTPS, 0) { + value.SoftTPS = auditdomain.DefaultDegradeSoftTPS + } + if value.HardTPS <= 0 || math.IsNaN(value.HardTPS) || math.IsInf(value.HardTPS, 0) { + value.HardTPS = auditdomain.DefaultDegradeHardTPS + } + if value.SoftTPS >= value.HardTPS { + value.SoftTPS = auditdomain.DefaultDegradeSoftTPS + value.HardTPS = auditdomain.DefaultDegradeHardTPS + } + if value.MinGenMS <= 0 { + value.MinGenMS = auditdomain.DefaultDegradeMinGenMS + } + if value.MinOut <= 0 { + value.MinOut = auditdomain.DefaultDegradeMinOutput + } + return value +} + +func buildDegradeSummary(window string, now time.Time, thresholds DegradeThresholds, events []repository.DegradeEvent) DegradeSummary { + type accAgg struct { + hits int + maxTPS float64 + classes map[string]int + nodes map[string]struct{} + last time.Time + name string + email string + enabled bool + found bool + bfs int + } + type nodeAgg struct { + hits int + accounts map[uint64]struct{} + maxTPS float64 + } + accounts := map[uint64]*accAgg{} + nodes := map[string]*nodeAgg{} + classCounts := map[string]int{} + var classified []DegradeEventView + var maxTPS float64 + + for _, event := range events { + class, tps, _ := auditdomain.ClassifyOutputSpeed(event.OutputTokens, event.FirstTokenMS, event.DurationMS, thresholds.SoftTPS, thresholds.HardTPS, thresholds.MinGenMS) + if class == "" { + continue + } + classCounts[class]++ + if tps > maxTPS { + maxTPS = tps + } + nodeName := event.EgressNodeName + if nodeName == "" { + nodeName = "?" + } + classified = append(classified, DegradeEventView{ + ID: event.ID, RequestID: event.RequestID, AccountID: event.AccountID, AccountName: event.AccountName, + NodeName: nodeName, OutputTokens: event.OutputTokens, TPS: math.Round(tps*100) / 100, Class: class, + CreatedAt: event.CreatedAt, Model: event.Model, + }) + if event.AccountID == nil || *event.AccountID == 0 { + continue + } + id := *event.AccountID + rec := accounts[id] + if rec == nil { + rec = &accAgg{classes: map[string]int{}, nodes: map[string]struct{}{}} + accounts[id] = rec + } + rec.hits++ + if tps > rec.maxTPS { + rec.maxTPS = tps + } + rec.classes[class]++ + rec.nodes[nodeName] = struct{}{} + if event.CreatedAt.After(rec.last) { + rec.last = event.CreatedAt + rec.name = event.AccountName + } + if rec.name == "" { + rec.name = event.AccountName + } + if event.Email != "" { + rec.email = event.Email + } + if event.Enabled != nil { + rec.enabled = *event.Enabled + rec.found = true + } + if event.BuildBotFlagSource > rec.bfs { + rec.bfs = event.BuildBotFlagSource + } + nd := nodes[nodeName] + if nd == nil { + nd = &nodeAgg{accounts: map[uint64]struct{}{}} + nodes[nodeName] = nd + } + nd.hits++ + nd.accounts[id] = struct{}{} + if tps > nd.maxTPS { + nd.maxTPS = tps + } + } + + accountViews := make([]DegradeAccount, 0, len(accounts)) + enabled, disabled := 0, 0 + for id, rec := range accounts { + if rec.found && rec.enabled { + enabled++ + } else { + disabled++ + } + nodeNames := make([]string, 0, len(rec.nodes)) + for name := range rec.nodes { + nodeNames = append(nodeNames, name) + } + sort.Strings(nodeNames) + email := rec.email + if email == "" { + email = rec.name + } + accountViews = append(accountViews, DegradeAccount{ + ID: id, Name: rec.name, Email: email, Hits: rec.hits, MaxTPS: math.Round(rec.maxTPS*10) / 10, + Classes: rec.classes, Nodes: nodeNames, Last: rec.last, Enabled: rec.found && rec.enabled, BFS: rec.bfs, Found: rec.found, + }) + } + sort.Slice(accountViews, func(i, j int) bool { + if accountViews[i].Hits != accountViews[j].Hits { + return accountViews[i].Hits > accountViews[j].Hits + } + return accountViews[i].MaxTPS > accountViews[j].MaxTPS + }) + + nodeViews := make([]DegradeNode, 0, len(nodes)) + for name, rec := range nodes { + nodeViews = append(nodeViews, DegradeNode{Name: name, Hits: rec.hits, Accounts: len(rec.accounts), MaxTPS: math.Round(rec.maxTPS*10) / 10}) + } + sort.Slice(nodeViews, func(i, j int) bool { return nodeViews[i].Hits > nodeViews[j].Hits }) + + recent := classified + if len(recent) > degradeRecentEventCap { + recent = recent[:degradeRecentEventCap] + } + + return DegradeSummary{ + Window: window, GeneratedAt: now, Thresholds: thresholds, + Totals: DegradeTotals{ + Hits: len(classified), Accounts: len(accounts), StillEnabled: enabled, Disabled: disabled, + Hard: classCounts[auditdomain.DegradeClassHard], Soft: classCounts[auditdomain.DegradeClassSoft], + Burst: classCounts[auditdomain.DegradeClassBurst], MaxTPS: maxTPS, + }, + Series: bucketDegradeSeries(classified, window, now), + Nodes: nodeViews, Accounts: accountViews, Events: recent, + } +} + +func bucketDegradeSeries(events []DegradeEventView, window string, now time.Time) []DegradeBucket { + var step time.Duration + var start time.Time + var label func(time.Time) string + switch window { + case degradeWindow7d: + step = 2 * time.Hour + start = now.Add(-7 * 24 * time.Hour) + label = func(t time.Time) string { return t.Format("01-02 15:00") } + case degradeWindow24h: + step = time.Hour + start = now.Add(-24 * time.Hour) + label = func(t time.Time) string { return t.Format("15:00") } + case degradeWindow6h: + step = 20 * time.Minute + start = now.Add(-6 * time.Hour) + label = func(t time.Time) string { return t.Format("15:04") } + default: + step = 5 * time.Minute + start = now.Add(-time.Hour) + label = func(t time.Time) string { return t.Format("15:04") } + } + var buckets []time.Time + for cursor := start; cursor.Before(now); cursor = cursor.Add(step) { + buckets = append(buckets, cursor) + } + if len(buckets) == 0 { + return nil + } + counts := make([]int, len(buckets)) + severe := make([]int, len(buckets)) + stepSeconds := step.Seconds() + for _, event := range events { + idx := int(event.CreatedAt.Sub(start).Seconds() / stepSeconds) + if idx < 0 || idx >= len(counts) { + continue + } + counts[idx]++ + if event.Class == auditdomain.DegradeClassHard || event.Class == auditdomain.DegradeClassBurst { + severe[idx]++ + } + } + out := make([]DegradeBucket, len(buckets)) + for i, bucket := range buckets { + out[i] = DegradeBucket{Label: label(bucket), Count: counts[i], Severe: severe[i]} + } + return out +} diff --git a/backend/internal/application/audit/degrade_test.go b/backend/internal/application/audit/degrade_test.go new file mode 100644 index 00000000..24d40fe7 --- /dev/null +++ b/backend/internal/application/audit/degrade_test.go @@ -0,0 +1,64 @@ +package audit + +import ( + "context" + "log/slog" + "path/filepath" + "testing" + "time" + + auditdomain "github.com/chenyme/grok2api/backend/internal/domain/audit" + "github.com/chenyme/grok2api/backend/internal/infra/persistence/relational" +) + +func TestDegradeSummaryClassifiesStreamingAnomalies(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + repo := relational.NewAuditRepository(database) + now := time.Now().UTC() + first := int64(100) + accountID := uint64(7) + records := []auditdomain.Record{ + {RequestID: "hard-1", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", AccountID: &accountID, AccountName: "hot", EgressNodeName: "node-a", StatusCode: 200, Streaming: true, OutputTokens: 2000, FirstTokenMS: &first, DurationMS: 1100, CreatedAt: now.Add(-time.Hour)}, + {RequestID: "quality_skip_me", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", AccountID: &accountID, StatusCode: 200, Streaming: true, OutputTokens: 2000, FirstTokenMS: &first, DurationMS: 1100, CreatedAt: now.Add(-time.Hour)}, + {RequestID: "non-stream", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", AccountID: &accountID, StatusCode: 200, Streaming: false, OutputTokens: 2000, FirstTokenMS: &first, DurationMS: 1100, CreatedAt: now.Add(-time.Hour)}, + } + if err := repo.CreateBatch(ctx, records); err != nil { + t.Fatal(err) + } + service := NewService(repo, slog.Default(), 8, 4, time.Second) + service.now = func() time.Time { return now } + summary, err := service.DegradeSummary(ctx, "24h", DegradeThresholds{SoftTPS: 500, HardTPS: 1000}) + if err != nil { + t.Fatal(err) + } + if summary.Totals.Hits != 1 || summary.Totals.Accounts != 1 || summary.Totals.Hard != 1 { + t.Fatalf("totals = %#v", summary.Totals) + } + if len(summary.Accounts) != 1 || summary.Accounts[0].ID != 7 || summary.Accounts[0].Hits != 1 { + t.Fatalf("accounts = %#v", summary.Accounts) + } +} + +func TestDegradeSummaryRejectsUnknownWindow(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-window.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + service := NewService(relational.NewAuditRepository(database), slog.Default(), 8, 4, time.Second) + if _, err := service.DegradeSummary(ctx, "3h", DegradeThresholds{}); err != ErrInvalidPeriod { + t.Fatalf("error = %v", err) + } +} diff --git a/backend/internal/domain/audit/degrade.go b/backend/internal/domain/audit/degrade.go new file mode 100644 index 00000000..f1b57113 --- /dev/null +++ b/backend/internal/domain/audit/degrade.go @@ -0,0 +1,36 @@ +package audit + +const ( + DegradeClassBurst = "buffered_burst" + DegradeClassSoft = "soft_tps" + DegradeClassHard = "hard_tps" +) + +const ( + DefaultDegradeSoftTPS = 500.0 + DefaultDegradeHardTPS = 1000.0 + DefaultDegradeMinGenMS = int64(1000) + DefaultDegradeMinOutput = int64(32) +) + +// ClassifyOutputSpeed matches the quality-guard panel formula: +// output tokens / (durationMs - firstTokenMs). Short generation windows with +// a soft-or-higher rate are buffered_burst; otherwise the hard and soft +// thresholds apply in that order. +func ClassifyOutputSpeed(outputTokens, firstTokenMS, durationMS int64, softTPS, hardTPS float64, minGenMS int64) (class string, tps float64, genMS int64) { + genMS = durationMS - firstTokenMS + if genMS <= 0 || outputTokens <= 0 { + return "", 0, genMS + } + tps = float64(outputTokens) * 1000 / float64(genMS) + if minGenMS > 0 && genMS < minGenMS && tps >= softTPS { + return DegradeClassBurst, tps, genMS + } + if tps >= hardTPS { + return DegradeClassHard, tps, genMS + } + if tps >= softTPS { + return DegradeClassSoft, tps, genMS + } + return "", tps, genMS +} diff --git a/backend/internal/domain/audit/degrade_test.go b/backend/internal/domain/audit/degrade_test.go new file mode 100644 index 00000000..24ac8c81 --- /dev/null +++ b/backend/internal/domain/audit/degrade_test.go @@ -0,0 +1,27 @@ +package audit + +import "testing" + +func TestClassifyOutputSpeed(t *testing.T) { + tests := []struct { + name string + output, first, duration int64 + soft, hard float64 + minGen int64 + wantClass string + }{ + {name: "hard", output: 2000, first: 200, duration: 1200, soft: 500, hard: 1000, minGen: 1000, wantClass: DegradeClassHard}, + {name: "soft", output: 600, first: 200, duration: 1400, soft: 500, hard: 1000, minGen: 1000, wantClass: DegradeClassSoft}, + {name: "burst short window", output: 200, first: 50, duration: 250, soft: 500, hard: 1000, minGen: 1000, wantClass: DegradeClassBurst}, + {name: "healthy", output: 100, first: 200, duration: 2200, soft: 500, hard: 1000, minGen: 1000, wantClass: ""}, + {name: "zero generation", output: 100, first: 500, duration: 500, soft: 500, hard: 1000, minGen: 1000, wantClass: ""}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + class, _, _ := ClassifyOutputSpeed(test.output, test.first, test.duration, test.soft, test.hard, test.minGen) + if class != test.wantClass { + t.Fatalf("class = %q, want %q", class, test.wantClass) + } + }) + } +} diff --git a/backend/internal/infra/persistence/relational/audit_repository.go b/backend/internal/infra/persistence/relational/audit_repository.go index 820824e3..6b2e8cde 100644 --- a/backend/internal/infra/persistence/relational/audit_repository.go +++ b/backend/internal/infra/persistence/relational/audit_repository.go @@ -683,6 +683,68 @@ func (r *AuditRepository) Summarize(ctx context.Context, input repository.AuditS return result, nil } +const degradeEventScanLimit = 20_000 + +type degradeEventRow struct { + ID uint64 `gorm:"column:id"` + RequestID string `gorm:"column:request_id"` + AccountID *uint64 `gorm:"column:account_id"` + AccountName string `gorm:"column:account_name"` + Email string `gorm:"column:email"` + Enabled *bool `gorm:"column:enabled"` + BuildBotFlagSource int `gorm:"column:build_bot_flag_source"` + EgressNodeID *uint64 `gorm:"column:egress_node_id"` + EgressNodeName string `gorm:"column:egress_node_name"` + OutputTokens int64 `gorm:"column:output_tokens"` + FirstTokenMS int64 `gorm:"column:first_token_ms"` + DurationMS int64 `gorm:"column:duration_ms"` + CreatedAt time.Time `gorm:"column:created_at"` + Model string `gorm:"column:model_upstream_model"` +} + +func (r *AuditRepository) ListDegradeEvents(ctx context.Context, input repository.DegradeEventQuery) ([]repository.DegradeEvent, error) { + limit := input.Limit + if limit <= 0 || limit > degradeEventScanLimit { + limit = degradeEventScanLimit + } + minOut := input.MinOutputTokens + if minOut <= 0 { + minOut = audit.DefaultDegradeMinOutput + } + var rows []degradeEventRow + query := r.db.db.WithContext(ctx).Table("request_audits AS a"). + Select("a.id, a.request_id, a.account_id, a.account_name, a.egress_node_id, a.egress_node_name, a.output_tokens, a.first_token_ms, a.duration_ms, a.created_at, a.model_upstream_model, p.email, p.enabled, COALESCE(c.build_bot_flag_source, 0) AS build_bot_flag_source"). + Joins("LEFT JOIN provider_accounts p ON p.id = a.account_id"). + Joins("LEFT JOIN account_credentials c ON c.account_id = a.account_id"). + Where("a.provider = ?", "grok_build"). + Where("a.streaming = ?", true). + Where(auditSuccessPredicate). + Where("a.output_tokens >= ?", minOut). + Where("a.first_token_ms IS NOT NULL"). + Where("a.duration_ms > a.first_token_ms"). + Where("a.request_id NOT LIKE ?", "quality_%") + if !input.Start.IsZero() { + query = query.Where("a.created_at >= ?", input.Start) + } + if !input.End.IsZero() { + query = query.Where("a.created_at < ?", input.End) + } + if err := query.Order("a.created_at DESC").Limit(limit).Scan(&rows).Error; err != nil { + return nil, err + } + out := make([]repository.DegradeEvent, 0, len(rows)) + for _, row := range rows { + out = append(out, repository.DegradeEvent{ + ID: row.ID, RequestID: row.RequestID, AccountID: row.AccountID, AccountName: row.AccountName, + Email: row.Email, Enabled: row.Enabled, BuildBotFlagSource: row.BuildBotFlagSource, + EgressNodeID: row.EgressNodeID, EgressNodeName: row.EgressNodeName, + OutputTokens: row.OutputTokens, FirstTokenMS: row.FirstTokenMS, DurationMS: row.DurationMS, + CreatedAt: row.CreatedAt, Model: row.Model, + }) + } + return out, nil +} + func applyAuditQuery(query *gorm.DB, search string, start, end time.Time, filter repository.AuditListFilter) *gorm.DB { if value := strings.TrimSpace(search); value != "" { pattern := "%" + strings.ToLower(value) + "%" diff --git a/backend/internal/repository/audit.go b/backend/internal/repository/audit.go index a29e56d0..4be019aa 100644 --- a/backend/internal/repository/audit.go +++ b/backend/internal/repository/audit.go @@ -16,4 +16,30 @@ type AuditRepository interface { ListCursor(ctx context.Context, query AuditCursorQuery) ([]audit.Record, bool, error) Summarize(ctx context.Context, query AuditSummaryQuery) (audit.Summary, error) SumTokensByAccountsSince(ctx context.Context, accountIDs []uint64, since time.Time) (map[uint64]int64, error) + ListDegradeEvents(ctx context.Context, query DegradeEventQuery) ([]DegradeEvent, error) +} + +type DegradeEventQuery struct { + Start time.Time + End time.Time + MinOutputTokens int64 + Limit int +} + +// DegradeEvent is a slim streaming-success audit plus optional account flags. +type DegradeEvent struct { + ID uint64 + RequestID string + AccountID *uint64 + AccountName string + Email string + Enabled *bool + BuildBotFlagSource int + EgressNodeID *uint64 + EgressNodeName string + OutputTokens int64 + FirstTokenMS int64 + DurationMS int64 + CreatedAt time.Time + Model string } diff --git a/backend/internal/transport/http/audit/handler.go b/backend/internal/transport/http/audit/handler.go index d3dd2f0b..ccdb4500 100644 --- a/backend/internal/transport/http/audit/handler.go +++ b/backend/internal/transport/http/audit/handler.go @@ -29,6 +29,7 @@ func NewQualityGuardHandler(service *auditapp.Service, clientKeyID uint64) *Hand func (h *Handler) Register(router *gin.RouterGroup) { router.GET("/request-audits", h.list) router.GET("/request-audits/summary", h.summary) + router.GET("/request-audits/degrade-accounts", h.degradeAccounts) router.GET("/request-audits/:id", h.get) } @@ -333,6 +334,105 @@ func (h *Handler) summary(c *gin.Context) { }) } +func (h *Handler) degradeAccounts(c *gin.Context) { + softTPS, _ := strconv.ParseFloat(c.Query("softTPS"), 64) + hardTPS, _ := strconv.ParseFloat(c.Query("hardTPS"), 64) + result, err := h.service.DegradeSummary(c.Request.Context(), c.DefaultQuery("window", "24h"), auditapp.DegradeThresholds{SoftTPS: softTPS, HardTPS: hardTPS}) + if errors.Is(err, auditapp.ErrInvalidPeriod) { + response.Error(c, http.StatusBadRequest, "invalidAuditPeriod", "window 仅支持 1h、6h、24h、7d") + return + } + if err != nil { + response.Error(c, http.StatusInternalServerError, "auditDegradeFailed", "读取降智账号失败") + return + } + accounts := make([]degradeAccountResponse, 0, len(result.Accounts)) + for _, account := range result.Accounts { + accounts = append(accounts, degradeAccountResponse{ + ID: strconv.FormatUint(account.ID, 10), Name: account.Name, Email: account.Email, Hits: account.Hits, + MaxTPS: account.MaxTPS, Classes: account.Classes, Nodes: account.Nodes, Last: account.Last, + Enabled: account.Enabled, BFS: account.BFS, + }) + } + events := make([]degradeEventResponse, 0, len(result.Events)) + for _, event := range result.Events { + item := degradeEventResponse{ + ID: strconv.FormatUint(event.ID, 10), RequestID: event.RequestID, AccountName: event.AccountName, + NodeName: event.NodeName, OutputTokens: event.OutputTokens, TPS: event.TPS, Class: event.Class, + CreatedAt: event.CreatedAt, Model: event.Model, + } + if event.AccountID != nil { + id := strconv.FormatUint(*event.AccountID, 10) + item.AccountID = &id + } + events = append(events, item) + } + response.Success(c, http.StatusOK, degradeSummaryResponse{ + Window: result.Window, GeneratedAt: result.GeneratedAt, + Thresholds: degradeThresholdsResponse{SoftTPS: result.Thresholds.SoftTPS, HardTPS: result.Thresholds.HardTPS, MinGenMS: result.Thresholds.MinGenMS, MinOut: result.Thresholds.MinOut}, + Totals: degradeTotalsResponse{ + Hits: result.Totals.Hits, Accounts: result.Totals.Accounts, StillEnabled: result.Totals.StillEnabled, + Disabled: result.Totals.Disabled, Hard: result.Totals.Hard, Soft: result.Totals.Soft, Burst: result.Totals.Burst, MaxTPS: result.Totals.MaxTPS, + }, + Series: result.Series, Nodes: result.Nodes, Accounts: accounts, Events: events, + }) +} + +type degradeSummaryResponse struct { + Window string `json:"window"` + GeneratedAt time.Time `json:"generatedAt"` + Thresholds degradeThresholdsResponse `json:"thresholds"` + Totals degradeTotalsResponse `json:"totals"` + Series []auditapp.DegradeBucket `json:"series"` + Nodes []auditapp.DegradeNode `json:"nodes"` + Accounts []degradeAccountResponse `json:"accounts"` + Events []degradeEventResponse `json:"events"` +} + +type degradeThresholdsResponse struct { + SoftTPS float64 `json:"softTPS"` + HardTPS float64 `json:"hardTPS"` + MinGenMS int64 `json:"minGenMs"` + MinOut int64 `json:"minOutputTokens"` +} + +type degradeTotalsResponse struct { + Hits int `json:"hits"` + Accounts int `json:"accounts"` + StillEnabled int `json:"stillEnabled"` + Disabled int `json:"disabled"` + Hard int `json:"hard"` + Soft int `json:"soft"` + Burst int `json:"burst"` + MaxTPS float64 `json:"maxTPS"` +} + +type degradeAccountResponse struct { + ID string `json:"id"` + Name string `json:"name"` + Email string `json:"email"` + Hits int `json:"hits"` + MaxTPS float64 `json:"maxTPS"` + Classes map[string]int `json:"classes"` + Nodes []string `json:"nodes"` + Last time.Time `json:"last"` + Enabled bool `json:"enabled"` + BFS int `json:"bfs"` +} + +type degradeEventResponse struct { + ID string `json:"id"` + RequestID string `json:"requestId"` + AccountID *string `json:"accountId,omitempty"` + AccountName string `json:"accountName"` + NodeName string `json:"nodeName"` + OutputTokens int64 `json:"outputTokens"` + TPS float64 `json:"tps"` + Class string `json:"class"` + CreatedAt time.Time `json:"createdAt"` + Model string `json:"model"` +} + func newListFilter(c *gin.Context) auditapp.ListFilter { return auditapp.ListFilter{ Model: c.Query("model"), Status: c.Query("status"), Mode: c.Query("mode"), diff --git a/backend/internal/transport/http/audit/handler_test.go b/backend/internal/transport/http/audit/handler_test.go index 0a9a6822..7e139f09 100644 --- a/backend/internal/transport/http/audit/handler_test.go +++ b/backend/internal/transport/http/audit/handler_test.go @@ -163,3 +163,40 @@ func TestAuditResponseExplainsBillingWithoutChangingStoredTotal(t *testing.T) { t.Fatalf("historical billing = %#v", historical.Billing) } } + +func TestDegradeAccountsListsHardHitsAndRejectsUnknownWindow(t *testing.T) { + gin.SetMode(gin.TestMode) + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-handler.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + repo := relational.NewAuditRepository(database) + now := time.Now().UTC() + first := int64(100) + accountID := uint64(11) + if err := repo.Create(ctx, auditdomain.Record{ + RequestID: "degrade-hard", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", AccountID: &accountID, AccountName: "noisy", + EgressNodeName: "edge-1", StatusCode: 200, Streaming: true, OutputTokens: 2000, FirstTokenMS: &first, DurationMS: 1100, CreatedAt: now.Add(-time.Minute), + }); err != nil { + t.Fatal(err) + } + router := gin.New() + NewHandler(auditapp.NewService(repo, slog.Default(), 8, 4, time.Second)).Register(router.Group("/api/admin/v1")) + + ok := httptest.NewRecorder() + router.ServeHTTP(ok, httptest.NewRequest(http.MethodGet, "/api/admin/v1/request-audits/degrade-accounts?window=24h&softTPS=500&hardTPS=1000", nil)) + if ok.Code != http.StatusOK || !strings.Contains(ok.Body.String(), `"id":"11"`) || !strings.Contains(ok.Body.String(), `"hard":1`) { + t.Fatalf("status=%d body=%s", ok.Code, ok.Body.String()) + } + + bad := httptest.NewRecorder() + router.ServeHTTP(bad, httptest.NewRequest(http.MethodGet, "/api/admin/v1/request-audits/degrade-accounts?window=3h", nil)) + if bad.Code != http.StatusBadRequest || !strings.Contains(bad.Body.String(), "invalidAuditPeriod") { + t.Fatalf("bad window status=%d body=%s", bad.Code, bad.Body.String()) + } +} diff --git a/frontend/src/features/quality-guard/degrade-accounts-panel.tsx b/frontend/src/features/quality-guard/degrade-accounts-panel.tsx new file mode 100644 index 00000000..e8d2da7b --- /dev/null +++ b/frontend/src/features/quality-guard/degrade-accounts-panel.tsx @@ -0,0 +1,262 @@ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { AlertTriangle, Gauge, PowerOff, RefreshCw, Search, Users } from "lucide-react"; +import { useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { toast } from "sonner"; + +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Checkbox } from "@/components/ui/checkbox"; +import { Input } from "@/components/ui/input"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; +import { updateAccountsEnabled } from "@/features/accounts/accounts-api"; +import { getDegradeAccounts, type DegradeAccountDTO, type DegradeClass, type DegradeSummaryDTO, type DegradeWindow } from "@/features/quality-guard/quality-guard-api"; +import { EmptyState, ErrorState } from "@/shared/components/data-state"; +import { cn } from "@/shared/lib/cn"; +import { formatCompactDateTime } from "@/shared/lib/format"; + +const MUTE_TOAST_ID = "quality-guard-degrade-mute"; + +export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; hardTPS?: number }) { + const { t, i18n } = useTranslation(); + const queryClient = useQueryClient(); + const [window, setWindow] = useState("24h"); + const [search, setSearch] = useState(""); + const [status, setStatus] = useState<"all" | "on" | "off">("all"); + const [cls, setCls] = useState<"all" | DegradeClass>("all"); + const [hitsMin, setHitsMin] = useState(1); + const [selected, setSelected] = useState>(() => new Set()); + + const query = useQuery({ + queryKey: ["quality-guard-degrade-accounts", window, softTPS, hardTPS], + queryFn: () => getDegradeAccounts({ window, softTPS, hardTPS }), + refetchInterval: 15_000, + }); + + const data = query.data; + const rows = useMemo(() => filterAccounts(data, { search, status, cls, hitsMin }), [data, search, status, cls, hitsMin]); + const selectable = rows.filter((account) => account.enabled); + const selectedEnabled = selectable.filter((account) => selected.has(account.id)); + const allSelected = selectable.length > 0 && selectedEnabled.length === selectable.length; + + const muteMutation = useMutation({ + mutationFn: (ids: string[]) => updateAccountsEnabled(ids, false, "grok_build"), + onMutate: () => toast.loading(t("qualityGuard.degrade.muting"), { id: MUTE_TOAST_ID }), + onSuccess: (_, ids) => { + setSelected(new Set()); + void queryClient.invalidateQueries({ queryKey: ["quality-guard-degrade-accounts"] }); + void queryClient.invalidateQueries({ queryKey: ["accounts"] }); + toast.success(t("qualityGuard.degrade.muted", { count: ids.length }), { id: MUTE_TOAST_ID }); + }, + onError: (error) => toast.error(error instanceof Error ? error.message : t("qualityGuard.degrade.muteFailed"), { id: MUTE_TOAST_ID }), + }); + + const toggleAll = (checked: boolean) => { + setSelected((current) => { + const next = new Set(current); + selectable.forEach((account) => { + if (checked) next.add(account.id); + else next.delete(account.id); + }); + return next; + }); + }; + + if (query.isError && !data) return void query.refetch()} />; + if (!data) return null; + + return ( +
+
+ + + + = data.thresholds.hardTPS ? "bad" : undefined} /> +
+ +
+ + +
+ +
+
+
+

{t("qualityGuard.degrade.accountsTitle")}

+

+ {hitsMin > 1 + ? t("qualityGuard.degrade.accountsHintFiltered", { shown: rows.length, total: data.accounts.length, min: hitsMin }) + : t("qualityGuard.degrade.accountsHint", { shown: rows.length, total: data.accounts.length })} +

+
+
+
+ + setSearch(event.target.value)} placeholder={t("qualityGuard.degrade.search")} /> +
+ { setSelected(new Set()); setWindow(value as DegradeWindow); }} items={[["1h", t("qualityGuard.degrade.windows.1h")], ["6h", t("qualityGuard.degrade.windows.6h")], ["24h", t("qualityGuard.degrade.windows.24h")], ["7d", t("qualityGuard.degrade.windows.7d")]]} /> + setStatus(value as "all" | "on" | "off")} items={[["all", t("qualityGuard.degrade.statusAll")], ["on", t("qualityGuard.degrade.statusOn")], ["off", t("qualityGuard.degrade.statusOff")]]} /> + setCls(value as "all" | DegradeClass)} items={[["all", t("qualityGuard.degrade.classAll")], ["buffered_burst", "burst"], ["soft_tps", "soft"], ["hard_tps", "hard"]]} /> + setHitsMin(Number(value))} items={[["1", t("qualityGuard.degrade.hitsAll")], ["2", t("qualityGuard.degrade.hitsMin", { count: 2 })], ["3", t("qualityGuard.degrade.hitsMin", { count: 3 })], ["5", t("qualityGuard.degrade.hitsMin", { count: 5 })], ["10", t("qualityGuard.degrade.hitsMin", { count: 10 })]]} /> + + +
+
+
+ + + + 0 ? "indeterminate" : false} disabled={selectable.length === 0} onCheckedChange={(checked) => toggleAll(checked === true)} aria-label={t("common.selectPage")} /> + {t("qualityGuard.degrade.account")} + {t("qualityGuard.degrade.status")} + {t("qualityGuard.degrade.hitCount")} + {t("qualityGuard.outputTPS")} + {t("qualityGuard.degrade.class")} + {t("qualityGuard.node")} + {t("qualityGuard.lastObserved")} + + + + {rows.length === 0 ? ( + + ) : rows.map((account) => ( + + setSelected((current) => { + const next = new Set(current); + if (checked === true) next.add(account.id); + else next.delete(account.id); + return next; + })} /> + +
#{account.id}
+
{account.email || account.name || "-"}
+
+ + {account.enabled ? {t("qualityGuard.degrade.scheduling")} : {t("qualityGuard.degrade.mutedStatus")}} + {account.bfs ? bfs {account.bfs} : null} + + {account.hits} + = data.thresholds.hardTPS ? "text-destructive" : account.maxTPS >= data.thresholds.softTPS ? "text-amber-600 dark:text-amber-400" : "")}>{account.maxTPS} + {classSummary(account.classes)} + {account.nodes.join(" · ") || "-"} + {account.last ? formatCompactDateTime(account.last, i18n.language) : "-"} +
+ ))} +
+
+
+
+ +
+
+

{t("qualityGuard.degrade.events")}

+

{t("qualityGuard.degrade.eventsHelp")}

+
+
+ {data.events.length === 0 ? : data.events.map((event) => ( +
+
{formatCompactDateTime(event.createdAt, i18n.language)}
+
#{event.accountId ?? "-"} {event.accountName} · {event.nodeName} · out {event.outputTokens} · {event.requestId}
+
{classBadge(event.class)}{event.tps}
+
+ ))} +
+
+
+ ); +} + +function filterAccounts(data: DegradeSummaryDTO | undefined, filters: { search: string; status: "all" | "on" | "off"; cls: "all" | DegradeClass; hitsMin: number }) { + if (!data) return []; + const search = filters.search.trim().toLowerCase(); + return data.accounts.filter((account) => { + if (account.hits < filters.hitsMin) return false; + if (filters.status === "on" && !account.enabled) return false; + if (filters.status === "off" && account.enabled) return false; + if (filters.cls !== "all" && (account.classes[filters.cls] ?? 0) <= 0) return false; + if (search && !`${account.id} ${account.email} ${account.name}`.toLowerCase().includes(search)) return false; + return true; + }); +} + +function classSummary(classes: DegradeAccountDTO["classes"]) { + return [ + classes.buffered_burst ? `burst ${classes.buffered_burst}` : "", + classes.soft_tps ? `soft ${classes.soft_tps}` : "", + classes.hard_tps ? `hard ${classes.hard_tps}` : "", + ].filter(Boolean).join(" · ") || "-"; +} + +function classBadge(cls: DegradeClass) { + if (cls === "hard_tps") return hard; + if (cls === "buffered_burst") return burst; + return soft; +} + +function FilterSelect({ value, onChange, items }: { value: string; onChange: (value: string) => void; items: string[][] }) { + return ( + + ); +} + +function Metric({ icon: Icon, label, value, detail, tone }: { icon: typeof AlertTriangle; label: string; value: string; detail: string; tone?: "good" | "bad" }) { + return ( +
+ +
+

{label}

+

{value}

+

{detail}

+
+
+ ); +} + +function SeriesChart({ series, empty, title }: { series: DegradeSummaryDTO["series"]; empty: string; title: string }) { + const max = Math.max(1, ...series.map((item) => item.count)); + return ( +
+

{title}

+
+ {series.length === 0 ?

{empty}

: series.map((item) => ( +
+
0 && item.severe >= item.count * 0.5 ? "bg-destructive" : "bg-amber-500/80")} style={{ height: `${Math.max(2, Math.round(item.count / max * 100))}%` }} /> +
{item.label}
+
+ ))} +
+
+ ); +} + +function NodeList({ nodes, empty, title }: { nodes: DegradeSummaryDTO["nodes"]; empty: string; title: string }) { + const max = Math.max(1, ...nodes.map((node) => node.hits)); + return ( +
+

{title}

+
+ {nodes.length === 0 ?

{empty}

: nodes.map((node) => ( +
+
+
{node.name}
+
+
+ {node.hits} / {node.accounts} + {node.maxTPS} +
+ ))} +
+
+ ); +} diff --git a/frontend/src/features/quality-guard/quality-guard-api.ts b/frontend/src/features/quality-guard/quality-guard-api.ts index 19223564..0ddffa14 100644 --- a/frontend/src/features/quality-guard/quality-guard-api.ts +++ b/frontend/src/features/quality-guard/quality-guard-api.ts @@ -1,5 +1,5 @@ import { apiRequest } from "@/shared/api/client"; -import { createObjectDecoder, hasShape, isArrayOf, isBoolean, isNumber, isOneOf, isOptional, isRecordOf, isString } from "@/shared/api/decoder"; +import { createObjectDecoder, hasShape, isArrayOf, isBoolean, isNumber, isObject, isOneOf, isOptional, isRecordOf, isString } from "@/shared/api/decoder"; export type QualityGuardPolicy = { mode: "active" | "passive" | "hybrid"; @@ -151,3 +151,70 @@ export function runQualityTest(nodeId: string, status: QualityGuardStatus): Prom export function updateQualityGuardPolicy(policy: QualityGuardPolicy): Promise<{ saved: boolean }> { return apiRequest("/api/admin/v1/egress-quality-guard/config", { method: "PUT", body: policy }, createObjectDecoder("quality guard config update", { saved: isBoolean })); } + +export type DegradeWindow = "1h" | "6h" | "24h" | "7d"; +export type DegradeClass = "buffered_burst" | "soft_tps" | "hard_tps"; + +export type DegradeAccountDTO = { + id: string; + name: string; + email: string; + hits: number; + maxTPS: number; + classes: Partial>; + nodes: string[]; + last: string; + enabled: boolean; + bfs: number; +}; + +export type DegradeEventDTO = { + id: string; + requestId: string; + accountId?: string; + accountName: string; + nodeName: string; + outputTokens: number; + tps: number; + class: DegradeClass; + createdAt: string; + model: string; +}; + +export type DegradeSummaryDTO = { + window: DegradeWindow; + generatedAt: string; + thresholds: { softTPS: number; hardTPS: number; minGenMs: number; minOutputTokens: number }; + totals: { hits: number; accounts: number; stillEnabled: number; disabled: number; hard: number; soft: number; burst: number; maxTPS: number }; + series: { label: string; count: number; severe: number }[]; + nodes: { name: string; hits: number; accounts: number; maxTPS: number }[]; + accounts: DegradeAccountDTO[]; + events: DegradeEventDTO[]; +}; + +const degradeClassValidator = isOneOf("buffered_burst", "soft_tps", "hard_tps"); + +const decodeDegradeSummary = createObjectDecoder("degrade accounts", { + window: isOneOf("1h", "6h", "24h", "7d"), + generatedAt: isString, + thresholds: hasShape({ softTPS: isNumber, hardTPS: isNumber, minGenMs: isNumber, minOutputTokens: isNumber }), + totals: hasShape({ hits: isNumber, accounts: isNumber, stillEnabled: isNumber, disabled: isNumber, hard: isNumber, soft: isNumber, burst: isNumber, maxTPS: isNumber }), + series: isArrayOf(hasShape({ label: isString, count: isNumber, severe: isNumber })), + nodes: isArrayOf(hasShape({ name: isString, hits: isNumber, accounts: isNumber, maxTPS: isNumber })), + accounts: isArrayOf(hasShape({ + id: isString, name: isString, email: isString, hits: isNumber, maxTPS: isNumber, + classes: isObject, nodes: isArrayOf(isString), last: isString, enabled: isBoolean, bfs: isNumber, + })), + events: isArrayOf(hasShape({ + id: isString, requestId: isString, accountId: isOptional(isString), accountName: isString, + nodeName: isString, outputTokens: isNumber, tps: isNumber, class: degradeClassValidator, + createdAt: isString, model: isString, + })), +}); + +export function getDegradeAccounts(input: { window: DegradeWindow; softTPS?: number; hardTPS?: number }): Promise { + const query = new URLSearchParams({ window: input.window }); + if (input.softTPS) query.set("softTPS", String(input.softTPS)); + if (input.hardTPS) query.set("hardTPS", String(input.hardTPS)); + return apiRequest(`/api/admin/v1/request-audits/degrade-accounts?${query}`, {}, decodeDegradeSummary); +} diff --git a/frontend/src/features/quality-guard/quality-guard-page.tsx b/frontend/src/features/quality-guard/quality-guard-page.tsx index 65551e62..ce682c16 100644 --- a/frontend/src/features/quality-guard/quality-guard-page.tsx +++ b/frontend/src/features/quality-guard/quality-guard-page.tsx @@ -18,6 +18,8 @@ import { Label } from "@/components/ui/label"; import { Spinner } from "@/components/ui/spinner"; import { Switch } from "@/components/ui/switch"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { DegradeAccountsPanel } from "@/features/quality-guard/degrade-accounts-panel"; import { getQualityGuardStatus, runQualityTest, updateQualityGuardPolicy, type QualityGuardEvent, type QualityGuardNodeState, type QualityGuardPolicy, type QualityGuardStatistics, type QualityGuardStatus, type QualityTestResult } from "@/features/quality-guard/quality-guard-api"; import { createEgressNode, deleteEgressNodes, listAllEgressNodes, updateEgressNode, updateEgressNodesEnabled, type EgressNodeDTO, type EgressNodeInput } from "@/features/settings/settings-api"; import { ErrorState } from "@/shared/components/data-state"; @@ -159,6 +161,15 @@ export function QualityGuardPage() { )} /> + + + {t("qualityGuard.nodesTab")} + {t("qualityGuard.degrade.tab")} + + + + + {!status?.available ? : ( <>
@@ -224,6 +235,8 @@ export function QualityGuardPage() { )} + + ); } diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index bef6f887..88fea127 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -443,6 +443,22 @@ const resources = { reasons: { unknown: "未记录原因", hard_tps: "超过硬阈值", soft_tps: "超过软阈值", buffered_burst: "短窗口输出突增,等待原 IP 复测", passive_hard_tps: "请求速度超过硬阈值", passive_soft_tps: "请求速度连续超过软阈值", quality_probe_healthy: "模型质量检测恢复正常", expected_marker_missing: "响应标记缺失", insufficient_output_tokens: "输出 Token 不足", insufficient_visible_tokens: "可见 Token 不足", insufficient_generation_window: "有效生成窗口不足", probe_errors: "主动检测连续失败", probe_no_account: "暂无可调度账号,已延后复测", recovery_probe_error: "恢复检测失败", rotation_error: "更换 IP 失败" }, policy: "当前策略", editPolicy: "编辑策略", editPolicyTitle: "编辑质量守护策略", editPolicyDescription: "保存后由守护进程热加载,无需重启服务。", restoreDefaults: "恢复默认值", policySaved: "策略已保存,正在热加载", invalidPolicyValue: "数值超出允许范围", softThresholdMustBeLower: "软阈值必须低于硬阈值", activeIntervalSeconds: "主动检测间隔(秒)", passiveIntervalSeconds: "被动审计间隔(秒)", consecutiveSoft: "软阈值连续次数", consecutiveErrors: "检测错误连续次数", quarantineSeconds: "隔离时长(秒)", softThreshold: "软阈值", hardThreshold: "硬阈值", activeInterval: "主动间隔", passiveInterval: "审计间隔", quarantineDuration: "隔离时长", minimumNodes: "最少保留节点", unavailable: "质量守护尚未连接", unavailableHelp: "在 config.yaml 中启用 qualityGuard,并启动 quality-guard Compose profile 后,这里会显示实时状态。", testing: "正在检测节点质量", testComplete: "检测完成:{{speed}}", testFailed: "质量检测暂不可用,请稍后重试", + nodesTab: "节点质量", + degrade: { + tab: "降智账号", overview: "降智账号概览", series: "降智时序", nodes: "按出口节点", + hits: "降智次数", hitsHelp: "burst {{burst}} · soft {{soft}} · hard {{hard}}", + accounts: "涉及账号", accountsHelp: "窗口内去重", stillEnabled: "仍在调度", stillEnabledHelp: "漏网,可批量禁", + maxTPS: "峰值 TPS", maxTPSHelp: "单次请求最高", + accountsTitle: "降智账号", accountsHint: "显示 {{shown}} / {{total}}", accountsHintFiltered: "显示 {{shown}} / {{total}} · 命中≥{{min}}", + search: "搜邮箱 / ID", statusAll: "全部状态", statusOn: "仍在调度", statusOff: "已禁言", + classAll: "全部类型", class: "类型", account: "账号", status: "状态", hitCount: "命中", + hitsAll: "全部次数", hitsMin: "命中 ≥ {{count}}", + windows: { "1h": "近 1 小时", "6h": "近 6 小时", "24h": "近 24 小时", "7d": "近 7 天" }, + muteSelected: "禁掉所选", muteSelectedCount: "禁掉所选 ({{count}})", muteConfirm: "确认禁掉 {{count}} 个仍在调度的降智账号?", muting: "正在禁言账号", muted: "已禁言 {{count}} 个账号", muteFailed: "禁言失败", + scheduling: "调度中", mutedStatus: "已禁", + events: "最近事件", eventsHelp: "用户请求,不含 quality-test 探针", + noHits: "这个窗口没有降智请求", noNodes: "无节点数据", noAccounts: "没有匹配账号", noEvents: "无事件", + }, refreshNodes: "刷新节点", nodeEnabled: "节点已启用", nodeDisabled: "节点已停用", nodesEnabled: "所选节点已启用", nodesDisabled: "所选节点已停用", enableNode: "启用节点 {{name}}", disableNode: "停用节点 {{name}}", nodeEditorDescription: "管理质量守护使用的 Grok Build 出口。代理地址仅写入;编辑时留空会保留现有配置。", nodeCapacityHelp: "最多可绑定的账号数,0 表示不限制。", deleteNodeTitle: "删除代理节点?", deleteNodeDescription: "将永久删除节点“{{name}}”。此操作无法撤销。", deleteNodesTitle: "删除所选 {{count}} 个节点?", deleteNodesDescription: "所选代理节点将被永久删除,此操作无法撤销。", }, @@ -1335,7 +1351,24 @@ const resources = { 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" } }, auth: { title: "Admin sign in", productTitle: "Lightweight API gateway", subtitle: "Manage upstream accounts, model routes, and client access.", username: "Username", password: "Password", usernameRequired: "Enter your username", passwordRequired: "Enter your password", signIn: "Sign in", signingIn: "Signing in", signOut: "Sign out", changePassword: "Change password", currentPassword: "Current password", newPassword: "New password", passwordUpdated: "Password updated. Sign in again.", sessionUnavailable: "Unable to restore the session", sessionUnavailableDescription: "The service may be temporarily unavailable. Your session was not cleared; please retry shortly.", retrySession: "Retry" }, shell: { appearance: "Appearance", dark: "Dark", light: "Light", system: "System", language: "Language", navigation: "Navigation", openNavigation: "Open navigation" }, - qualityGuard: { title: "Quality guard", description: "Monitor Grok egress quality and quarantine anomalous nodes automatically.", overview: "Quality guard overview", serviceStatus: "Guard service", running: "Running", stale: "Status stale", mode: "Detection mode", availableNodes: "Enabled nodes", quarantinedNodes: "Quarantined", modes: { active: "Active probes", passive: "Passive audits", hybrid: "Hybrid" }, nodes: "Node quality", nodesHelp: "Speed matches the grok2api panel: output tokens include reasoning tokens. Passive anomalies only trigger an active confirmation. Strike counts are passive / active / errors.", updatedAt: "Updated {{time}}", node: "Node", state: "State", outputTPS: "Panel output speed", firstToken: "First token", source: "Source", strikes: "Strikes", lastObserved: "Last observed", test: "Test", sources: { active: "Active probe", passive: "Request audit" }, quarantined: "Quarantined", fixedFallback: "Fixed fallback (protected)", suspect: "Suspect", healthy: "Healthy", pending: "Pending", probeFailed: "Probe failed", events: "Recent events", noEvents: "No anomaly or recovery events", eventTypes: { node_quarantined: "Node quarantined", node_restored: "Node restored", node_rotated: "Node IP rotated", passive_audit_anomaly: "Anomalous request detected" }, statistics: "Automatic detection statistics", statisticsSince: "Accumulated since {{time}}. Manual tests are excluded.", statisticsChecks: "Valid checks", statisticsChecksHelp: "Active probes and valid passive audits", statisticsActive: "Active probes", statisticsActiveDetail: "Healthy {{healthy}}, errors {{errors}}", statisticsPassive: "Passive audits", statisticsPassiveDetail: "Healthy {{healthy}}, from real requests", statisticsTokens: "Active output tokens", statisticsTokensHelp: "Includes reasoning tokens; not proxy traffic", statisticsAnomalies: "Anomaly hits", statisticsAnomalyDetail: "Soft {{soft}}, hard {{hard}}", statisticsQuarantines: "Quarantines applied", statisticsActionDetail: "Restored {{restored}}, protected {{suppressed}}", reasons: { unknown: "No reason recorded", hard_tps: "Hard threshold exceeded", soft_tps: "Soft threshold exceeded", buffered_burst: "Short-window output burst; retesting the same IP", passive_hard_tps: "Request exceeded hard threshold", passive_soft_tps: "Requests repeatedly exceeded soft threshold", quality_probe_healthy: "Model quality probe recovered", expected_marker_missing: "Expected marker missing", insufficient_output_tokens: "Too few output tokens", insufficient_visible_tokens: "Too few visible tokens", insufficient_generation_window: "Generation window too short", probe_errors: "Repeated probe errors", probe_no_account: "No schedulable probe account; retry deferred", recovery_probe_error: "Recovery probe failed", rotation_error: "IP rotation failed" }, policy: "Current policy", editPolicy: "Edit policy", editPolicyTitle: "Edit quality guard policy", editPolicyDescription: "The guard hot-reloads saved changes without a service restart.", restoreDefaults: "Restore defaults", policySaved: "Policy saved and queued for hot reload", invalidPolicyValue: "Value is outside the allowed range", softThresholdMustBeLower: "The soft threshold must be lower than the hard threshold", activeIntervalSeconds: "Active interval (seconds)", passiveIntervalSeconds: "Passive interval (seconds)", consecutiveSoft: "Consecutive soft strikes", consecutiveErrors: "Consecutive probe errors", quarantineSeconds: "Quarantine (seconds)", softThreshold: "Soft threshold", hardThreshold: "Hard threshold", activeInterval: "Active interval", passiveInterval: "Audit interval", quarantineDuration: "Quarantine", minimumNodes: "Minimum nodes", unavailable: "Quality guard is not connected", unavailableHelp: "Enable qualityGuard in config.yaml and start the quality-guard Compose profile to display live status here.", testing: "Testing node quality", testComplete: "Test complete: {{speed}}", testFailed: "Quality test is temporarily unavailable. Try again shortly.", refreshNodes: "Refresh nodes", nodeEnabled: "Node enabled", nodeDisabled: "Node disabled", nodesEnabled: "Selected nodes enabled", nodesDisabled: "Selected nodes disabled", enableNode: "Enable node {{name}}", disableNode: "Disable node {{name}}", nodeEditorDescription: "Manage Grok Build egress used by the quality guard. Proxy URLs are write-only; leave the field blank while editing to keep the current value.", nodeCapacityHelp: "Maximum number of bound accounts; 0 means unlimited.", deleteNodeTitle: "Delete proxy node?", deleteNodeDescription: "Node “{{name}}” will be permanently deleted. This action cannot be undone.", deleteNodesTitle: "Delete {{count}} selected nodes?", deleteNodesDescription: "The selected proxy nodes will be permanently deleted. This action cannot be undone." }, + qualityGuard: { title: "Quality guard", description: "Monitor Grok egress quality and quarantine anomalous nodes automatically.", overview: "Quality guard overview", serviceStatus: "Guard service", running: "Running", stale: "Status stale", mode: "Detection mode", availableNodes: "Enabled nodes", quarantinedNodes: "Quarantined", modes: { active: "Active probes", passive: "Passive audits", hybrid: "Hybrid" }, nodes: "Node quality", nodesHelp: "Speed matches the grok2api panel: output tokens include reasoning tokens. Passive anomalies only trigger an active confirmation. Strike counts are passive / active / errors.", updatedAt: "Updated {{time}}", node: "Node", state: "State", outputTPS: "Panel output speed", firstToken: "First token", source: "Source", strikes: "Strikes", lastObserved: "Last observed", test: "Test", sources: { active: "Active probe", passive: "Request audit" }, quarantined: "Quarantined", fixedFallback: "Fixed fallback (protected)", suspect: "Suspect", healthy: "Healthy", pending: "Pending", probeFailed: "Probe failed", events: "Recent events", noEvents: "No anomaly or recovery events", eventTypes: { node_quarantined: "Node quarantined", node_restored: "Node restored", node_rotated: "Node IP rotated", passive_audit_anomaly: "Anomalous request detected" }, statistics: "Automatic detection statistics", statisticsSince: "Accumulated since {{time}}. Manual tests are excluded.", statisticsChecks: "Valid checks", statisticsChecksHelp: "Active probes and valid passive audits", statisticsActive: "Active probes", statisticsActiveDetail: "Healthy {{healthy}}, errors {{errors}}", statisticsPassive: "Passive audits", statisticsPassiveDetail: "Healthy {{healthy}}, from real requests", statisticsTokens: "Active output tokens", statisticsTokensHelp: "Includes reasoning tokens; not proxy traffic", statisticsAnomalies: "Anomaly hits", statisticsAnomalyDetail: "Soft {{soft}}, hard {{hard}}", statisticsQuarantines: "Quarantines applied", statisticsActionDetail: "Restored {{restored}}, protected {{suppressed}}", reasons: { unknown: "No reason recorded", hard_tps: "Hard threshold exceeded", soft_tps: "Soft threshold exceeded", buffered_burst: "Short-window output burst; retesting the same IP", passive_hard_tps: "Request exceeded hard threshold", passive_soft_tps: "Requests repeatedly exceeded soft threshold", quality_probe_healthy: "Model quality probe recovered", expected_marker_missing: "Expected marker missing", insufficient_output_tokens: "Too few output tokens", insufficient_visible_tokens: "Too few visible tokens", insufficient_generation_window: "Generation window too short", probe_errors: "Repeated probe errors", probe_no_account: "No schedulable probe account; retry deferred", recovery_probe_error: "Recovery probe failed", rotation_error: "IP rotation failed" }, policy: "Current policy", editPolicy: "Edit policy", editPolicyTitle: "Edit quality guard policy", editPolicyDescription: "The guard hot-reloads saved changes without a service restart.", restoreDefaults: "Restore defaults", policySaved: "Policy saved and queued for hot reload", invalidPolicyValue: "Value is outside the allowed range", softThresholdMustBeLower: "The soft threshold must be lower than the hard threshold", activeIntervalSeconds: "Active interval (seconds)", passiveIntervalSeconds: "Passive interval (seconds)", consecutiveSoft: "Consecutive soft strikes", consecutiveErrors: "Consecutive probe errors", quarantineSeconds: "Quarantine (seconds)", softThreshold: "Soft threshold", hardThreshold: "Hard threshold", activeInterval: "Active interval", passiveInterval: "Audit interval", quarantineDuration: "Quarantine", minimumNodes: "Minimum nodes", unavailable: "Quality guard is not connected", unavailableHelp: "Enable qualityGuard in config.yaml and start the quality-guard Compose profile to display live status here.", testing: "Testing node quality", testComplete: "Test complete: {{speed}}", testFailed: "Quality test is temporarily unavailable. Try again shortly.", refreshNodes: "Refresh nodes", nodeEnabled: "Node enabled", nodeDisabled: "Node disabled", nodesEnabled: "Selected nodes enabled", nodesDisabled: "Selected nodes disabled", enableNode: "Enable node {{name}}", disableNode: "Disable node {{name}}", nodeEditorDescription: "Manage Grok Build egress used by the quality guard. Proxy URLs are write-only; leave the field blank while editing to keep the current value.", nodeCapacityHelp: "Maximum number of bound accounts; 0 means unlimited.", deleteNodeTitle: "Delete proxy node?", deleteNodeDescription: "Node “{{name}}” will be permanently deleted. This action cannot be undone.", deleteNodesTitle: "Delete {{count}} selected nodes?", deleteNodesDescription: "The selected proxy nodes will be permanently deleted. This action cannot be undone.", + nodesTab: "Node quality", + degrade: { + tab: "Degraded accounts", overview: "Degraded account overview", series: "Degrade timeline", nodes: "By egress node", + hits: "Degrade hits", hitsHelp: "burst {{burst}} · soft {{soft}} · hard {{hard}}", + accounts: "Accounts", accountsHelp: "Unique in this window", stillEnabled: "Still scheduled", stillEnabledHelp: "Still enabled; can be muted in bulk", + maxTPS: "Peak TPS", maxTPSHelp: "Highest single request", + accountsTitle: "Degraded accounts", accountsHint: "Showing {{shown}} / {{total}}", accountsHintFiltered: "Showing {{shown}} / {{total}} · hits ≥ {{min}}", + search: "Search email / ID", statusAll: "All statuses", statusOn: "Still scheduled", statusOff: "Muted", + classAll: "All classes", class: "Class", account: "Account", status: "Status", hitCount: "Hits", + hitsAll: "Any hit count", hitsMin: "Hits ≥ {{count}}", + windows: { "1h": "Last 1 hour", "6h": "Last 6 hours", "24h": "Last 24 hours", "7d": "Last 7 days" }, + muteSelected: "Mute selected", muteSelectedCount: "Mute selected ({{count}})", muteConfirm: "Mute {{count}} still-scheduled degraded accounts?", muting: "Muting accounts", muted: "Muted {{count}} accounts", muteFailed: "Failed to mute accounts", + scheduling: "Scheduled", mutedStatus: "Muted", + events: "Recent events", eventsHelp: "User requests; quality-test probes are excluded", + noHits: "No degrade requests in this window", noNodes: "No node data", noAccounts: "No matching accounts", noEvents: "No events", + }, + }, accountQuotaReset: { action: "Reset quota", description: "This clears only local waiting-reset and model quota blocks. It does not change upstream Billing or audit history. Accounts that remain exhausted will be marked again by real traffic.", completed: "Reset local quota state for {{reset}} accounts" }, 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" }, From 277f2879bd3f9a1606766335f3375a65a71c561f Mon Sep 17 00:00:00 2001 From: lij768423-svg Date: Thu, 13 Aug 2026 15:21:26 +0800 Subject: [PATCH 12/48] fix: polish degraded-account panel controls Allow selecting muted accounts, unmute them in bulk, keep status badges on one line, and grow the timeline bars from the bottom of the card. --- .../quality-guard/degrade-accounts-panel.tsx | 110 +++++++++++++----- frontend/src/shared/i18n/index.ts | 6 +- 2 files changed, 82 insertions(+), 34 deletions(-) diff --git a/frontend/src/features/quality-guard/degrade-accounts-panel.tsx b/frontend/src/features/quality-guard/degrade-accounts-panel.tsx index e8d2da7b..66dd821c 100644 --- a/frontend/src/features/quality-guard/degrade-accounts-panel.tsx +++ b/frontend/src/features/quality-guard/degrade-accounts-panel.tsx @@ -1,5 +1,5 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { AlertTriangle, Gauge, PowerOff, RefreshCw, Search, Users } from "lucide-react"; +import { AlertTriangle, Gauge, Power, PowerOff, RefreshCw, Search, Users } from "lucide-react"; import { useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; @@ -21,7 +21,7 @@ const MUTE_TOAST_ID = "quality-guard-degrade-mute"; export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; hardTPS?: number }) { const { t, i18n } = useTranslation(); const queryClient = useQueryClient(); - const [window, setWindow] = useState("24h"); + const [period, setPeriod] = useState("24h"); const [search, setSearch] = useState(""); const [status, setStatus] = useState<"all" | "on" | "off">("all"); const [cls, setCls] = useState<"all" | DegradeClass>("all"); @@ -29,16 +29,18 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h const [selected, setSelected] = useState>(() => new Set()); const query = useQuery({ - queryKey: ["quality-guard-degrade-accounts", window, softTPS, hardTPS], - queryFn: () => getDegradeAccounts({ window, softTPS, hardTPS }), + queryKey: ["quality-guard-degrade-accounts", period, softTPS, hardTPS], + queryFn: () => getDegradeAccounts({ window: period, softTPS, hardTPS }), refetchInterval: 15_000, }); const data = query.data; const rows = useMemo(() => filterAccounts(data, { search, status, cls, hitsMin }), [data, search, status, cls, hitsMin]); - const selectable = rows.filter((account) => account.enabled); - const selectedEnabled = selectable.filter((account) => selected.has(account.id)); - const allSelected = selectable.length > 0 && selectedEnabled.length === selectable.length; + const selectable = rows; + const selectedRows = selectable.filter((account) => selected.has(account.id)); + const selectedEnabled = selectedRows.filter((account) => account.enabled); + const selectedMuted = selectedRows.filter((account) => !account.enabled); + const allSelected = selectable.length > 0 && selectedRows.length === selectable.length; const muteMutation = useMutation({ mutationFn: (ids: string[]) => updateAccountsEnabled(ids, false, "grok_build"), @@ -51,6 +53,18 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h }, onError: (error) => toast.error(error instanceof Error ? error.message : t("qualityGuard.degrade.muteFailed"), { id: MUTE_TOAST_ID }), }); + const unmuteMutation = useMutation({ + mutationFn: (ids: string[]) => updateAccountsEnabled(ids, true, "grok_build"), + onMutate: () => toast.loading(t("qualityGuard.degrade.unmuting"), { id: MUTE_TOAST_ID }), + onSuccess: (_, ids) => { + setSelected(new Set()); + void queryClient.invalidateQueries({ queryKey: ["quality-guard-degrade-accounts"] }); + void queryClient.invalidateQueries({ queryKey: ["accounts"] }); + toast.success(t("qualityGuard.degrade.unmuted", { count: ids.length }), { id: MUTE_TOAST_ID }); + }, + onError: (error) => toast.error(error instanceof Error ? error.message : t("qualityGuard.degrade.unmuteFailed"), { id: MUTE_TOAST_ID }), + }); + const busy = muteMutation.isPending || unmuteMutation.isPending; const toggleAll = (checked: boolean) => { setSelected((current) => { @@ -75,7 +89,7 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h = data.thresholds.hardTPS ? "bad" : undefined} />
-
+
@@ -95,16 +109,22 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h setSearch(event.target.value)} placeholder={t("qualityGuard.degrade.search")} />
- { setSelected(new Set()); setWindow(value as DegradeWindow); }} items={[["1h", t("qualityGuard.degrade.windows.1h")], ["6h", t("qualityGuard.degrade.windows.6h")], ["24h", t("qualityGuard.degrade.windows.24h")], ["7d", t("qualityGuard.degrade.windows.7d")]]} /> + { setSelected(new Set()); setPeriod(value as DegradeWindow); }} items={[["1h", t("qualityGuard.degrade.windows.1h")], ["6h", t("qualityGuard.degrade.windows.6h")], ["24h", t("qualityGuard.degrade.windows.24h")], ["7d", t("qualityGuard.degrade.windows.7d")]]} /> setStatus(value as "all" | "on" | "off")} items={[["all", t("qualityGuard.degrade.statusAll")], ["on", t("qualityGuard.degrade.statusOn")], ["off", t("qualityGuard.degrade.statusOff")]]} /> setCls(value as "all" | DegradeClass)} items={[["all", t("qualityGuard.degrade.classAll")], ["buffered_burst", "burst"], ["soft_tps", "soft"], ["hard_tps", "hard"]]} /> setHitsMin(Number(value))} items={[["1", t("qualityGuard.degrade.hitsAll")], ["2", t("qualityGuard.degrade.hitsMin", { count: 2 })], ["3", t("qualityGuard.degrade.hitsMin", { count: 3 })], ["5", t("qualityGuard.degrade.hitsMin", { count: 5 })], ["10", t("qualityGuard.degrade.hitsMin", { count: 10 })]]} /> - + @@ -114,7 +134,7 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h - 0 ? "indeterminate" : false} disabled={selectable.length === 0} onCheckedChange={(checked) => toggleAll(checked === true)} aria-label={t("common.selectPage")} /> + 0 ? "indeterminate" : false} disabled={selectable.length === 0} onCheckedChange={(checked) => toggleAll(checked === true)} aria-label={t("common.selectPage")} /> {t("qualityGuard.degrade.account")} {t("qualityGuard.degrade.status")} {t("qualityGuard.degrade.hitCount")} @@ -128,20 +148,31 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h {rows.length === 0 ? ( ) : rows.map((account) => ( - - setSelected((current) => { + { + setSelected((current) => { const next = new Set(current); - if (checked === true) next.add(account.id); - else next.delete(account.id); + if (next.has(account.id)) next.delete(account.id); + else next.add(account.id); return next; - })} /> + }); + }}> + event.stopPropagation()}> + +
#{account.id}
{account.email || account.name || "-"}
- - {account.enabled ? {t("qualityGuard.degrade.scheduling")} : {t("qualityGuard.degrade.mutedStatus")}} - {account.bfs ? bfs {account.bfs} : null} + + {account.enabled ? {t("qualityGuard.degrade.scheduling")} : {t("qualityGuard.degrade.mutedStatus")}} + {account.bfs ? bfs {account.bfs} : null} {account.hits} = data.thresholds.hardTPS ? "text-destructive" : account.maxTPS >= data.thresholds.softTPS ? "text-amber-600 dark:text-amber-400" : "")}>{account.maxTPS} @@ -225,27 +256,44 @@ function Metric({ icon: Icon, label, value, detail, tone }: { icon: typeof Alert function SeriesChart({ series, empty, title }: { series: DegradeSummaryDTO["series"]; empty: string; title: string }) { const max = Math.max(1, ...series.map((item) => item.count)); + const labelStep = series.length > 12 ? Math.ceil(series.length / 8) : 1; return ( -
-

{title}

-
- {series.length === 0 ?

{empty}

: series.map((item) => ( -
-
0 && item.severe >= item.count * 0.5 ? "bg-destructive" : "bg-amber-500/80")} style={{ height: `${Math.max(2, Math.round(item.count / max * 100))}%` }} /> -
{item.label}
-
- ))} +
+

{title}

+
+ {series.length === 0 ?

{empty}

: series.map((item, index) => { + const height = item.count <= 0 ? 0 : Math.max(6, Math.round((item.count / max) * 100)); + const showLabel = index % labelStep === 0 || index === series.length - 1; + return ( +
+
+
0 && item.severe >= item.count * 0.5 ? "bg-destructive" : "bg-amber-500")} + style={{ height: `${height}%` }} + /> +
+
+ {showLabel ? shortSeriesLabel(item.label) : ""} +
+
+ ); + })}
); } +function shortSeriesLabel(label: string) { + const hour = label.match(/(\d{1,2})(?::\d{2})?$/); + return hour ? hour[1].padStart(2, "0") : label; +} + function NodeList({ nodes, empty, title }: { nodes: DegradeSummaryDTO["nodes"]; empty: string; title: string }) { const max = Math.max(1, ...nodes.map((node) => node.hits)); return ( -
-

{title}

-
+
+

{title}

+
{nodes.length === 0 ?

{empty}

: nodes.map((node) => (
diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index 88fea127..169df231 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -454,8 +454,8 @@ const resources = { classAll: "全部类型", class: "类型", account: "账号", status: "状态", hitCount: "命中", hitsAll: "全部次数", hitsMin: "命中 ≥ {{count}}", windows: { "1h": "近 1 小时", "6h": "近 6 小时", "24h": "近 24 小时", "7d": "近 7 天" }, - muteSelected: "禁掉所选", muteSelectedCount: "禁掉所选 ({{count}})", muteConfirm: "确认禁掉 {{count}} 个仍在调度的降智账号?", muting: "正在禁言账号", muted: "已禁言 {{count}} 个账号", muteFailed: "禁言失败", - scheduling: "调度中", mutedStatus: "已禁", + muteSelected: "禁掉所选", muteSelectedCount: "禁掉所选 ({{count}})", muteConfirm: "确认禁掉 {{count}} 个仍在调度的降智账号?", muting: "正在禁言账号", muted: "已禁言 {{count}} 个账号", muteFailed: "禁言失败", unmuteSelected: "解除禁用", unmuteSelectedCount: "解除禁用 ({{count}})", unmuteConfirm: "确认恢复 {{count}} 个已禁账号到调度?", unmuting: "正在恢复账号", unmuted: "已恢复 {{count}} 个账号", unmuteFailed: "恢复失败", + scheduling: "调度", mutedStatus: "已禁", events: "最近事件", eventsHelp: "用户请求,不含 quality-test 探针", noHits: "这个窗口没有降智请求", noNodes: "无节点数据", noAccounts: "没有匹配账号", noEvents: "无事件", }, @@ -1363,7 +1363,7 @@ const resources = { classAll: "All classes", class: "Class", account: "Account", status: "Status", hitCount: "Hits", hitsAll: "Any hit count", hitsMin: "Hits ≥ {{count}}", windows: { "1h": "Last 1 hour", "6h": "Last 6 hours", "24h": "Last 24 hours", "7d": "Last 7 days" }, - muteSelected: "Mute selected", muteSelectedCount: "Mute selected ({{count}})", muteConfirm: "Mute {{count}} still-scheduled degraded accounts?", muting: "Muting accounts", muted: "Muted {{count}} accounts", muteFailed: "Failed to mute accounts", + muteSelected: "Mute selected", muteSelectedCount: "Mute selected ({{count}})", muteConfirm: "Mute {{count}} still-scheduled degraded accounts?", muting: "Muting accounts", muted: "Muted {{count}} accounts", muteFailed: "Failed to mute accounts", unmuteSelected: "Unmute selected", unmuteSelectedCount: "Unmute selected ({{count}})", unmuteConfirm: "Restore {{count}} muted accounts to scheduling?", unmuting: "Restoring accounts", unmuted: "Restored {{count}} accounts", unmuteFailed: "Failed to restore accounts", scheduling: "Scheduled", mutedStatus: "Muted", events: "Recent events", eventsHelp: "User requests; quality-test probes are excluded", noHits: "No degrade requests in this window", noNodes: "No node data", noAccounts: "No matching accounts", noEvents: "No events", From 90b408841a3474adf70803097029cbb8ce945140 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Thu, 13 Aug 2026 19:39:57 +0800 Subject: [PATCH 13/48] refactor: enhance proxy configuration and validation --- .../application/egress/subscription.go | 2 +- .../internal/pkg/tunnelproxy/tunnelproxy.go | 124 +++++++++++++++--- .../pkg/tunnelproxy/tunnelproxy_test.go | 91 +++++++++++++ .../src/features/settings/settings-model.ts | 94 ++++++++++++- 4 files changed, 291 insertions(+), 20 deletions(-) diff --git a/backend/internal/application/egress/subscription.go b/backend/internal/application/egress/subscription.go index ec20f7a3..42ddff98 100644 --- a/backend/internal/application/egress/subscription.go +++ b/backend/internal/application/egress/subscription.go @@ -368,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/pkg/tunnelproxy/tunnelproxy.go b/backend/internal/pkg/tunnelproxy/tunnelproxy.go index 4b35809c..c6314036 100644 --- a/backend/internal/pkg/tunnelproxy/tunnelproxy.go +++ b/backend/internal/pkg/tunnelproxy/tunnelproxy.go @@ -42,6 +42,8 @@ type Config struct { CanonicalProxyURL string } +const tunnelHandshakeTimeout = 10 * time.Second + func IsSupportedScheme(scheme string) bool { switch strings.ToLower(strings.TrimSpace(scheme)) { case "trojan", "vless", "ss", "vmess": @@ -113,9 +115,11 @@ func parseUserInfoProxy(value string) (Config, error) { return Config{}, fmt.Errorf("暂不支持 VLESS flow %q", flow) } if scheme == "vless" { - if _, err := uuid.Parse(credential); err != nil { + 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") } @@ -153,26 +157,48 @@ func parseUserInfoProxy(value string) (Config, error) { if transport == "tcp" && (query.Get("path") != "" || query.Get("host") != "") { return Config{}, errors.New("TCP 隧道不能包含 WebSocket host/path") } - parsed.Scheme = scheme - parsed.Host = server - parsed.User = url.User(credential) - parsed.Path = "" - parsed.RawPath = "" - parsed.Fragment = "" - parsed.RawFragment = "" - parsed.RawQuery = query.Encode() 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, - CanonicalProxyURL: parsed.String(), } + 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 { @@ -279,10 +305,11 @@ func parseVMess(value string) (Config, error) { if err != nil { return Config{}, fmt.Errorf("VMess %w", err) } - userID := jsonString(raw, "id") - if _, err := uuid.Parse(userID); err != nil { + 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 无效") @@ -316,6 +343,8 @@ func parseVMess(value string) (Config, error) { 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") @@ -438,7 +467,7 @@ func buildProxy(config Config) (netapi.Proxy, error) { case "vless": protocolConfig := &protocol.Vless{} protocolConfig.SetUuid(config.Credential) - return vless.NewClient(protocolConfig, current) + return newOwnedVLESSProxy(protocolConfig, current) case "vmess": protocolConfig := &protocol.Vmess{} protocolConfig.SetUuid(config.Credential) @@ -450,6 +479,63 @@ func buildProxy(config Config) (netapi.Proxy, error) { } } +// 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 @@ -462,7 +548,9 @@ func (p *tlsProxy) Conn(ctx context.Context, address netapi.Address) (net.Conn, return nil, err } tlsConnection := tls.Client(connection, p.tlsConfig()) - if err := tlsConnection.HandshakeContext(ctx); err != nil { + handshakeCtx, cancel := newTunnelHandshakeContext(ctx) + defer cancel() + if err := tlsConnection.HandshakeContext(handshakeCtx); err != nil { _ = connection.Close() return nil, fmt.Errorf("隧道 TLS 握手: %w", err) } @@ -501,7 +589,9 @@ func (p *websocketProxy) Conn(ctx context.Context, address netapi.Address) (net. ForceAttemptHTTP2: false, TLSClientConfig: websocketTLSConfig(p.config), } - connection, _, err := websocket.Dial(ctx, endpoint, &websocket.DialOptions{ + handshakeCtx, cancel := newTunnelHandshakeContext(ctx) + defer cancel() + connection, _, err := websocket.Dial(handshakeCtx, endpoint, &websocket.DialOptions{ HTTPClient: &http.Client{Transport: transport}, Host: p.config.WebSocketHost, }) @@ -529,6 +619,10 @@ 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"} diff --git a/backend/internal/pkg/tunnelproxy/tunnelproxy_test.go b/backend/internal/pkg/tunnelproxy/tunnelproxy_test.go index 33ffc121..a34f86a8 100644 --- a/backend/internal/pkg/tunnelproxy/tunnelproxy_test.go +++ b/backend/internal/pkg/tunnelproxy/tunnelproxy_test.go @@ -3,8 +3,10 @@ package tunnelproxy import ( "context" "encoding/base64" + "encoding/json" "fmt" "io" + "net" "net/http" "net/http/httptest" "strings" @@ -12,6 +14,7 @@ import ( "time" "github.com/Asutorufa/yuhaiin/pkg/net/netapi" + "github.com/Asutorufa/yuhaiin/pkg/protos/node/protocol" "github.com/coder/websocket" ) @@ -60,6 +63,75 @@ func TestNormalizeRemarksDoNotChangeIdentity(t *testing.T) { } } +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) @@ -130,3 +202,22 @@ func TestWebSocketTransportCarriesBinaryStream(t *testing.T) { 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/frontend/src/features/settings/settings-model.ts b/frontend/src/features/settings/settings-model.ts index 239c4e70..a35b4420 100644 --- a/frontend/src/features/settings/settings-model.ts +++ b/frontend/src/features/settings/settings-model.ts @@ -363,21 +363,31 @@ function validProxyURL(value: string): boolean { 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 /^ss:\/\/[^\s#]+(?:#[^\r\n]*)?$/.test(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 parsedScheme = parsed.protocol.replace(/:$/, "").toLowerCase(); if (["trojan", "vless"].includes(parsedScheme)) { - if (!parsed.username || parsed.password) return false; + 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; - return parsed.pathname === "" || parsed.pathname === "/"; + 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; @@ -390,6 +400,65 @@ function validProxyURL(value: string): boolean { } } +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("_", "/"); @@ -400,14 +469,31 @@ function validVMessURL(value: string): boolean { 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) - && ["tcp", "ws", "websocket"].includes(network) && ["", "none", "tls"].includes(tls); + && 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); From 4d805f91120160bfc86b9538bae744b8d4a2b260 Mon Sep 17 00:00:00 2001 From: 741075810 <31341354+741075810@users.noreply.github.com> Date: Thu, 13 Aug 2026 11:44:46 +0000 Subject: [PATCH 14/48] fix(models): skip alias-conflicting models during discovery instead of aborting the batch UpsertDiscovered calls ensureModelPublicIDNotAlias inside the transaction and returns on conflict, so one alias collision rolls back the whole batch and silently drops unrelated new models. preserveModelRouteAlias registers the old public ID as a compatibility alias on every route rename, so a single historical rename can permanently hide every future model of that provider. Skip the conflicting entry and keep the rest of the batch. Non-conflict errors still propagate. The skipped entry could not have been inserted anyway, so reachable state is unchanged. --- .../relational/model_discovery_alias_test.go | 79 +++++++++++++++++++ .../relational/model_repository.go | 7 ++ 2 files changed, 86 insertions(+) create mode 100644 backend/internal/infra/persistence/relational/model_discovery_alias_test.go diff --git a/backend/internal/infra/persistence/relational/model_discovery_alias_test.go b/backend/internal/infra/persistence/relational/model_discovery_alias_test.go new file mode 100644 index 00000000..9144eb4c --- /dev/null +++ b/backend/internal/infra/persistence/relational/model_discovery_alias_test.go @@ -0,0 +1,79 @@ +package relational + +import ( + "context" + "path/filepath" + "testing" + + "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/domain/model" + "github.com/chenyme/grok2api/backend/internal/repository" +) + +// Reproduces the reported behaviour: one alias collision inside a discovery +// batch rolls back the whole transaction, so unrelated new models in the same +// batch are silently dropped and can never be discovered again. +// +// Setup mirrors a real deployment: a route was renamed at some point, which +// makes preserveModelRouteAlias register the old public ID as a compatibility +// alias. Later the upstream catalog starts returning both the old model and a +// brand new one. +func TestUpsertDiscoveredAliasCollisionDropsWholeBatch(t *testing.T) { + ctx := context.Background() + database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "alias-batch.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + models := NewModelRepository(database) + + // A discovered route exists under its original public ID. + if err := models.UpsertDiscovered(ctx, account.ProviderBuild, []string{"grok-4.5"}); err != nil { + t.Fatal(err) + } + routes, _, err := models.List(ctx, repository.ModelListQuery{Page: repository.PageQuery{Limit: 100}}) + if err != nil { + t.Fatal(err) + } + var routeID uint64 + for _, route := range routes { + if route.UpstreamModel == "grok-4.5" { + routeID = route.ID + } + } + if routeID == 0 { + t.Fatalf("routes = %#v", routes) + } + + // Renaming it leaves "Build/grok-4.5" behind as a compatibility alias. + existing, err := models.Get(ctx, routeID) + if err != nil { + t.Fatal(err) + } + existing.PublicID = "Build/build-grok-4.5" + if _, err := models.Update(ctx, existing, nil); err != nil { + t.Fatal(err) + } + + // Upstream now returns the old model plus a new one. The old model maps onto + // the alias and conflicts; the new model does not. + err = models.UpsertDiscovered(ctx, account.ProviderBuild, []string{"grok-4.5", "grok-4.6"}) + t.Logf("UpsertDiscovered error = %v", err) + + routes, _, listErr := models.List(ctx, repository.ModelListQuery{Page: repository.PageQuery{Limit: 100}}) + if listErr != nil { + t.Fatal(listErr) + } + found46 := false + for _, route := range routes { + if route.UpstreamModel == "grok-4.6" && route.Origin == model.OriginDiscovered { + found46 = true + } + } + if !found46 { + t.Errorf("grok-4.6 was dropped because grok-4.5 collided with an alias in the same batch; routes = %#v", routes) + } +} diff --git a/backend/internal/infra/persistence/relational/model_repository.go b/backend/internal/infra/persistence/relational/model_repository.go index f13327cc..fb7f1f2e 100644 --- a/backend/internal/infra/persistence/relational/model_repository.go +++ b/backend/internal/infra/persistence/relational/model_repository.go @@ -705,7 +705,14 @@ func (r *ModelRepository) UpsertDiscovered(ctx context.Context, provider account if publicIDs[key] { continue } + // A discovered model whose canonical public ID is already reserved as + // another route compatibility alias cannot be inserted. Skip it and + // keep the rest of the batch: aborting here lets one historical rename + // permanently hide every future model of this provider. if err := ensureModelPublicIDNotAlias(tx, publicID, 0); err != nil { + if errors.Is(err, repository.ErrConflict) { + continue + } return err } publicIDs[key] = true From 9cae6ec6c51f5ed7886b4b97745c1019017656b6 Mon Sep 17 00:00:00 2001 From: 741075810 <31341354+741075810@users.noreply.github.com> Date: Thu, 13 Aug 2026 11:45:15 +0000 Subject: [PATCH 15/48] fix(console): split video input ceilings per field and cap reference-to-video duration Upstream enforces the two video image inputs separately: image is a single first frame (image-to-video) and reference_images holds up to 7 references (reference-to-video). The combined ceiling of MaxInputImages (8) let 8 references pass the local guard and take a 400 from upstream instead: "Too many reference images: 8. Maximum allowed is 7." Generation also allowed 1-15s for every mode, but reference-to-video on grok-imagine-video caps at 10s upstream: "Duration 15s exceeds the maximum allowed for reference-to-video, which is 10s." image-to-video and grok-imagine-video-1.5 keep 15s, so the new guard keys on reference_images plus the base model rather than on duration alone. Both limits come straight from upstream error text, quoted in comments so future changes can be checked against them. --- .../infra/provider/console/console_test.go | 51 ++++++++++++++++++- .../internal/infra/provider/console/media.go | 38 ++++++++++---- 2 files changed, 76 insertions(+), 13 deletions(-) diff --git a/backend/internal/infra/provider/console/console_test.go b/backend/internal/infra/provider/console/console_test.go index 81d90c56..9c013b83 100644 --- a/backend/internal/infra/provider/console/console_test.go +++ b/backend/internal/infra/provider/console/console_test.go @@ -1616,9 +1616,11 @@ func TestConsoleVideoPostsReferenceAudios(t *testing.T) { } } +// 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, consoleMaxVideoImages+1) + references := make([]string, consoleMaxVideoReferenceImages+1) for i := range references { references[i] = "https://example.com/" + strings.Repeat("x", i+1) + ".png" } @@ -1632,7 +1634,7 @@ func TestConsoleVideoRejectsTooManyReferenceImages(t *testing.T) { func TestConsoleVideoRejectsTooManyCombinedImages(t *testing.T) { adapter, credential := newConsoleTestAdapter(t, "https://console.example") - references := make([]string, consoleMaxVideoImages) + references := make([]string, consoleMaxVideoReferenceImages) for i := range references { references[i] = "https://example.com/" + strings.Repeat("y", i+1) + ".png" } @@ -1645,6 +1647,51 @@ func TestConsoleVideoRejectsTooManyCombinedImages(t *testing.T) { } } +// 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) { diff --git a/backend/internal/infra/provider/console/media.go b/backend/internal/infra/provider/console/media.go index c57a2a38..b0f04a2a 100644 --- a/backend/internal/infra/provider/console/media.go +++ b/backend/internal/infra/provider/console/media.go @@ -29,9 +29,15 @@ const ( consoleMediaOutputAttempts = 3 consoleVideoPollEvery = 2 * time.Second consoleMaxEditImages = 3 - // Align with the gateway ceiling and official xAI video inputs: - // image = first frame; reference_images = style/content references (may be length 1). - consoleMaxVideoImages = mediadomain.MaxInputImages + // 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 { @@ -458,14 +464,25 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque if operation != provider.VideoOperationGenerate && modelName != "grok-imagine-video" { return provider.VideoResult{}, fmt.Errorf("%s 仅支持 grok-imagine-video", operation) } - totalImages := consoleVideoImageCount(request) - if totalImages > consoleMaxVideoImages { - return provider.VideoResult{}, fmt.Errorf("Console %s 最多支持 %d 张输入图,当前为 %d 张", modelName, consoleMaxVideoImages, totalImages) + 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 { @@ -920,15 +937,14 @@ func trustedConsoleVideoHost(host string) bool { return host == "vidgen.x.ai" || strings.HasSuffix(host, ".vidgen.x.ai") } -func consoleVideoImageCount(request provider.VideoRequest) int { - count := 0 +func consoleVideoImageCounts(request provider.VideoRequest) (firstFrames int, referenceImages int) { if strings.TrimSpace(request.ImageURL) != "" { - count++ + firstFrames++ } for _, raw := range request.ReferenceURLs { if strings.TrimSpace(raw) != "" { - count++ + referenceImages++ } } - return count + return firstFrames, referenceImages } From 02c4014d6dcaca19bef91f37044912deb9390346 Mon Sep 17 00:00:00 2001 From: 2164312714-svg <2164312714-svg@users.noreply.github.com> Date: Thu, 13 Aug 2026 19:51:37 +0800 Subject: [PATCH 16/48] fix(web): isolate image prompts from chat history Use only the latest user turn for stateless image generation, support both Web image generation models through Chat Completions and Responses, and direct current-turn image inputs to the image edits endpoint. Refs #911 --- backend/internal/infra/provider/web/chat.go | 81 +++++++++++++++++-- backend/internal/infra/provider/web/image.go | 76 ++++++++++++++--- .../infra/provider/web/protocol_test.go | 72 +++++++++++++++++ 3 files changed, 214 insertions(+), 15 deletions(-) diff --git a/backend/internal/infra/provider/web/chat.go b/backend/internal/infra/provider/web/chat.go index 9549be88..a6f94462 100644 --- a/backend/internal/infra/provider/web/chat.go +++ b/backend/internal/infra/provider/web/chat.go @@ -20,6 +20,7 @@ import ( "github.com/chenyme/grok2api/backend/internal/domain/account" inferencedomain "github.com/chenyme/grok2api/backend/internal/domain/inference" + 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" "github.com/chenyme/grok2api/backend/internal/infra/provider/conversation" @@ -62,6 +63,8 @@ type openAIRequest struct { ImageConfig *struct { Count *int `json:"n"` ResponseFormat string `json:"response_format"` + AspectRatio string `json:"aspect_ratio"` + Resolution string `json:"resolution"` } `json:"image_config"` } @@ -209,7 +212,14 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response if len(input.Include) > 0 { conversationOptions.Include = append([]string{}, input.Include...) } - normalized, err := normalizeOpenAIInput(input, request.Operation) + spec, modelKnown := Resolve(request.Model) + var normalized normalizedChatInput + var err error + if modelKnown && spec.Capability == modeldomain.CapabilityImage { + normalized, err = normalizeLatestImageInput(input, request.Operation) + } else { + normalized, err = normalizeOpenAIInput(input, request.Operation) + } if err != nil { return jsonProviderResponse(http.StatusBadRequest, map[string]any{"error": map[string]any{"message": err.Error(), "type": "invalid_request_error"}}), nil } @@ -221,14 +231,16 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response if input.ParallelToolCalls != nil { parallelTools = *input.ParallelToolCalls } - spec, ok := Resolve(request.Model) - if ok && spec.ProtocolModel == "imagine-lite" && request.Operation == "chat" { + if modelKnown && spec.Capability == modeldomain.CapabilityImage { if len(tools.ResponseTools) > 0 { - return invalidImageRequest("grok-imagine-image-lite 不支持 tools") + return invalidImageRequest("图片生成模型不支持 tools") } - return a.forwardLiteChatCompletion(ctx, request, input, normalized, spec) + return a.forwardImageChatCompletion(ctx, request, input, normalized, spec) } - if !ok || spec.Capability != "chat" { + if modelKnown && spec.Capability == modeldomain.CapabilityImageEdit { + return invalidImageRequest("图片编辑模型请使用 /v1/images/edits,并在当前请求中显式提供输入图片") + } + if !modelKnown || spec.Capability != modeldomain.CapabilityChat { return jsonProviderResponse(http.StatusBadRequest, map[string]any{"error": map[string]any{"message": "模型不支持文本对话", "type": "invalid_request_error"}}), nil } @@ -736,6 +748,63 @@ func normalizeOpenAIInput(input openAIRequest, operation string) (normalizedChat return normalizedChatInput{Prompt: value, Attachments: attachments}, nil } +// Image generation is stateless: only the latest user turn is a prompt. In +// particular, assistant images from an OpenAI-compatible client's history must +// not be reinterpreted as image-edit inputs on the next generation request. +func normalizeLatestImageInput(input openAIRequest, operation string) (normalizedChatInput, error) { + if operation == conversation.OperationChat { + for index := len(input.Messages) - 1; index >= 0; index-- { + message := input.Messages[index] + if !strings.EqualFold(strings.TrimSpace(message.Role), "user") { + continue + } + return normalizeImageMessage(message.Content) + } + return normalizedChatInput{}, errors.New("messages 中缺少用户消息") + } + + trimmed := bytes.TrimSpace(input.Input) + if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) { + return normalizedChatInput{}, errors.New("input 不能为空") + } + if trimmed[0] == '"' { + var prompt string + if json.Unmarshal(trimmed, &prompt) != nil { + return normalizedChatInput{}, errors.New("input 格式无效") + } + prompt = strings.TrimSpace(prompt) + if prompt == "" { + return normalizedChatInput{}, errors.New("图片生成提示词不能为空") + } + return normalizedChatInput{Prompt: prompt}, nil + } + + var messages []chatMessage + if json.Unmarshal(trimmed, &messages) != nil { + return normalizedChatInput{}, errors.New("input 必须是字符串或消息数组") + } + for index := len(messages) - 1; index >= 0; index-- { + message := messages[index] + typeName := strings.ToLower(strings.TrimSpace(message.Type)) + if (typeName == "" || typeName == "message") && strings.EqualFold(strings.TrimSpace(message.Role), "user") { + return normalizeImageMessage(message.Content) + } + } + return normalizedChatInput{}, errors.New("input 中缺少用户消息") +} + +func normalizeImageMessage(content json.RawMessage) (normalizedChatInput, error) { + prompt, attachments, err := contentTextAndAttachments(content) + if err != nil { + return normalizedChatInput{}, err + } + prompt = strings.TrimSpace(prompt) + if prompt == "" && len(attachments) == 0 { + return normalizedChatInput{}, errors.New("图片生成提示词不能为空") + } + return normalizedChatInput{Prompt: prompt, Attachments: attachments}, nil +} + func rawTextValue(raw json.RawMessage) (string, error) { trimmed := bytes.TrimSpace(raw) if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) { diff --git a/backend/internal/infra/provider/web/image.go b/backend/internal/infra/provider/web/image.go index a94f198a..ced5e2b5 100644 --- a/backend/internal/infra/provider/web/image.go +++ b/backend/internal/infra/provider/web/image.go @@ -470,9 +470,9 @@ func (a *Adapter) generateLiteImageURL(ctx context.Context, credential account.C return "", fmt.Errorf("Grok Web Lite 图片签名刷新失败") } -func (a *Adapter) forwardLiteChatCompletion(ctx context.Context, request provider.ResponseResourceRequest, input openAIRequest, normalized normalizedChatInput, spec ModelSpec) (*provider.Response, error) { +func (a *Adapter) forwardImageChatCompletion(ctx context.Context, request provider.ResponseResourceRequest, input openAIRequest, normalized normalizedChatInput, spec ModelSpec) (*provider.Response, error) { if len(normalized.Attachments) > 0 { - return invalidImageRequest("grok-imagine-image-lite 只支持纯文本生图;附件请使用对应的图片编辑或对话模型") + return invalidImageRequest("文生图模型只接受当前用户消息中的纯文本;图生图请使用 grok-imagine-image-edit 和 /v1/images/edits") } count := 1 format := "url" @@ -490,12 +490,15 @@ func (a *Adapter) forwardLiteChatCompletion(ctx context.Context, request provide if format != "url" && format != "b64_json" { return invalidImageRequest("image_config.response_format 必须是 url 或 b64_json") } + if spec.ProtocolModel != "imagine-lite" { + return a.forwardQualityImageChatCompletion(ctx, request, input, normalized, count, format) + } responseID := newWebID("resp") streaming := input.Stream || request.Streaming if streaming { reader, writer := io.Pipe() streamCtx, cancel := context.WithCancel(ctx) - go a.streamLiteChatImages(streamCtx, writer, request.Credential, spec, responseID, input.Model, normalized.Prompt, count, format) + go a.streamLiteChatImages(streamCtx, writer, request.Credential, spec, responseID, input.Model, request.Operation, normalized.Prompt, count, format) return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: &cancelBody{ReadCloser: reader, cancel: cancel}, QuotaUnits: count}, nil } parsed := parsedChat{ResponseID: responseID, InputTokens: estimateTokens(normalized.Prompt)} @@ -517,7 +520,7 @@ func (a *Adapter) forwardLiteChatCompletion(ctx context.Context, request provide } parsed.appendText(liteImageMarkdown(item)) } - payload := buildOpenAIResult("chat", responseID, input.Model, parsed, false) + payload := buildOpenAIResult(request.Operation, responseID, input.Model, parsed, false) data, err := json.Marshal(payload) if err != nil { return nil, err @@ -525,9 +528,9 @@ func (a *Adapter) forwardLiteChatCompletion(ctx context.Context, request provide return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: jsonHeaders(), Body: io.NopCloser(bytes.NewReader(data)), QuotaUnits: count}, nil } -func (a *Adapter) streamLiteChatImages(ctx context.Context, writer *io.PipeWriter, credential account.Credential, spec ModelSpec, responseID, model, prompt string, count int, format string) { +func (a *Adapter) streamLiteChatImages(ctx context.Context, writer *io.PipeWriter, credential account.Credential, spec ModelSpec, responseID, model, operation, prompt string, count int, format string) { parsed := parsedChat{ResponseID: responseID, InputTokens: estimateTokens(prompt)} - writeStreamStart(writer, "chat", responseID, model, parsed.InputTokens) + writeStreamStart(writer, operation, responseID, model, parsed.InputTokens) for range count { rawURL, err := a.generateLiteImageURL(ctx, credential, spec, prompt) if err != nil { @@ -544,16 +547,71 @@ func (a *Adapter) streamLiteChatImages(ctx context.Context, writer *io.PipeWrite delta = "\n\n" + delta } parsed.appendText(delta) - if err := writeStreamDelta(writer, "chat", responseID, model, "text", delta); err != nil { + if err := writeStreamDelta(writer, operation, responseID, model, "text", delta); err != nil { _ = writer.CloseWithError(err) return } } - payload := buildOpenAIResult("chat", responseID, model, parsed, false) - writeStreamDone(writer, "chat", responseID, model, parsed, payload) + payload := buildOpenAIResult(operation, responseID, model, parsed, false) + writeStreamDone(writer, operation, responseID, model, parsed, payload) _ = writer.Close() } +func (a *Adapter) forwardQualityImageChatCompletion(ctx context.Context, request provider.ResponseResourceRequest, input openAIRequest, normalized normalizedChatInput, count int, format string) (*provider.Response, error) { + aspectRatio := "" + resolution := "" + if input.ImageConfig != nil { + aspectRatio = input.ImageConfig.AspectRatio + resolution = input.ImageConfig.Resolution + } + generated, err := a.GenerateImage(ctx, provider.ImageGenerationRequest{ + Credential: request.Credential, Model: request.Model, Prompt: normalized.Prompt, + Count: count, AspectRatio: aspectRatio, Resolution: resolution, ResponseFormat: format, + }) + if err != nil { + return nil, err + } + if generated.StatusCode < http.StatusOK || generated.StatusCode >= http.StatusMultipleChoices { + return generated, nil + } + defer generated.Body.Close() + var payload struct { + Data []map[string]any `json:"data"` + } + if err := json.NewDecoder(generated.Body).Decode(&payload); err != nil { + return nil, provider.NewMediaPostProcessingError(provider.MediaPostProcessingStorage, fmt.Errorf("图片生成兼容响应解析失败: %w", err)) + } + parsed := parsedChat{ResponseID: newWebID("resp"), InputTokens: estimateTokens(normalized.Prompt)} + for _, item := range payload.Data { + markdown := liteImageMarkdown(item) + if markdown == "" { + continue + } + if parsed.Text.Len() > 0 { + parsed.appendText("\n\n") + } + parsed.appendText(markdown) + } + if parsed.Text.Len() == 0 { + return nil, fmt.Errorf("图片生成兼容响应中没有图片") + } + result := buildOpenAIResult(request.Operation, parsed.ResponseID, input.Model, parsed, false) + if input.Stream || request.Streaming { + var stream bytes.Buffer + writeStreamStart(&stream, request.Operation, parsed.ResponseID, input.Model, parsed.InputTokens) + if err := writeStreamDelta(&stream, request.Operation, parsed.ResponseID, input.Model, "text", parsed.Text.String()); err != nil { + return nil, err + } + writeStreamDone(&stream, request.Operation, parsed.ResponseID, input.Model, parsed, result) + return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: io.NopCloser(bytes.NewReader(stream.Bytes())), QuotaUnits: generated.QuotaUnits}, nil + } + data, err := json.Marshal(result) + if err != nil { + return nil, err + } + return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: jsonHeaders(), Body: io.NopCloser(bytes.NewReader(data)), QuotaUnits: generated.QuotaUnits}, nil +} + func liteImageMarkdown(item map[string]any) string { if value, _ := item["url"].(string); value != "" { return "![image](" + value + ")" diff --git a/backend/internal/infra/provider/web/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index 2377d375..cdbe6991 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -143,6 +143,78 @@ func TestNormalizeOpenAIInputSeparatesTextAndImages(t *testing.T) { } } +func TestNormalizeLatestImageInputIgnoresHistoricalAssistantImage(t *testing.T) { + historical, _ := json.Marshal([]any{ + map[string]any{"type": "text", "text": "first result"}, + map[string]any{"type": "image_url", "image_url": map[string]any{"url": "https://example.com/first.png"}}, + }) + latest, _ := json.Marshal("生成另一张蓝色的图片") + value, err := normalizeLatestImageInput(openAIRequest{Messages: []chatMessage{ + {Role: "user", Content: json.RawMessage(`"生成第一张图片"`)}, + {Role: "assistant", Content: historical}, + {Role: "user", Content: latest}, + }}, conversation.OperationChat) + if err != nil { + t.Fatal(err) + } + if value.Prompt != "生成另一张蓝色的图片" || len(value.Attachments) != 0 { + t.Fatalf("normalized latest image input = %#v", value) + } +} + +func TestNormalizeLatestResponsesImageInputIgnoresHistory(t *testing.T) { + input, _ := json.Marshal([]any{ + map[string]any{"type": "message", "role": "assistant", "content": []any{ + map[string]any{"type": "output_text", "text": "![image](https://example.com/first.png)"}, + map[string]any{"type": "input_image", "image_url": "https://example.com/first.png"}, + }}, + map[string]any{"role": "user", "content": []any{ + map[string]any{"type": "input_text", "text": "generate a different image"}, + }}, + }) + value, err := normalizeLatestImageInput(openAIRequest{Input: input}, conversation.OperationResponses) + if err != nil { + t.Fatal(err) + } + if value.Prompt != "generate a different image" || len(value.Attachments) != 0 { + t.Fatalf("normalized latest responses input = %#v", value) + } +} + +func TestImageChatRejectsOnlyCurrentTurnAttachment(t *testing.T) { + content, _ := json.Marshal([]any{ + map[string]any{"type": "text", "text": "make it blue"}, + map[string]any{"type": "image_url", "image_url": map[string]any{"url": "https://example.com/input.png"}}, + }) + response, err := (&Adapter{}).ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Method: http.MethodPost, Model: "grok-imagine-image", Operation: conversation.OperationChat, + Body: []byte(fmt.Sprintf(`{"model":"grok-imagine-image-lite","messages":[{"role":"user","content":%s}]}`, content)), + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + body, _ := io.ReadAll(response.Body) + if response.StatusCode != http.StatusBadRequest || !strings.Contains(string(body), "/v1/images/edits") { + t.Fatalf("status=%d body=%s", response.StatusCode, body) + } +} + +func TestQualityImageResponsesUsesImageCompatibilityValidation(t *testing.T) { + response, err := (&Adapter{}).ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Method: http.MethodPost, Model: "grok-imagine-image-quality", Operation: conversation.OperationResponses, + Body: []byte(`{"model":"grok-imagine-image-quality-lite","input":[{"role":"user","content":[{"type":"input_text","text":"draw"}]}],"image_config":{"n":0}}`), + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + body, _ := io.ReadAll(response.Body) + if response.StatusCode != http.StatusBadRequest || !strings.Contains(string(body), "image_config.n") || strings.Contains(string(body), "模型不支持文本对话") { + t.Fatalf("status=%d body=%s", response.StatusCode, body) + } +} + func TestNormalizeResponsesInputImage(t *testing.T) { dataURI := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=" input, _ := json.Marshal([]any{map[string]any{ From a2e4abb558315bc79435214cd5042b70f497d5db Mon Sep 17 00:00:00 2001 From: 2164312714-svg <2164312714-svg@users.noreply.github.com> Date: Thu, 13 Aug 2026 20:27:34 +0800 Subject: [PATCH 17/48] fix(web): surface lite image stream failures --- backend/internal/infra/provider/web/image.go | 45 ++++------------- .../infra/provider/web/protocol_test.go | 50 +++++++++++++++++++ 2 files changed, 59 insertions(+), 36 deletions(-) diff --git a/backend/internal/infra/provider/web/image.go b/backend/internal/infra/provider/web/image.go index ced5e2b5..fb759985 100644 --- a/backend/internal/infra/provider/web/image.go +++ b/backend/internal/infra/provider/web/image.go @@ -494,13 +494,6 @@ func (a *Adapter) forwardImageChatCompletion(ctx context.Context, request provid return a.forwardQualityImageChatCompletion(ctx, request, input, normalized, count, format) } responseID := newWebID("resp") - streaming := input.Stream || request.Streaming - if streaming { - reader, writer := io.Pipe() - streamCtx, cancel := context.WithCancel(ctx) - go a.streamLiteChatImages(streamCtx, writer, request.Credential, spec, responseID, input.Model, request.Operation, normalized.Prompt, count, format) - return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: &cancelBody{ReadCloser: reader, cancel: cancel}, QuotaUnits: count}, nil - } parsed := parsedChat{ResponseID: responseID, InputTokens: estimateTokens(normalized.Prompt)} for range count { rawURL, err := a.generateLiteImageURL(ctx, request.Credential, spec, normalized.Prompt) @@ -521,6 +514,15 @@ func (a *Adapter) forwardImageChatCompletion(ctx context.Context, request provid parsed.appendText(liteImageMarkdown(item)) } payload := buildOpenAIResult(request.Operation, responseID, input.Model, parsed, false) + if input.Stream || request.Streaming { + var stream bytes.Buffer + writeStreamStart(&stream, request.Operation, responseID, input.Model, parsed.InputTokens) + if err := writeStreamDelta(&stream, request.Operation, responseID, input.Model, "text", parsed.Text.String()); err != nil { + return nil, err + } + writeStreamDone(&stream, request.Operation, responseID, input.Model, parsed, payload) + return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: io.NopCloser(bytes.NewReader(stream.Bytes())), QuotaUnits: count}, nil + } data, err := json.Marshal(payload) if err != nil { return nil, err @@ -528,35 +530,6 @@ func (a *Adapter) forwardImageChatCompletion(ctx context.Context, request provid return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: jsonHeaders(), Body: io.NopCloser(bytes.NewReader(data)), QuotaUnits: count}, nil } -func (a *Adapter) streamLiteChatImages(ctx context.Context, writer *io.PipeWriter, credential account.Credential, spec ModelSpec, responseID, model, operation, prompt string, count int, format string) { - parsed := parsedChat{ResponseID: responseID, InputTokens: estimateTokens(prompt)} - writeStreamStart(writer, operation, responseID, model, parsed.InputTokens) - for range count { - rawURL, err := a.generateLiteImageURL(ctx, credential, spec, prompt) - if err != nil { - _ = writer.CloseWithError(err) - return - } - item, err := a.imageDataItem(ctx, credential, imagineImageValue{URL: rawURL}, format) - if err != nil { - _ = writer.CloseWithError(err) - return - } - delta := liteImageMarkdown(item) - if parsed.Text.Len() > 0 { - delta = "\n\n" + delta - } - parsed.appendText(delta) - if err := writeStreamDelta(writer, operation, responseID, model, "text", delta); err != nil { - _ = writer.CloseWithError(err) - return - } - } - payload := buildOpenAIResult(operation, responseID, model, parsed, false) - writeStreamDone(writer, operation, responseID, model, parsed, payload) - _ = writer.Close() -} - func (a *Adapter) forwardQualityImageChatCompletion(ctx context.Context, request provider.ResponseResourceRequest, input openAIRequest, normalized normalizedChatInput, count int, format string) (*provider.Response, error) { aspectRatio := "" resolution := "" diff --git a/backend/internal/infra/provider/web/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index cdbe6991..3c848f22 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -657,6 +657,56 @@ func TestLiteChatRejectsInvalidImageConfigBeforeUpstream(t *testing.T) { } } +func TestLiteChatStreamFailsBeforeReturningSuccessResponse(t *testing.T) { + server := fhttptest.NewServer(fhttp.HandlerFunc(func(writer fhttp.ResponseWriter, request *fhttp.Request) { + if request.URL.Path != "/ws/mgw/" { + fhttp.NotFound(writer, request) + return + } + connection, err := (&websocket.Upgrader{CheckOrigin: func(*fhttp.Request) bool { return true }}).Upgrade(writer, request, nil) + if err != nil { + t.Errorf("upgrade: %v", err) + return + } + defer connection.Close() + var initial map[string]any + if err := connection.ReadJSON(&initial); err != nil { + t.Errorf("read session.create: %v", err) + return + } + initialID := initial["event"].(map[string]any)["event_id"].(string) + _ = connection.WriteJSON(map[string]any{"session_id": "conv_1", "event": map[string]any{"type": "session.created", "client_event_id": initialID}}) + _ = connection.WriteJSON(map[string]any{"session_id": "conv_1", "event": map[string]any{"type": "conversation.attached", "conversation": map[string]any{"id": "conv_1"}}}) + for range 2 { + var event map[string]any + if err := connection.ReadJSON(&event); err != nil { + t.Errorf("read turn event: %v", err) + return + } + } + _ = connection.WriteJSON(map[string]any{"session_id": "conv_1", "event": map[string]any{"type": "response.done", "response": map[string]any{"id": "parent_1", "status": "completed"}}}) + })) + defer server.Close() + + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + encrypted, err := cipher.Encrypt("test-sso") + if err != nil { + t.Fatal(err) + } + adapter := NewAdapter(Config{BaseURL: server.URL, StatsigMode: "manual"}, infraegress.NewManager(egressRepositoryStub{}, cipher), cipher, nil, imageAssetStoreStub{}) + response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Credential: account.Credential{ID: 1, Provider: account.ProviderWeb, UserID: "497f19f8-49d4-458a-bee4-43ec3dcaf8ca", EncryptedAccessToken: encrypted}, + Method: http.MethodPost, Path: "/v1/chat/completions", Model: "grok-imagine-image", Operation: conversation.OperationChat, + Body: []byte(`{"model":"grok-imagine-image-lite","stream":true,"messages":[{"role":"user","content":"draw a cat"}]}`), Streaming: true, + }) + if err == nil || response != nil || !strings.Contains(err.Error(), "未解析到最终图片") { + t.Fatalf("response=%#v error=%v", response, err) + } +} + func TestParseLiteImageCardAttachment(t *testing.T) { parsed := &parsedChat{} frame := map[string]any{"result": map[string]any{"response": map[string]any{ From 61010b4bc2581a34562b8635d89e23ef91a4c0b6 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Thu, 13 Aug 2026 21:21:50 +0800 Subject: [PATCH 18/48] feat: add reliable on-demand Cloudflare Clearance refresh --- README.md | 7 +- README.zh-CN.md | 7 +- .../application/settings/service_test.go | 8 +- backend/internal/infra/egress/manager.go | 11 +- backend/internal/infra/egress/manager_test.go | 102 ++++++++++++++++++ docker-compose.yml | 2 +- .../src/features/settings/egress-nodes.tsx | 13 ++- .../src/features/settings/settings-api.ts | 6 +- .../src/features/settings/settings-model.ts | 4 +- .../src/features/settings/settings-page.tsx | 7 +- frontend/src/shared/i18n/index.ts | 8 ++ 11 files changed, 157 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 38208957..429a4e8b 100644 --- a/README.md +++ b/README.md @@ -377,7 +377,12 @@ For managed Web/Console Cloudflare Clearance: docker compose --profile flaresolverr up -d ``` -Then select `FlareSolverr` under **Runtime Settings → Media & Network → Clearance** and use `http://flaresolverr:8191`. +Then use `http://flaresolverr:8191` under **Runtime Settings → Media & Network → Clearance** and select one of the managed modes: + +- `FlareSolverr` proactively refreshes stale fixed-egress Clearance on the configured schedule. +- `On demand` keeps the last successful Clearance regardless of age and solves again only after an upstream rejection explicitly invalidates it. Scheduled refresh does not launch a browser in this mode. + +`Manual` never invokes FlareSolverr. The on-demand mode can make the first request without a managed Clearance; if Cloudflare rejects it, the next lease performs one deduplicated solve. The egress layer retries only connection failures known to occur before request submission. It does not replay submitted generation requests, authentication failures, exhausted quotas, or upstream rate limits. diff --git a/README.zh-CN.md b/README.zh-CN.md index 38aff70d..907afdcd 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -371,7 +371,12 @@ socks5h://Default.{account}:RESIN_PROXY_TOKEN@resin:2260 docker compose --profile flaresolverr up -d ``` -随后在 **运行设置 → 媒体与网络 → Clearance** 选择 `FlareSolverr`,地址填写 `http://flaresolverr:8191`。 +随后在 **运行设置 → 媒体与网络 → Clearance** 填写 `http://flaresolverr:8191`,并选择一种托管模式: + +- `FlareSolverr` 按配置周期主动刷新固定出口中过期的 Clearance。 +- `按需刷新` 不按时间淘汰最后一次成功的 Clearance,只在上游明确拒绝并将其标记失效后重新求解;后台定时任务不会在该模式下启动浏览器。 + +`手动维护` 始终不会调用 FlareSolverr。按需模式允许首次请求不携带托管 Clearance;若被 Cloudflare 拒绝,下一次租约会执行一次经过并发去重的求解。 出口层只重试可以确认发生在请求提交前的连接故障,不会重放已经提交的生成请求、认证失败、额度耗尽或上游限流。 diff --git a/backend/internal/application/settings/service_test.go b/backend/internal/application/settings/service_test.go index ac8b95e0..cf711178 100644 --- a/backend/internal/application/settings/service_test.go +++ b/backend/internal/application/settings/service_test.go @@ -58,6 +58,9 @@ func TestUpdatePersistsAppliesAndReportsRestart(t *testing.T) { input.Frontend.PublicAPIBaseURL = "https://public.example.com" input.ProviderConsole.BaseURL = "https://console.example.com" input.ProviderConsole.ChatTimeout = "6m" + input.ProviderWeb.ClearanceProvided = true + input.ProviderWeb.ClearanceMode = config.ClearanceModeOnDemand + input.ProviderWeb.FlareSolverrURL = "http://flaresolverr:8191" input.Batch = BatchConfig{ImportConcurrency: 26, ConversionConcurrency: 27, SyncConcurrency: 28, RefreshConcurrency: 29, RandomDelay: "750ms"} snapshot, err := service.Update(context.Background(), service.Get().Revision, input) @@ -85,6 +88,9 @@ func TestUpdatePersistsAppliesAndReportsRestart(t *testing.T) { if applied.Provider.Console.BaseURL != "https://console.example.com" || applied.Provider.Console.ChatTimeout.Value() != 6*time.Minute { t.Fatalf("console configuration was not applied: %#v", applied.Provider.Console) } + if applied.Provider.Web.ClearanceMode != config.ClearanceModeOnDemand || applied.Provider.Web.FlareSolverrURL != "http://flaresolverr:8191" { + t.Fatalf("on-demand Clearance configuration was not applied: %#v", applied.Provider.Web) + } if len(snapshot.RestartRequired) != 1 || snapshot.RestartRequired[0] != "audit.bufferSize" { t.Fatalf("restartRequired = %#v", snapshot.RestartRequired) } @@ -92,7 +98,7 @@ func TestUpdatePersistsAppliesAndReportsRestart(t *testing.T) { if err != nil { t.Fatal(err) } - if reloaded.Server.MaxConcurrentRequests != 2048 || reloaded.Provider.Build.ResponseHeaderTimeout.Value() != 7*time.Minute || reloaded.Routing.MaxAttempts != 5 || !reloaded.Routing.PreferFreeBuild || !reloaded.Routing.SegmentedSelectorEnabled || reloaded.Routing.SegmentedMinCandidates != 5000 || reloaded.Routing.SegmentedWindowSize != 96 || reloaded.Audit.BufferSize != input.Audit.BufferSize || reloaded.Media.MaxTotalBytes != 2<<30 || reloaded.Media.CleanupThresholdPercent != 75 || reloaded.Batch.SyncConcurrency != 28 || reloaded.Batch.RandomDelay.Value() != 750*time.Millisecond || reloaded.Provider.Console.BaseURL != "https://console.example.com" { + if reloaded.Server.MaxConcurrentRequests != 2048 || reloaded.Provider.Build.ResponseHeaderTimeout.Value() != 7*time.Minute || reloaded.Routing.MaxAttempts != 5 || !reloaded.Routing.PreferFreeBuild || !reloaded.Routing.SegmentedSelectorEnabled || reloaded.Routing.SegmentedMinCandidates != 5000 || reloaded.Routing.SegmentedWindowSize != 96 || reloaded.Audit.BufferSize != input.Audit.BufferSize || reloaded.Media.MaxTotalBytes != 2<<30 || reloaded.Media.CleanupThresholdPercent != 75 || reloaded.Batch.SyncConcurrency != 28 || reloaded.Batch.RandomDelay.Value() != 750*time.Millisecond || reloaded.Provider.Console.BaseURL != "https://console.example.com" || reloaded.Provider.Web.ClearanceMode != config.ClearanceModeOnDemand { t.Fatalf("configuration was not persisted") } } diff --git a/backend/internal/infra/egress/manager.go b/backend/internal/infra/egress/manager.go index 09b8e360..e3c99930 100644 --- a/backend/internal/infra/egress/manager.go +++ b/backend/internal/infra/egress/manager.go @@ -1820,6 +1820,9 @@ func (m *Manager) ensureClearance(ctx context.Context, node domain.Node, proxyUR } if cfg.Mode == "on_demand" && !forceRefresh { m.clearanceMu.Unlock() + if fallbackAllowed { + return fallback.Cookies, fallback.UserAgent, nil + } return existingCookies, existingUserAgent, nil } if cfg.Mode != "flaresolverr" && cfg.Mode != "on_demand" { @@ -1879,8 +1882,12 @@ func (m *Manager) refreshNode(ctx context.Context, node domain.Node, proxyURL, k return clearanceSolution{}, errors.New("另一个实例正在刷新 Cloudflare Clearance") } defer release() - if !force { - if solution, refreshedAt, ok := m.loadPersistedClearance(ctx, node.ID, fingerprint, bindingFingerprint, interval); ok { + if solution, refreshedAt, ok := m.loadPersistedClearance(ctx, node.ID, fingerprint, bindingFingerprint, interval); ok { + // A peer may have refreshed the rejected Clearance immediately before + // this instance acquired the distributed lock. Reuse that newer result + // instead of performing a duplicate browser solve. A force refresh with + // no newer persisted generation must still reach the solver. + if !force || (!refreshAfter.IsZero() && refreshedAt.After(refreshAfter)) { m.cacheClearance(key, solution, refreshedAt, solveVersion, fingerprint, bindingFingerprint, interval) return solution, nil } diff --git a/backend/internal/infra/egress/manager_test.go b/backend/internal/infra/egress/manager_test.go index 9fd88863..1b2f3a3d 100644 --- a/backend/internal/infra/egress/manager_test.go +++ b/backend/internal/infra/egress/manager_test.go @@ -1907,6 +1907,108 @@ func TestOnDemandClearanceSkipsBackgroundRefresh(t *testing.T) { } } +func TestOnDemandClearanceKeepsLastSuccessfulDirectSolutionPastRefreshInterval(t *testing.T) { + cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") + if err != nil { + t.Fatal(err) + } + solver := &clearanceSolverStub{} + manager := NewManager(egressRepositoryTestStub{}, cipher) + manager.solver = solver + manager.UpdateClearanceConfig(ClearanceConfig{ + Mode: "on_demand", FlareSolverrURL: "http://solver", TargetURL: "https://grok.com", + Timeout: time.Second, RefreshInterval: time.Nanosecond, + }) + + initial, err := manager.Acquire(context.Background(), domain.ScopeConsole, "account") + if err != nil { + t.Fatal(err) + } + if initial.CFCookies != "" || solver.calls != 0 { + t.Fatalf("initial lease cookies=%q calls=%d", initial.CFCookies, solver.calls) + } + initial.InvalidateClearance() + initial.Release() + + refreshed, err := manager.Acquire(context.Background(), domain.ScopeConsole, "account") + if err != nil { + t.Fatal(err) + } + if refreshed.CFCookies != "cf_clearance=value-1" || solver.calls != 1 { + t.Fatalf("refreshed lease cookies=%q calls=%d", refreshed.CFCookies, solver.calls) + } + refreshed.Release() + + // The interval is deliberately expired. on_demand must keep using the last + // successful runtime-only solution until an upstream rejection invalidates it. + reused, err := manager.Acquire(context.Background(), domain.ScopeConsole, "account") + if err != nil { + t.Fatal(err) + } + defer reused.Release() + if reused.CFCookies != "cf_clearance=value-1" || reused.UserAgent != "Chrome/146 test" || solver.calls != 1 { + t.Fatalf("reused lease=%#v calls=%d", reused, solver.calls) + } +} + +func TestOnDemandClearanceReusesPeerRefreshAfterDistributedLock(t *testing.T) { + cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") + if err != nil { + t.Fatal(err) + } + config := ClearanceConfig{ + Mode: "on_demand", FlareSolverrURL: "http://solver", TargetURL: "https://grok.com", + Timeout: time.Second, RefreshInterval: time.Hour, + } + oldCookies, err := cipher.Encrypt("cf_clearance=old") + if err != nil { + t.Fatal(err) + } + oldRefreshedAt := time.Now().UTC().Add(-time.Minute) + repository := &mutableEgressRepository{node: domain.Node{ + ID: 1, Name: "console", Scope: domain.ScopeConsole, Enabled: true, Health: 1, + EncryptedCloudflareCookie: oldCookies, UserAgent: "Chrome/old", + ClearanceFingerprint: clearanceFingerprint(config, ""), ClearanceBindingFingerprint: clearanceBindingFingerprint(config, ""), + ClearanceRefreshedAt: &oldRefreshedAt, + }} + solver := &clearanceSolverStub{} + firstManager := NewManager(repository, cipher) + firstManager.solver = solver + firstManager.SetClearanceLock(alwaysAcquiredDistributedLock{}) + firstManager.UpdateClearanceConfig(config) + secondManager := NewManager(repository, cipher) + secondManager.solver = solver + secondManager.SetClearanceLock(alwaysAcquiredDistributedLock{}) + secondManager.UpdateClearanceConfig(config) + + firstOld, err := firstManager.Acquire(context.Background(), domain.ScopeConsole, "first") + if err != nil { + t.Fatal(err) + } + secondOld, err := secondManager.Acquire(context.Background(), domain.ScopeConsole, "second") + if err != nil { + t.Fatal(err) + } + firstOld.InvalidateClearance() + secondOld.InvalidateClearance() + firstOld.Release() + secondOld.Release() + + firstFresh, err := firstManager.Acquire(context.Background(), domain.ScopeConsole, "first") + if err != nil { + t.Fatal(err) + } + firstFresh.Release() + secondFresh, err := secondManager.Acquire(context.Background(), domain.ScopeConsole, "second") + if err != nil { + t.Fatal(err) + } + defer secondFresh.Release() + if solver.calls != 1 || secondFresh.CFCookies != "cf_clearance=value-1" { + t.Fatalf("peer refresh was not reused: calls=%d cookies=%q", solver.calls, secondFresh.CFCookies) + } +} + func TestFlareSolverrRefreshesRejectedNodeBeforeNextLease(t *testing.T) { cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") if err != nil { diff --git a/docker-compose.yml b/docker-compose.yml index 514ac373..e11f0fbc 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -38,7 +38,7 @@ services: # - NET_ADMIN # ================================ FLARESOLVERR ================================ - # 在管理端将 Clearance 模式设为 FlareSolverr,并使用 http://flaresolverr:8191。 + # 在管理端将 Clearance 模式设为 FlareSolverr 或按需刷新,并使用 http://flaresolverr:8191。 # 启动命令:docker compose --profile flaresolverr up -d # Podman:podman compose --profile flaresolverr up -d diff --git a/frontend/src/features/settings/egress-nodes.tsx b/frontend/src/features/settings/egress-nodes.tsx index 157ce75f..e852e199 100644 --- a/frontend/src/features/settings/egress-nodes.tsx +++ b/frontend/src/features/settings/egress-nodes.tsx @@ -19,7 +19,7 @@ import { Table, TableActionCell, TableActionHead, TableBody, TableCell, TableHea import { Textarea } from "@/components/ui/textarea"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { EgressAutomation, EgressSources } from "@/features/settings/egress-operations"; -import { cleanupUnhealthyEgressNodes, createEgressNode, deleteEgressNode, deleteEgressNodes, importEgressText, listEgressNodes, previewUnhealthyEgressNodes, refreshEgressClearance, testEgressNode, updateEgressNode, updateEgressNodesEnabled, type EgressIPProbeDTO, type EgressNodeDTO, type EgressNodeInput, type EgressScope } from "@/features/settings/settings-api"; +import { cleanupUnhealthyEgressNodes, createEgressNode, deleteEgressNode, deleteEgressNodes, importEgressText, listEgressNodes, previewUnhealthyEgressNodes, refreshEgressClearance, testEgressNode, updateEgressNode, updateEgressNodesEnabled, type ClearanceMode, type EgressIPProbeDTO, type EgressNodeDTO, type EgressNodeInput, type EgressScope } from "@/features/settings/settings-api"; import { ErrorState, TableLoadingRow } from "@/shared/components/data-state"; import { DataTableShell } from "@/shared/components/data-table-shell"; import { DataTableFilters } from "@/shared/components/data-table-filters"; @@ -34,7 +34,7 @@ const emptyInput: EgressNodeInput = { name: "", scope: "grok_build", enabled: tr type ImportForm = { name: string; scope: EgressScope; accountCapacity: number; content: string }; const emptyImport: ImportForm = { name: "", scope: "grok_build", accountCapacity: 0, content: "" }; -export function EgressNodes({ title, clearanceMode }: { title: string; clearanceMode: "manual" | "flaresolverr" }) { +export function EgressNodes({ title, clearanceMode }: { title: string; clearanceMode: ClearanceMode }) { const { t } = useTranslation(); const queryClient = useQueryClient(); const [editing, setEditing] = useState(undefined); @@ -302,7 +302,7 @@ export function EgressNodes({ title, clearanceMode }: { title: string; clearance openEdit(node)}>{t("common.edit")} - {clearanceMode === "flaresolverr" && !node.accountBoundProxy && (node.scope === "grok_web" || node.scope === "grok_web_asset" || node.scope === "grok_console") ? refreshClearance.mutate(node.id)}>{t("settings.egress.refreshClearance")} : null} + {clearanceMode !== "manual" && !node.accountBoundProxy && (node.scope === "grok_web" || node.scope === "grok_web_asset" || node.scope === "grok_console") ? refreshClearance.mutate(node.id)}>{t("settings.egress.refreshClearance")} : null} testNode.mutate(node.id)}>{t("settings.egress.test")} remove.mutate(node.id)}>{t("common.delete")} @@ -401,7 +401,7 @@ export function EgressNodes({ title, clearanceMode }: { title: string; clearance
{t("settings.egress.clearance")} - {clearanceMode === "flaresolverr" ? t("settings.web.clearanceFlareSolverr") : t("settings.web.clearanceManual")} + {clearanceMode === "flaresolverr" ? t("settings.web.clearanceFlareSolverr") : clearanceMode === "on_demand" ? t("settings.web.clearanceOnDemand") : t("settings.web.clearanceManual")}
) : null} @@ -485,12 +485,15 @@ function ErrorTooltip({ message }: { message: string }) { ); } -function ClearanceBadge({ node, clearanceMode }: { node: EgressNodeDTO; clearanceMode: "manual" | "flaresolverr" }) { +function ClearanceBadge({ node, clearanceMode }: { node: EgressNodeDTO; clearanceMode: ClearanceMode }) { const { t } = useTranslation(); if (node.scope === "grok_build") return —; if (clearanceMode === "flaresolverr") { return {node.accountBoundProxy ? `${t("settings.web.clearanceFlareSolverr")} · Resin` : t("settings.web.clearanceFlareSolverr")}; } + if (clearanceMode === "on_demand") { + return {node.accountBoundProxy ? `${t("settings.web.clearanceOnDemand")} · Resin` : t("settings.web.clearanceOnDemand")}; + } return {node.cookieConfigured ? t("settings.egress.configured") : t("settings.egress.none")}; } diff --git a/frontend/src/features/settings/settings-api.ts b/frontend/src/features/settings/settings-api.ts index 22fda831..85dd007d 100644 --- a/frontend/src/features/settings/settings-api.ts +++ b/frontend/src/features/settings/settings-api.ts @@ -8,7 +8,7 @@ export type SettingsConfigDTO = { providerWeb: { baseURL: string; quotaTimeout: string; chatTimeout: string; streamIdleTimeout: string; imageTimeout: string; videoTimeout: string; statsigMode: "manual" | "url"; statsigManualValue?: string; statsigManualConfigured: boolean; statsigSignerURL: string; - clearanceMode: "manual" | "flaresolverr"; flareSolverrURL: string; clearanceTimeout: string; clearanceRefresh: string; + clearanceMode: ClearanceMode; flareSolverrURL: string; clearanceTimeout: string; clearanceRefresh: string; mediaConcurrency: number; allowNSFW: boolean; recoveryBackoffBase: string; recoveryBackoffMax: string; }; @@ -37,6 +37,8 @@ export type SettingsConfigDTO = { }; }; +export type ClearanceMode = "manual" | "flaresolverr" | "on_demand"; + export type EgressNodeDTO = { id: string; name: string; scope: EgressScope; enabled: boolean; proxyConfigured: boolean; userAgent: string; cookieConfigured: boolean; @@ -108,7 +110,7 @@ const settingsConfigValidator = hasShape({ providerWeb: hasShape({ baseURL: isString, quotaTimeout: isString, chatTimeout: isString, streamIdleTimeout: isOptional(isString), imageTimeout: isString, videoTimeout: isString, statsigMode: isOneOf("manual", "url"), statsigManualValue: isOptional(isString), statsigManualConfigured: isBoolean, - statsigSignerURL: isString, clearanceMode: isOneOf("manual", "flaresolverr"), flareSolverrURL: isString, + statsigSignerURL: isString, clearanceMode: isOneOf("manual", "flaresolverr", "on_demand"), flareSolverrURL: isString, clearanceTimeout: isString, clearanceRefresh: isString, mediaConcurrency: isNumber, allowNSFW: isBoolean, recoveryBackoffBase: isString, recoveryBackoffMax: isString, }), providerConsole: hasShape({ baseURL: isString, chatTimeout: isString, streamIdleTimeout: isOptional(isString) }), diff --git a/frontend/src/features/settings/settings-model.ts b/frontend/src/features/settings/settings-model.ts index d31c1411..d0988aa6 100644 --- a/frontend/src/features/settings/settings-model.ts +++ b/frontend/src/features/settings/settings-model.ts @@ -83,7 +83,7 @@ export const settingsSchema = z.object({ statsigManualValue: z.string().trim().max(4096), statsigManualConfigured: z.boolean(), statsigSignerURL: z.string().trim().max(2048), - clearanceMode: z.enum(["manual", "flaresolverr"]), + clearanceMode: z.enum(["manual", "flaresolverr", "on_demand"]), flareSolverrURL: z.string().trim().max(2048), clearanceTimeout: durationSchema.refine((value) => durationSeconds(value) >= 10 && durationSeconds(value) <= 300), clearanceRefresh: durationSchema.refine((value) => durationSeconds(value) >= 60 && durationSeconds(value) <= 86_400), @@ -108,7 +108,7 @@ export const settingsSchema = z.object({ context.addIssue({ code: "custom", path: ["statsigSignerURL"], message: "invalid" }); } } - if (value.clearanceMode === "flaresolverr" && !validHTTPURL(value.flareSolverrURL)) { + if (value.clearanceMode !== "manual" && !validHTTPURL(value.flareSolverrURL)) { context.addIssue({ code: "custom", path: ["flareSolverrURL"], message: "invalid" }); } }), diff --git a/frontend/src/features/settings/settings-page.tsx b/frontend/src/features/settings/settings-page.tsx index bf4f18bf..457a691d 100644 --- a/frontend/src/features/settings/settings-page.tsx +++ b/frontend/src/features/settings/settings-page.tsx @@ -191,17 +191,18 @@ export function SettingsPage() { ( - + {t("settings.web.clearanceManual")} {t("settings.web.clearanceFlareSolverr")} + {t("settings.web.clearanceOnDemand")} )} /> - {draftClearanceMode === "flaresolverr" ? <> + {draftClearanceMode !== "manual" ? <> } /> - } /> + {draftClearanceMode === "flaresolverr" ? } /> : null} : null}
diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index bef6f887..c6290f6f 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -1941,6 +1941,14 @@ Object.assign(resources.en.translation.settings.routing as unknown as Record, { + clearanceModeHelp: "手动维护 Clearance,使用 FlareSolverr 定期主动刷新,或仅在上游明确拒绝后按需重新求解。", + clearanceOnDemand: "按需刷新", +}); +Object.assign(resources.en.translation.settings.web as unknown as Record, { + clearanceModeHelp: "Maintain Clearance manually, refresh it proactively with FlareSolverr, or solve on demand only after an explicit upstream rejection.", + clearanceOnDemand: "On demand", +}); function readStoredLanguage(): string | null { if (typeof window === "undefined") return null; try { From 0ec941bf3c9380894e4c140ec0d2439f8b7fdc4d Mon Sep 17 00:00:00 2001 From: 741075810 <31341354+741075810@users.noreply.github.com> Date: Thu, 13 Aug 2026 21:45:43 +0800 Subject: [PATCH 19/48] docs(api): state measured Console video input limits --- frontend/src/shared/i18n/index.ts | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index bdf47d9c..08ae7f32 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -1100,20 +1100,20 @@ const resources = { fieldPrompt: "用于生成或编辑图片的自然语言描述。", fieldImageCount: "需要返回的图片数量;网关会选择可满足数量的最小上游批次。", fieldAspectRatio: "输出媒体的宽高比,例如 1:1、2:3 或 16:9。", - fieldResolution: "输出分辨率;图片支持 1k/2k,视频按模型能力校验。", + fieldResolution: "输出分辨率;图片支持 1k/2k。视频 grok-imagine-video 支持 480p/720p,grok-imagine-video-1.5 额外支持 1080p,但 1080p 不能用于参考图生视频。", fieldQuality: "Image 2.0 的生成质量,可选 low 或 medium;默认 medium。", fieldResponseFormat: "图片返回格式,支持 url 或 b64_json。", fieldImageStream: "是否使用图片生成扩展 SSE 流;默认 false。", fieldEditImages: "待编辑图片,使用 image 或 images 传入 URL、Data URL 或已支持的图片引用。", fieldVideoPrompt: "视频描述;使用图片输入时可作为运动或镜头指令。", - fieldDuration: "视频时长,按上游模型支持范围校验。", - fieldVideoImage: "可选首帧图片引用,用于图生视频。", + fieldDuration: "视频时长(秒)。文生视频与首帧图生视频最长 15 秒;参考图生视频 grok-imagine-video 最长 10 秒、grok-imagine-video-1.5 最长 15 秒。", + fieldVideoImage: "可选首帧图片引用,用于图生视频;最多 1 张,不可与 reference_images 同时使用。", fieldVideoEditPrompt: "描述希望如何修改原视频。", fieldVideoExtendPrompt: "描述视频接下来应发生的内容。", fieldVideoInput: "输入视频,支持 url 或本地上传后的 file_id。", fieldVideoExtendDuration: "延长片段时长,单位秒,范围 2 到 10,默认 6。", - fieldReferenceImages: "可选参考图片数组,用于参考图视频;每项提供 url 或 file_id,不可与 image 同时使用。", - fieldReferenceAudios: "可选参考音频数组,最多 3 个内置 voice_id;可单独使用或与 reference_images 组合。", + fieldReferenceImages: "可选参考图片数组,用于参考图视频;最多 7 张,每项提供 url 或 file_id,不可与 image 同时使用。", + fieldReferenceAudios: "可选参考音频数组,最多 3 个内置 voice_id;可单独使用或与 reference_images 组合。需上游团队开启该能力,未开启时上游返回 403。", fieldRequestId: "创建视频任务时返回的 request_id。", noteChatProviders: "Build、Web 与 Console 使用独立账号池和上游协议,但向客户端返回统一的 Chat Completions 结构。", noteChatImages: "对话图片会先完成校验与上传,再绑定到本次选择的账号;不会在流开始后切换账号。", @@ -1131,7 +1131,7 @@ const resources = { noteEditSources: "远程图片会经过 SSRF、防体积超限和内容类型校验后再上传到上游。", noteVideoAsync: "创建接口只返回 request_id;生成过程异步执行并持久化任务状态。", noteVideoDuration: "时长、比例、分辨率和图片输入按当前视频模型能力校验。", - noteVideoReference: "参考图视频走 /videos/generations + reference_images;不可与 image 同用,resolution 最高 720p;reference_audios 使用内置 voice_id。", + noteVideoReference: "参考图视频走 /videos/generations + reference_images,最多 7 张;只传 1 张也保持参考图语义,不会被当成首帧。不可与 image 同用。参考图模式 resolution 最高 720p,grok-imagine-video-1.5 也不例外。reference_audios 使用内置 voice_id,需团队开启该能力。", noteVideoStrict: "视频接口严格使用当前官方字段,不保留旧项目的兼容别名。", noteVideoEditModel: "视频编辑与延长的实际路由必须指向 Console/grok-imagine-video;对外模型名可以自定义。", noteVideoBilling: "视频编辑与延长暂未返回可可靠结算的输入视频时长,因此保持可调用,并在请求审计中标记为未计费;不会消耗 API Key 的金额额度。", @@ -1730,20 +1730,20 @@ const resources = { fieldPrompt: "Natural-language instructions for image generation or editing.", 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.", + fieldResolution: "Output resolution. Images support 1k/2k. For video, grok-imagine-video supports 480p/720p and grok-imagine-video-1.5 also supports 1080p, but 1080p cannot be used for reference-to-video.", 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.", + fieldDuration: "Video duration in seconds. Text-to-video and first-frame image-to-video allow up to 15s. For reference-to-video, grok-imagine-video allows up to 10s and grok-imagine-video-1.5 up to 15s.", + fieldVideoImage: "Optional first-frame image reference for image-to-video generation. At most one image, and it cannot be combined with reference_images.", 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.", + fieldReferenceImages: "Optional reference image array for reference-to-video, up to 7 items. 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. The upstream team must have the capability enabled; otherwise upstream returns 403.", 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.", @@ -1761,7 +1761,7 @@ const resources = { 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.", + noteVideoReference: "Reference-to-video uses /videos/generations with reference_images, up to 7 items. A single item still keeps reference semantics and is not promoted to a first frame. Do not combine with image. Resolution tops out at 720p in reference mode, including grok-imagine-video-1.5. reference_audios accepts built-in voice_id values and requires team entitlement.", 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.", From 6ac4f0b858b37385875f1dae02aebe08ebf03248 Mon Sep 17 00:00:00 2001 From: lindahao Date: Thu, 13 Aug 2026 21:47:40 +0800 Subject: [PATCH 20/48] feat: add standalone video max attempts for create-phase failover Video generation often runs long, and frequent 429s during create make a dedicated retry/switch budget more valuable than waiting on a single limited account. Add routing.videoMaxAttempts as a number-or-unlimited setting used only for video create-phase account failover, keep poll pinned after create succeeds, surface real upstream statuses such as 429 in video audits, and mark provider create/poll stages so retries stay safe. --- backend/internal/app/application.go | 2 + .../internal/application/gateway/service.go | 5 + backend/internal/application/gateway/video.go | 333 ++++++++++++++---- .../application/gateway/video_test.go | 42 +++ .../internal/application/settings/service.go | 8 +- backend/internal/domain/settings/settings.go | 5 +- backend/internal/infra/config/config.go | 8 +- backend/internal/infra/provider/cli/video.go | 36 +- .../internal/infra/provider/console/media.go | 8 +- backend/internal/infra/provider/provider.go | 79 +++++ backend/internal/infra/provider/web/video.go | 16 +- .../transport/http/settings/handler.go | 5 +- .../src/features/settings/settings-api.ts | 4 +- .../src/features/settings/settings-model.ts | 5 +- .../src/features/settings/settings-page.tsx | 37 ++ frontend/src/shared/i18n/index.ts | 4 +- 16 files changed, 474 insertions(+), 123 deletions(-) diff --git a/backend/internal/app/application.go b/backend/internal/app/application.go index ca99e67c..eb86333d 100644 --- a/backend/internal/app/application.go +++ b/backend/internal/app/application.go @@ -350,6 +350,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat modelRepo.SetInvalidationObserver(invalidationService.Notify) clientKeyRepo.SetInvalidationObserver(invalidationService.Notify) gatewayService := gateway.NewService(modelService, auditService, accountService, clientKeyService, providers, selector, responseRepo, cfg.Routing.MaxAttempts) + gatewayService.UpdateVideoMaxAttempts(cfg.Routing.VideoMaxAttempts) gatewayService.UpdateMarkBuildChatDeniedAsReauth(cfg.Routing.MarkBuildChatDeniedAsReauth) gatewayService.SetLogger(logger) egressService.SetQualityProber(gatewayService) @@ -403,6 +404,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat egressManager.UpdateAccountIsolatedConnections(next.Routing.AccountIsolatedConnections) reasoningReplay.UpdateConfig(reasoningreplay.Config{Enabled: next.Routing.ReasoningReplayEnabled, TTL: next.Routing.ReasoningReplayTTL.Value()}) gatewayService.UpdateMaxAttempts(next.Routing.MaxAttempts) + gatewayService.UpdateVideoMaxAttempts(next.Routing.VideoMaxAttempts) gatewayService.UpdateMarkBuildChatDeniedAsReauth(next.Routing.MarkBuildChatDeniedAsReauth) gatewayService.UpdateBuildForbiddenReauthPolicy(next.Accounts.MarkBuildForbiddenReauth, next.Accounts.BuildForbiddenReauthCodes) auditService.UpdateWriterConfig(next.Audit.BatchSize, next.Audit.FlushInterval.Value(), next.Audit.CommitDelay.Value()) diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index e1cbde7a..d25d1c65 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -179,6 +179,7 @@ type Service struct { selector *Selector responses repository.ResponseRepository maxAttempts atomic.Int64 + videoMaxAttempts atomic.Int64 buildForbiddenReauth atomic.Pointer[buildForbiddenReauthPolicy] requestTimeout atomic.Int64 mediaJobs repository.MediaJobRepository @@ -444,6 +445,10 @@ func (s *Service) SetLogger(logger *slog.Logger) { func (s *Service) UpdateMaxAttempts(maxAttempts int) { s.maxAttempts.Store(int64(maxAttempts)) } +// UpdateVideoMaxAttempts configures create-phase account failover for video jobs. +// 0 is treated as the general default pool size for legacy configs. +func (s *Service) UpdateVideoMaxAttempts(maxAttempts int) { s.videoMaxAttempts.Store(int64(maxAttempts)) } + // UpdateMarkBuildChatDeniedAsReauth 热更新 Build chat 永久拒绝是否标 reauthRequired。 // 默认 false:仅模型级冷却;true 时按旧逻辑将账号标为失效并出池。 func (s *Service) UpdateMarkBuildChatDeniedAsReauth(enabled bool) { diff --git a/backend/internal/application/gateway/video.go b/backend/internal/application/gateway/video.go index 9b048876..0ff4012d 100644 --- a/backend/internal/application/gateway/video.go +++ b/backend/internal/application/gateway/video.go @@ -376,7 +376,7 @@ func (s *Service) processVideoJob(ctx context.Context, id string) { route, err = s.models.GetByPublicID(ctx, job.Model) } if err != nil { - s.failVideoJob(ctx, job, "model_not_found", errors.New("模型路由不存在")) + s.failVideoJob(ctx, job, "model_not_found", errors.New("模型路由不存在"), 0, nil) return } s.runVideoJob(ctx, job, route) @@ -424,29 +424,9 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model return } defer releaseInputSlot() - // 视频任务创建时已持久化账号归属;恢复只能重新获取原账号,禁止因后续 - // 轮询或结果处理失败切换到其他账号。 - 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 { - s.deferVideoJob(parent, job) - return - } - s.failVideoJob(parent, job, "account_unavailable", err) - return - } - defer lease.Release() - credential, err := s.accounts.EnsureCredential(ctx, lease.Credential, false) - if err != nil { - s.failVideoJob(parent, job, "account_unavailable", err) - return - } - lease.Credential = credential adapter, ok := s.providers.Videos(route.Provider) if !ok { - s.failVideoJob(parent, job, "provider_unavailable", ErrNoAvailableAccount) + s.failVideoJob(parent, job, "provider_unavailable", ErrNoAvailableAccount, 0, nil) return } operation := provider.VideoOperation(job.Operation) @@ -455,10 +435,9 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model } imageURL, referenceURLs, referenceAudios, videoURL, err := s.resolveVideoJobInputs(ctx, operation, job.InputJSON) if err != nil { - s.failVideoJob(parent, job, "input_unavailable", err) + s.failVideoJob(parent, job, "input_unavailable", err, 0, nil) return } - lastProgress := job.Progress duration := job.Seconds aspectRatio := job.Size resolution := job.Quality @@ -468,60 +447,136 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model case provider.VideoOperationExtend: aspectRatio, resolution = "", "" } - result, err := adapter.GenerateVideo(ctx, provider.VideoRequest{ - 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 { + + quotaMode := videoQuotaMode(route.Provider, s.providers.QuotaMode(route.Provider, route.UpstreamModel), job.Quality) + quotaRefreshGroup := s.providers.QuotaRefreshGroup(route.Provider, route.UpstreamModel) + attemptPolicy := s.videoAttemptPolicy() + excluded := make(map[uint64]bool) + failureAttempts := newFailureAttemptRecorder(http.MethodPost, "/videos/generations") + var selection *selectionSession + var lease *accountLease + var result provider.VideoResult + var lastErr error + + for attempt := 0; attemptPolicy.allows(attempt); attempt++ { + attemptStarted := time.Now() + err = nil + if lease != nil { + lease.Release() + lease = nil + } + // First try stays on the account chosen when the local job was created. + // Create-stage failures may switch accounts; poll failures never reach here as retries. + if attempt == 0 && job.AccountID > 0 && !excluded[job.AccountID] { + lease, err = s.selector.AcquirePinned(ctx, route.Provider, job.AccountID, route.ID, route.UpstreamModel, quotaMode, true) + if err != nil { + excluded[job.AccountID] = true + lease = nil + } + } + if lease == nil { + if selection == nil { + selection, err = s.selector.beginSelectionSession(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, "", excluded, false) + } + if err == nil { + lease, err = selection.Acquire(ctx, excluded, false) + } + } + if err != nil { + if parent.Err() != nil { + s.deferVideoJob(parent, job) return } - lastProgress = value - job.Progress, job.UpdatedAt = value, time.Now().UTC() - leaseUntil := job.UpdatedAt.Add(videoJobLease) - job.LeaseUntil = &leaseUntil - updateCtx, updateCancel := context.WithTimeout(context.Background(), 3*time.Second) - _ = s.mediaJobs.UpdateMediaJob(updateCtx, job) - updateCancel() - }, - }) - // Provider 已消费请求体,尽早释放 Base64 物化名额和大字符串。 - referenceURLs = nil - releaseInputSlot() - if err == nil && result.AssetID == "" && result.URL != "" { - result, err = s.persistRemoteVideo(ctx, job.ID, adapter, lease.Credential, result) - } - if err != nil { + if lastErr == nil { + lastErr = err + } + s.failVideoJob(parent, job, "account_unavailable", lastErr, 0, failureAttempts.snapshot()) + return + } + excluded[lease.Credential.ID] = true + credential, credErr := s.accounts.EnsureCredential(ctx, lease.Credential, false) + if credErr != nil { + failureAttempts.captureCredentialFailure(lease.Credential, attemptStarted, false, credErr) + lastErr = credErr + if attemptPolicy.hasNext(attempt) { + continue + } + s.failVideoJob(parent, job, "account_unavailable", credErr, 0, failureAttempts.snapshot()) + return + } + lease.Credential = credential + if job.AccountID != credential.ID || job.AccountName != credential.Name { + job.AccountID, job.AccountName = credential.ID, credential.Name + job.UpdatedAt = time.Now().UTC() + _ = s.mediaJobs.UpdateMediaJob(ctx, job) + } + + lastProgress := job.Progress + result, err = adapter.GenerateVideo(ctx, provider.VideoRequest{ + 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 { + return + } + lastProgress = value + job.Progress, job.UpdatedAt = value, time.Now().UTC() + leaseUntil := job.UpdatedAt.Add(videoJobLease) + job.LeaseUntil = &leaseUntil + updateCtx, updateCancel := context.WithTimeout(context.Background(), 3*time.Second) + _ = s.mediaJobs.UpdateMediaJob(updateCtx, job) + updateCancel() + }, + }) + if err == nil && result.AssetID == "" && result.URL != "" { + result, err = s.persistRemoteVideo(ctx, job.ID, adapter, lease.Credential, result) + } + if err == nil { + break + } + lastErr = err + captureVideoAttempt(failureAttempts, lease.Credential, attemptStarted, err) if parent.Err() != nil { s.deferVideoJob(parent, job) return } + failureCtx, failureCancel := context.WithTimeout(context.Background(), finalizationTimeout) failureHandled := false + retriableCreate := false + stage, hasStage := provider.VideoErrorStage(err) + status, hasStatus := provider.ErrorHTTPStatus(err) if errors.Is(err, provider.ErrUnauthorized) { if lease.Credential.AuthType == account.AuthTypeSSO { s.markSSOCredentialRejected(failureCtx, lease.Credential, fmt.Sprintf("%s SSO credential rejected", lease.Credential.Provider)) } failureHandled = true - } else if status, ok := provider.ErrorHTTPStatus(err); ok { + retriableCreate = !hasStage || stage == provider.VideoStageCreate + } else if hasStatus { switch { case status == http.StatusUnauthorized && lease.Credential.AuthType == account.AuthTypeSSO: s.markSSOCredentialRejected(failureCtx, lease.Credential, fmt.Sprintf("%s SSO credential rejected", lease.Credential.Provider)) failureHandled = true + retriableCreate = !hasStage || stage == provider.VideoStageCreate case status == http.StatusForbidden && s.providers.RetryForbiddenAsEgress(lease.Credential.Provider): - // Web Provider 已对 anti-bot 403 降低出口健康并重建浏览器会话; - // 视频请求已提交,不能换号重试,也不能误伤账号池。 - // 符合资格的 Build 主地址 403 由 Adapter 尝试 XAI,不在此禁用账号。 + // Web anti-bot 403 is egress-scoped. Retry create on same account once via policy budget. failureHandled = true + if !hasStage || stage == provider.VideoStageCreate { + delete(excluded, lease.Credential.ID) + if selection != nil { + selection.RetryAccount(lease.Credential.ID) + } + retriableCreate = true + } case status == http.StatusForbidden && lease.Credential.Provider == account.ProviderBuild: if !account.IsBuildSuper(lease.Credential, lease.Billing) { - // 非 Super 的 403 按账号级故障处理;auto 模式不会因此回退 XAI。 s.selector.MarkFailure(failureCtx, lease.Credential, status, 0) } - // Super(Billing paid 或 entitlement)的 403 保持服务级处理。 failureHandled = true + retriableCreate = (!hasStage || stage == provider.VideoStageCreate) && !account.IsBuildSuper(lease.Credential, lease.Billing) case (status == http.StatusPaymentRequired || status == http.StatusTooManyRequests) && lease.QuotaMode != "": exhausted, reconcileErr := s.accounts.ReconcileRateLimit(failureCtx, lease.Credential.ID, lease.QuotaMode, 0) s.selector.MarkQuotaStateChanged(lease.Credential.Provider, lease.Credential.ID) @@ -529,27 +584,57 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model s.selector.MarkFailure(failureCtx, lease.Credential, status, 0) } failureHandled = true - case status >= http.StatusInternalServerError: - // 5xx 是 Provider 服务级故障,不应让某个账号退出号池。 + retriableCreate = !hasStage || stage == provider.VideoStageCreate + case status == http.StatusTooManyRequests || status == http.StatusPaymentRequired: + s.selector.MarkFailure(failureCtx, lease.Credential, status, 0) failureHandled = true + retriableCreate = !hasStage || stage == provider.VideoStageCreate + case status >= http.StatusInternalServerError: + // 5xx is provider-level; keep the account and allow create-stage failover. + failureHandled = true + retriableCreate = !hasStage || stage == provider.VideoStageCreate default: s.selector.MarkFailure(failureCtx, lease.Credential, status, 0) failureHandled = true + retriableCreate = (!hasStage || stage == provider.VideoStageCreate) && status != http.StatusBadRequest && status != http.StatusUnprocessableEntity } } if !failureHandled && !provider.IsMediaPostProcessingError(err) { s.selector.MarkFailure(failureCtx, lease.Credential, 0, 0) + retriableCreate = !hasStage || stage == provider.VideoStageCreate } failureCancel() applyMediaJobEgress(&job, egressTrace, route.Provider) s.logVideoGenerationFailure(job, lease.Credential, err) - failureCode, publicErr := "generation_failed", err - if status, ok := provider.ErrorHTTPStatus(err); errors.Is(err, provider.ErrUnauthorized) || (ok && (status == http.StatusUnauthorized || status == http.StatusForbidden)) { - failureCode, publicErr = "provider_unavailable", errors.New("上游服务暂不可用") + + // Poll/post-processing failures are bound to the already-created upstream job. + if provider.IsMediaPostProcessingError(err) || (hasStage && stage == provider.VideoStagePoll) || !retriableCreate || !attemptPolicy.hasNext(attempt) { + failureCode, publicErr := "generation_failed", err + upstreamStatus := 0 + if hasStatus { + upstreamStatus = status + } + if errors.Is(err, provider.ErrUnauthorized) || (hasStatus && (status == http.StatusUnauthorized || status == http.StatusForbidden)) { + failureCode, publicErr = "provider_unavailable", errors.New("上游服务暂不可用") + } else if hasStatus && status == http.StatusTooManyRequests { + failureCode = "rate_limited" + } + s.failVideoJob(parent, job, failureCode, publicErr, upstreamStatus, failureAttempts.snapshot()) + return } - s.failVideoJob(parent, job, failureCode, publicErr) + // Create-stage failure: switch account according to runtime attempt policy. + continue + } + if lease == nil { + s.failVideoJob(parent, job, "account_unavailable", ErrNoAvailableAccount, 0, failureAttempts.snapshot()) return } + defer lease.Release() + + // Provider 已消费请求体,尽早释放 Base64 物化名额和大字符串。 + referenceURLs = nil + releaseInputSlot() + now := time.Now().UTC() job.Status, job.Progress, job.UpstreamURL, job.ContentType = media.StatusCompleted, 100, result.URL, result.ContentType // 成功终态必须清空历史错误字段,避免管理端/恢复路径把中间失败文案当成最终结果。 @@ -580,7 +665,7 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model s.selector.ConsumeQuota(route.Provider, job.AccountID, decrementMode, 1) } } - if err := s.recordVideoAudit(context.Background(), job, time.Since(startedAt).Milliseconds()); err != nil { + if err := s.recordVideoAudit(context.Background(), job, time.Since(startedAt).Milliseconds(), http.StatusOK, failureAttempts.snapshot()); 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 && refreshMode != "" { @@ -798,14 +883,14 @@ func (s *Service) reconcileVideoUsage(ctx context.Context) error { if job.CompletedAt != nil { durationMS = max(int64(0), job.CompletedAt.Sub(job.CreatedAt).Milliseconds()) } - if err := s.recordVideoAudit(ctx, job, durationMS); err != nil { + if err := s.recordVideoAudit(ctx, job, durationMS, 0, nil); err != nil { result = firstError(result, fmt.Errorf("任务 %s: %w", job.ID, err)) } } return result } -func (s *Service) recordVideoAudit(ctx context.Context, job media.Job, durationMS int64) error { +func (s *Service) recordVideoAudit(ctx context.Context, job media.Job, durationMS int64, upstreamStatus int, attempts []audit.Attempt) error { var accountID *uint64 if job.AccountID > 0 { value := job.AccountID @@ -815,16 +900,7 @@ func (s *Service) recordVideoAudit(ctx context.Context, job media.Job, durationM if job.CompletedAt != nil && !job.CompletedAt.IsZero() { createdAt = job.CompletedAt.UTC() } - statusCode := http.StatusOK - if job.Status == media.StatusFailed { - statusCode = http.StatusBadGateway - switch job.ErrorCode { - case "account_unavailable", "provider_unavailable": - statusCode = http.StatusServiceUnavailable - case "model_not_found": - statusCode = http.StatusNotFound - } - } + statusCode := resolveVideoAuditStatusCode(job, upstreamStatus, attempts) record := audit.Record{ EventID: "video_usage_" + job.ID, RequestID: job.RequestID, ClientKeyID: job.ClientKeyID, ClientKeyName: job.ClientKeyName, ModelRouteID: job.ModelRouteID, ModelPublicID: job.Model, ModelUpstreamModel: job.UpstreamModel, @@ -832,7 +908,7 @@ func (s *Service) recordVideoAudit(ctx context.Context, job media.Job, durationM AccountID: accountID, AccountName: job.AccountName, StatusCode: statusCode, ErrorCode: job.ErrorCode, EgressNodeID: job.EgressNodeID, EgressNodeName: job.EgressNodeName, EgressScope: job.EgressScope, EgressMode: audit.EgressMode(job.EgressMode), MediaInputImages: int64(job.InputImageCount), - DurationMS: durationMS, CreatedAt: createdAt, + DurationMS: durationMS, AttemptCount: len(attempts), Attempts: append([]audit.Attempt(nil), attempts...), CreatedAt: createdAt, } if job.Status == media.StatusCompleted && job.Seconds > 0 { record.MediaOutputSeconds = int64(max(0, job.Seconds)) @@ -1037,9 +1113,13 @@ func videoInputReferences(imageURL string, referenceURLs []string) []string { return values } -func (s *Service) failVideoJob(ctx context.Context, job media.Job, code string, err error) { +func (s *Service) failVideoJob(ctx context.Context, job media.Job, code string, err error, upstreamStatus int, attempts []audit.Attempt) { now := time.Now().UTC() - job.Status, job.ErrorCode, job.ErrorMessage = media.StatusFailed, code, err.Error() + message := "" + if err != nil { + message = err.Error() + } + job.Status, job.ErrorCode, job.ErrorMessage = media.StatusFailed, code, message if len(job.ErrorMessage) > 512 { job.ErrorMessage = job.ErrorMessage[:512] } @@ -1048,13 +1128,112 @@ func (s *Service) failVideoJob(ctx context.Context, job media.Job, code string, s.logger.Error("video_job_terminal_write_failed", "job_id", job.ID, "error", updateErr) return } - if auditErr := s.recordVideoAudit(context.Background(), job, max(int64(0), now.Sub(job.CreatedAt).Milliseconds())); auditErr != nil { + if auditErr := s.recordVideoAudit(context.Background(), job, max(int64(0), now.Sub(job.CreatedAt).Milliseconds()), upstreamStatus, attempts); auditErr != nil { s.logger.Error("video_usage_record_failed", "job_id", job.ID, "event_id", "video_usage_"+job.ID, "error", auditErr) } s.cancelBillingReservation("video_usage_" + job.ID) s.releaseVideoInputs(job) } +func resolveVideoAuditStatusCode(job media.Job, upstreamStatus int, attempts []audit.Attempt) int { + if job.Status != media.StatusFailed { + return http.StatusOK + } + if upstreamStatus >= 100 && upstreamStatus <= 599 { + return upstreamStatus + } + for i := len(attempts) - 1; i >= 0; i-- { + if attempts[i].UpstreamStatusCode != nil { + status := *attempts[i].UpstreamStatusCode + if status >= 100 && status <= 599 { + return status + } + } + } + if status := parseUpstreamStatusFromMessage(job.ErrorMessage); status > 0 { + return status + } + switch job.ErrorCode { + case "account_unavailable", "provider_unavailable": + return http.StatusServiceUnavailable + case "model_not_found": + return http.StatusNotFound + case "rate_limited": + return http.StatusTooManyRequests + default: + return http.StatusBadGateway + } +} + +func parseUpstreamStatusFromMessage(message string) int { + message = strings.TrimSpace(message) + if message == "" { + return 0 + } + // Console/Web summaries commonly look like: "Console 媒体上游返回 429: ..." + for _, token := range []string{"返回 ", "status ", "Status ", "HTTP "} { + if idx := strings.Index(message, token); idx >= 0 { + rest := strings.TrimSpace(message[idx+len(token):]) + n := 0 + for i := 0; i < len(rest); i++ { + ch := rest[i] + if ch < '0' || ch > '9' { + break + } + n = n*10 + int(ch-'0') + if n > 599 { + return 0 + } + } + if n >= 100 && n <= 599 { + return n + } + } + } + return 0 +} + +func captureVideoAttempt(recorder *failureAttemptRecorder, credential account.Credential, startedAt time.Time, err error) { + if recorder == nil || err == nil { + return + } + status, hasStatus := provider.ErrorHTTPStatus(err) + stage := "upstream_response" + if videoStage, ok := provider.VideoErrorStage(err); ok { + stage = "video_" + string(videoStage) + } + attempt := audit.Attempt{ + Source: audit.AttemptSourceUpstreamHTTP, + Stage: stage, + AccountID: auditAccountID(credential.ID), + AccountName: credential.Name, + Method: recorder.method, + RequestPath: recorder.path, + StartedAt: startedAt.UTC(), + DurationMS: time.Since(startedAt).Milliseconds(), + TransportError: sanitizeDiagnosticText(err.Error(), diagnosticTextLimit), + ErrorChain: errorFrames(err), + } + if hasStatus { + value := status + attempt.UpstreamStatusCode = &value + attempt.UpstreamStatus = http.StatusText(status) + body := []byte(sanitizeDiagnosticText(err.Error(), diagnosticTextLimit)) + attempt.ResponseBody = body + } + recorder.append(attempt) +} + +func (s *Service) videoAttemptPolicy() routingAttemptPolicy { + configured := int(s.videoMaxAttempts.Load()) + // Legacy installs may still have 0 from the short-lived "inherit" default. + // Treat it as the general default pool size instead of reintroducing inherit UI. + if configured == 0 { + configured = 999 + } + return newRoutingAttemptPolicy(configured) +} + func (s *Service) releaseVideoInputs(job media.Job) { if s.mediaAssets == nil { return diff --git a/backend/internal/application/gateway/video_test.go b/backend/internal/application/gateway/video_test.go index 05f82ff0..fc050300 100644 --- a/backend/internal/application/gateway/video_test.go +++ b/backend/internal/application/gateway/video_test.go @@ -500,3 +500,45 @@ func (r *videoUsageRepository) MarkMediaJobUsageRecorded(_ context.Context, _ st r.job.UsageRecordedAt = &recordedAt return nil } + + +func TestResolveVideoAuditStatusCodePrefersUpstream429(t *testing.T) { + status429 := http.StatusTooManyRequests + job := media.Job{Status: media.StatusFailed, ErrorCode: "generation_failed", ErrorMessage: "Console 媒体上游返回 429: Too many requests"} + if got := resolveVideoAuditStatusCode(job, 0, nil); got != http.StatusTooManyRequests { + t.Fatalf("message status = %d", got) + } + if got := resolveVideoAuditStatusCode(job, http.StatusTooManyRequests, nil); got != http.StatusTooManyRequests { + t.Fatalf("explicit status = %d", got) + } + attempts := []audit.Attempt{{UpstreamStatusCode: &status429}} + job.ErrorMessage = "wrapped" + if got := resolveVideoAuditStatusCode(job, 0, attempts); got != http.StatusTooManyRequests { + t.Fatalf("attempt status = %d", got) + } + job.ErrorCode = "rate_limited" + job.ErrorMessage = "" + if got := resolveVideoAuditStatusCode(job, 0, nil); got != http.StatusTooManyRequests { + t.Fatalf("code status = %d", got) + } +} + +func TestVideoAttemptPolicyStandaloneAndUnlimited(t *testing.T) { + service := &Service{} + service.UpdateMaxAttempts(3) + service.UpdateVideoMaxAttempts(0) + policy := service.videoAttemptPolicy() + if policy.unlimited || policy.limit != 999 { + t.Fatalf("legacy zero policy = %#v", policy) + } + service.UpdateVideoMaxAttempts(-1) + policy = service.videoAttemptPolicy() + if !policy.unlimited { + t.Fatalf("unlimited video policy = %#v", policy) + } + service.UpdateVideoMaxAttempts(5) + policy = service.videoAttemptPolicy() + if policy.unlimited || policy.limit != 5 { + t.Fatalf("standalone policy = %#v", policy) + } +} diff --git a/backend/internal/application/settings/service.go b/backend/internal/application/settings/service.go index e7b790a9..79249c6d 100644 --- a/backend/internal/application/settings/service.go +++ b/backend/internal/application/settings/service.go @@ -99,6 +99,7 @@ type RoutingConfig struct { CooldownMax string CapacityWait string MaxAttempts int + VideoMaxAttempts int PreferFreeBuild bool MarkBuildChatDeniedAsReauth bool MarkBuildChatDeniedAsReauthProvided bool @@ -388,7 +389,7 @@ func applyDomainConfig(base config.Config, value settingsdomain.Config) config.C } base.Routing = config.RoutingConfig{ StickyTTL: config.Duration(value.Routing.StickyTTL), CooldownBase: config.Duration(value.Routing.CooldownBase), - CooldownMax: config.Duration(value.Routing.CooldownMax), CapacityWait: config.Duration(capacityWait), MaxAttempts: value.Routing.MaxAttempts, + CooldownMax: config.Duration(value.Routing.CooldownMax), CapacityWait: config.Duration(capacityWait), MaxAttempts: value.Routing.MaxAttempts, VideoMaxAttempts: value.Routing.VideoMaxAttempts, MarkBuildChatDeniedAsReauth: value.Routing.MarkBuildChatDeniedAsReauth, PreferFreeBuild: value.Routing.PreferFreeBuild, AccountIsolatedConnections: accountIsolatedConnections, @@ -470,7 +471,7 @@ func toDomainConfig(value config.Config) settingsdomain.Config { }, Routing: settingsdomain.RoutingConfig{ StickyTTL: value.Routing.StickyTTL.Value(), CooldownBase: value.Routing.CooldownBase.Value(), - CooldownMax: value.Routing.CooldownMax.Value(), CapacityWait: value.Routing.CapacityWait.Value(), MaxAttempts: value.Routing.MaxAttempts, + CooldownMax: value.Routing.CooldownMax.Value(), CapacityWait: value.Routing.CapacityWait.Value(), MaxAttempts: value.Routing.MaxAttempts, VideoMaxAttempts: value.Routing.VideoMaxAttempts, MarkBuildChatDeniedAsReauth: value.Routing.MarkBuildChatDeniedAsReauth, PreferFreeBuild: value.Routing.PreferFreeBuild, AccountIsolatedConnections: &accountIsolatedConnections, @@ -555,6 +556,7 @@ func mergeEditable(current config.Config, input EditableConfig) (config.Config, next.Media.CleanupThresholdPercent = input.Media.CleanupThresholdPercent next.Frontend.PublicAPIBaseURLOverride = strings.TrimSpace(input.Frontend.PublicAPIBaseURL) next.Routing.MaxAttempts = input.Routing.MaxAttempts + next.Routing.VideoMaxAttempts = input.Routing.VideoMaxAttempts next.Routing.PreferFreeBuild = input.Routing.PreferFreeBuild if input.Routing.AccountIsolatedConnectionsProvided { next.Routing.AccountIsolatedConnections = input.Routing.AccountIsolatedConnections @@ -695,7 +697,7 @@ func toEditable(cfg config.Config) EditableConfig { }, Routing: RoutingConfig{ StickyTTL: cfg.Routing.StickyTTL.String(), CooldownBase: cfg.Routing.CooldownBase.String(), - CooldownMax: cfg.Routing.CooldownMax.String(), CapacityWait: cfg.Routing.CapacityWait.String(), MaxAttempts: cfg.Routing.MaxAttempts, + CooldownMax: cfg.Routing.CooldownMax.String(), CapacityWait: cfg.Routing.CapacityWait.String(), MaxAttempts: cfg.Routing.MaxAttempts, VideoMaxAttempts: cfg.Routing.VideoMaxAttempts, MarkBuildChatDeniedAsReauth: cfg.Routing.MarkBuildChatDeniedAsReauth, MarkBuildChatDeniedAsReauthProvided: true, PreferFreeBuild: cfg.Routing.PreferFreeBuild, diff --git a/backend/internal/domain/settings/settings.go b/backend/internal/domain/settings/settings.go index a9ec5b0e..2a00befc 100644 --- a/backend/internal/domain/settings/settings.go +++ b/backend/internal/domain/settings/settings.go @@ -102,8 +102,9 @@ type RoutingConfig struct { CooldownBase time.Duration CooldownMax time.Duration CapacityWait time.Duration - MaxAttempts int - PreferFreeBuild bool + MaxAttempts int + VideoMaxAttempts int + PreferFreeBuild bool // MarkBuildChatDeniedAsReauth 为 true 时,Build chat 权限拒绝标 reauthRequired,默认 false 保留模型级冷却。 MarkBuildChatDeniedAsReauth bool // AccountIsolatedConnections is optional so persisted payloads written by diff --git a/backend/internal/infra/config/config.go b/backend/internal/infra/config/config.go index a87ce043..a2efc88b 100644 --- a/backend/internal/infra/config/config.go +++ b/backend/internal/infra/config/config.go @@ -215,8 +215,9 @@ type RoutingConfig struct { CooldownBase Duration `yaml:"cooldownBase"` CooldownMax Duration `yaml:"cooldownMax"` CapacityWait Duration `yaml:"capacityWait"` - MaxAttempts int `yaml:"maxAttempts"` - PreferFreeBuild bool `yaml:"preferFreeBuild"` + MaxAttempts int `yaml:"maxAttempts"` + VideoMaxAttempts int `yaml:"videoMaxAttempts"` + PreferFreeBuild bool `yaml:"preferFreeBuild"` // MarkBuildChatDeniedAsReauth 为 true 时,Build chat 权限拒绝标 reauthRequired,默认 false。 MarkBuildChatDeniedAsReauth bool `yaml:"markBuildChatDeniedAsReauth"` AccountIsolatedConnections bool `yaml:"accountIsolatedConnections"` @@ -615,7 +616,7 @@ func (c Config) Validate() error { if c.Provider.Web.RecoveryBackoffBase.Value() < 5*time.Second || c.Provider.Web.RecoveryBackoffMax.Value() < c.Provider.Web.RecoveryBackoffBase.Value() || c.Provider.Web.RecoveryBackoffMax.Value() > 6*time.Hour { return errors.New("provider.web 恢复退避配置无效") } - if c.Routing.StickyTTL.Value() <= 0 || c.Routing.StickyTTL.Value() > maxRoutingTTL || c.Routing.CooldownBase.Value() <= 0 || c.Routing.CooldownMax.Value() < c.Routing.CooldownBase.Value() || c.Routing.CooldownMax.Value() > maxRoutingCooldown || c.Routing.CapacityWait.Value() <= 0 || c.Routing.CapacityWait.Value() > maxRoutingCapacityWait || c.Routing.MaxAttempts < unlimitedRoutingAttempts || c.Routing.MaxAttempts == 0 || c.Routing.MaxAttempts > maxRoutingAttempts { + if c.Routing.StickyTTL.Value() <= 0 || c.Routing.StickyTTL.Value() > maxRoutingTTL || c.Routing.CooldownBase.Value() <= 0 || c.Routing.CooldownMax.Value() < c.Routing.CooldownBase.Value() || c.Routing.CooldownMax.Value() > maxRoutingCooldown || c.Routing.CapacityWait.Value() <= 0 || c.Routing.CapacityWait.Value() > maxRoutingCapacityWait || (c.Routing.MaxAttempts < unlimitedRoutingAttempts || c.Routing.MaxAttempts == 0 || c.Routing.MaxAttempts > maxRoutingAttempts) || (c.Routing.VideoMaxAttempts < unlimitedRoutingAttempts || c.Routing.VideoMaxAttempts > maxRoutingAttempts) { return errors.New("routing 配置无效") } if c.Routing.SegmentedMinCandidates < 100 || c.Routing.SegmentedMinCandidates > 1000000 || @@ -826,6 +827,7 @@ func defaultConfig() Config { CooldownMax: Duration(30 * time.Minute), CapacityWait: Duration(500 * time.Millisecond), MaxAttempts: 999, + VideoMaxAttempts: 999, MarkBuildChatDeniedAsReauth: false, PreferFreeBuild: false, AccountIsolatedConnections: false, diff --git a/backend/internal/infra/provider/cli/video.go b/backend/internal/infra/provider/cli/video.go index 5f771ef3..18408cf9 100644 --- a/backend/internal/infra/provider/cli/video.go +++ b/backend/internal/infra/provider/cli/video.go @@ -157,11 +157,11 @@ func boundDiagnosticText(value string, limit int) string { // 其他 auto Super 账号仅在当次 Build 创建返回 403 后探测 XAI。 func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoRequest) (provider.VideoResult, error) { if total := buildVideoImageCount(request); total > buildVideoMaxImages { - return provider.VideoResult{}, fmt.Errorf("Build grok-imagine-video-1.5 最多支持 %d 张输入图,当前为 %d 张", buildVideoMaxImages, total) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, fmt.Errorf("Build grok-imagine-video-1.5 最多支持 %d 张输入图,当前为 %d 张", buildVideoMaxImages, total)) } accessToken, err := a.cipher.Decrypt(request.Credential.EncryptedAccessToken) if err != nil { - return provider.VideoResult{}, err + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) } credential := request.Credential routeMode := normalizedBuildRouteMode(credential) @@ -173,17 +173,17 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque primaryBase := a.primaryBaseURL() payload, err := videoCreatePayload(request, "", buildVideoRequestProfile) if err != nil { - return provider.VideoResult{}, err + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) } body, err := json.Marshal(payload) if err != nil { - return provider.VideoResult{}, err + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) } createResp, createErr := a.doVideoJSON(ctx, credential, accessToken, http.MethodPost, primaryBase, "/videos/generations", body, buildVideoRequestProfile, true) if createErr == nil { jobID, parseErr := parseVideoCreateResponse(createResp) if parseErr != nil { - return provider.VideoResult{}, parseErr + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, parseErr) } if request.Progress != nil { request.Progress(1) @@ -192,10 +192,10 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque } var upstream *videoUpstreamError if !asVideoUpstreamError(createErr, &upstream) || !isHTTPForbidden(upstream.status) { - return provider.VideoResult{}, createErr + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, createErr) } if routeMode == account.BuildRouteBuild || !xaiEligible { - return provider.VideoResult{}, createErr + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, createErr) } // 已确认 Super 的主地址 403:签发 upload_url 后探测 XAI;创建成功才标记降级。 return a.generateVideoOnXAI(ctx, request, credential, accessToken, true) @@ -204,7 +204,7 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque func (a *Adapter) generateVideoOnXAI(ctx context.Context, request provider.VideoRequest, credential account.Credential, accessToken string, recordFallback bool) (provider.VideoResult, error) { issuer := a.uploadIssuerRef() if issuer == nil { - return provider.VideoResult{}, fmt.Errorf("XAI 视频需要媒体上传接收服务") + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, fmt.Errorf("XAI 视频需要媒体上传接收服务")) } jobKey := strings.TrimSpace(request.JobID) if jobKey == "" { @@ -213,25 +213,25 @@ func (a *Adapter) generateVideoOnXAI(ctx context.Context, request provider.Video uploadURL, assetID, err := issuer.IssueVideoUpload(ctx, jobKey) if err != nil { // 配置错误(例如 PublicAPIBaseURL 不可用)不得误标降级。 - return provider.VideoResult{}, err + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) } payload, err := videoCreatePayload(request, uploadURL, xaiVideoRequestProfile) if err != nil { - return provider.VideoResult{}, err + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) } body, err := json.Marshal(payload) if err != nil { - return provider.VideoResult{}, err + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) } base := a.fallbackBaseURL() createResp, err := a.doVideoJSON(ctx, credential, accessToken, http.MethodPost, base, "/videos/generations", body, xaiVideoRequestProfile, true) if err != nil { - return provider.VideoResult{}, err + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) } // 必须先解析到可用 job ID,再标记降级;畸形 2xx 不得激活或本地置位。 jobID, err := parseVideoCreateResponse(createResp) if err != nil { - return provider.VideoResult{}, err + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) } if recordFallback { a.activateBuildAPIFallback(ctx, &credential) @@ -354,17 +354,17 @@ func (a *Adapter) pollVideoJob(ctx context.Context, credential account.Credentia for { statusBody, err := a.doVideoJSON(ctx, credential, accessToken, http.MethodGet, base, "/videos/"+url.PathEscape(jobID), nil, profile, false) if err != nil { - return provider.VideoResult{}, err + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStagePoll, 0, err) } result, done, pollErr := parseVideoStatusResponse(statusBody, progress, assetID != "") if pollErr != nil { - return provider.VideoResult{}, pollErr + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStagePoll, 0, pollErr) } if done { if assetID != "" { issuer := a.uploadIssuerRef() if issuer == nil { - return provider.VideoResult{}, fmt.Errorf("XAI 视频需要媒体上传接收服务") + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStagePoll, 0, fmt.Errorf("XAI 视频需要媒体上传接收服务")) } contentType, waitErr := issuer.WaitVideoUpload(ctx, assetID) if waitErr != nil { @@ -372,7 +372,7 @@ func (a *Adapter) pollVideoJob(ctx context.Context, credential account.Credentia if result.URL != "" { return result, nil } - return provider.VideoResult{}, waitErr + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStagePoll, 0, waitErr) } if contentType == "" { contentType = "video/mp4" @@ -383,7 +383,7 @@ func (a *Adapter) pollVideoJob(ctx context.Context, credential account.Credentia } select { case <-ctx.Done(): - return provider.VideoResult{}, ctx.Err() + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStagePoll, 0, ctx.Err()) case <-ticker.C: } } diff --git a/backend/internal/infra/provider/console/media.go b/backend/internal/infra/provider/console/media.go index b0f04a2a..1f284bec 100644 --- a/backend/internal/infra/provider/console/media.go +++ b/backend/internal/infra/provider/console/media.go @@ -611,11 +611,11 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque } created, err := a.doConsoleVideoJSON(ctx, request.Credential, token, lease, http.MethodPost, consoleV1Endpoint(baseURL, createPath), body) if err != nil { - return provider.VideoResult{}, err + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) } requestID, err := parseConsoleVideoCreate(created) if err != nil { - return provider.VideoResult{}, err + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) } if request.Progress != nil { request.Progress(1) @@ -625,11 +625,11 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque for { statusBody, pollErr := a.doConsoleVideoJSON(ctx, request.Credential, token, lease, http.MethodGet, consoleV1Endpoint(baseURL, "/videos/"+url.PathEscape(requestID)), nil) if pollErr != nil { - return provider.VideoResult{}, pollErr + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStagePoll, 0, pollErr) } result, done, parseErr := parseConsoleVideoStatus(statusBody, request.Progress) if parseErr != nil { - return provider.VideoResult{}, parseErr + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStagePoll, 0, parseErr) } if done { return result, nil diff --git a/backend/internal/infra/provider/provider.go b/backend/internal/infra/provider/provider.go index 1ed13440..5405fb38 100644 --- a/backend/internal/infra/provider/provider.go +++ b/backend/internal/infra/provider/provider.go @@ -63,6 +63,85 @@ func ErrorHTTPStatus(err error) (int, bool) { return status, status > 0 } +// VideoStage identifies which phase of an asynchronous video job failed. +type VideoStage string + +const ( + VideoStageCreate VideoStage = "create" + VideoStagePoll VideoStage = "poll" +) + +// VideoStageError marks whether a video failure happened before the upstream +// job was created (safe to switch accounts) or while polling an existing job. +type VideoStageError struct { + Stage VideoStage + Status int + Err error +} + +func (e *VideoStageError) Error() string { + if e == nil { + return "video request failed" + } + if e.Err != nil { + return e.Err.Error() + } + if e.Status > 0 { + return fmt.Sprintf("video %s failed with status %d", e.Stage, e.Status) + } + return fmt.Sprintf("video %s failed", e.Stage) +} + +func (e *VideoStageError) Unwrap() error { + if e == nil { + return nil + } + return e.Err +} + +func (e *VideoStageError) HTTPStatusCode() int { + if e == nil { + return 0 + } + if e.Status > 0 { + return e.Status + } + return ErrorHTTPStatusOrZero(e.Err) +} + +// ErrorHTTPStatusOrZero extracts an upstream status or returns 0. +func ErrorHTTPStatusOrZero(err error) int { + status, ok := ErrorHTTPStatus(err) + if !ok { + return 0 + } + return status +} + +// VideoErrorStage reports the video phase for an error chain. +func VideoErrorStage(err error) (VideoStage, bool) { + var stageErr *VideoStageError + if !errors.As(err, &stageErr) || stageErr == nil || stageErr.Stage == "" { + return "", false + } + return stageErr.Stage, true +} + +// WrapVideoStage annotates err with the video phase and optional HTTP status. +func WrapVideoStage(stage VideoStage, status int, err error) error { + if err == nil { + return nil + } + var existing *VideoStageError + if errors.As(err, &existing) { + return err + } + if status <= 0 { + status = ErrorHTTPStatusOrZero(err) + } + return &VideoStageError{Stage: stage, Status: status, Err: err} +} + // ErrorRetryAfter extracts a positive retry delay from an error chain. func ErrorRetryAfter(err error) time.Duration { var retryError RetryAfterError diff --git a/backend/internal/infra/provider/web/video.go b/backend/internal/infra/provider/web/video.go index c0c502a6..82330a98 100644 --- a/backend/internal/infra/provider/web/video.go +++ b/backend/internal/infra/provider/web/video.go @@ -211,11 +211,11 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque cfg := a.config() token, err := a.cipher.Decrypt(request.Credential.EncryptedAccessToken) if err != nil { - return provider.VideoResult{}, err + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) } lease, err := a.egress.AcquireCredential(ctx, domainegress.ScopeWeb, request.Credential) if err != nil { - return provider.VideoResult{}, err + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) } defer lease.Release() parentID := "" @@ -232,7 +232,7 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque for _, rawReference := range rawReferences { reference, referenceErr := a.prepareVideoReference(ctx, cfg, lease, token, rawReference) if referenceErr != nil { - return provider.VideoResult{}, referenceErr + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, referenceErr) } references = append(references, reference) } @@ -242,11 +242,11 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque parentID, err = a.createMediaPost(ctx, cfg, lease, token, "MEDIA_POST_TYPE_VIDEO", "", request.Prompt, "video_prompt_media_post") } if err != nil { - return provider.VideoResult{}, err + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) } segments := videoSegments(request.Duration) if len(segments) == 0 { - return provider.VideoResult{}, fmt.Errorf("duration 必须在 1 到 15 秒之间") + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, fmt.Errorf("duration 必须在 1 到 15 秒之间")) } ratio := resolveAspectRatio(request.AspectRatio) resolution := request.Resolution @@ -256,7 +256,7 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque payload := videoCreatePayload(request.Prompt, parentID, ratio, resolution, segments[0], references) response, err := a.postJSON(ctx, cfg, lease, token, cfg.BaseURL+"/rest/app-chat/conversations/new", payload, time.Duration(cfg.VideoTimeoutSeconds)*time.Second) if err != nil { - return provider.VideoResult{}, err + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) } result, _, parseErr := parseVideoStream(response, request.Progress) _ = response.Body.Close() @@ -264,10 +264,10 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque if upstreamErr, ok := parseErr.(*webMediaUpstreamError); ok { a.logWebMediaUpstreamRejection("video_generation", response, upstreamErr) } - return provider.VideoResult{}, parseErr + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, parseErr) } if result.URL == "" { - return provider.VideoResult{}, fmt.Errorf("视频生成完成但没有返回内容 URL") + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, fmt.Errorf("视频生成完成但没有返回内容 URL")) } return result, nil } diff --git a/backend/internal/transport/http/settings/handler.go b/backend/internal/transport/http/settings/handler.go index 52a1a9e0..06849104 100644 --- a/backend/internal/transport/http/settings/handler.go +++ b/backend/internal/transport/http/settings/handler.go @@ -102,6 +102,7 @@ type routingConfigDTO struct { CooldownMax string `json:"cooldownMax"` CapacityWait string `json:"capacityWait"` MaxAttempts int `json:"maxAttempts"` + VideoMaxAttempts int `json:"videoMaxAttempts"` PreferFreeBuild bool `json:"preferFreeBuild"` MarkBuildChatDeniedAsReauth *bool `json:"markBuildChatDeniedAsReauth,omitempty"` AccountIsolatedConnections *bool `json:"accountIsolatedConnections,omitempty"` @@ -223,7 +224,7 @@ func (value settingsConfigDTO) toApplication() settingsapp.EditableConfig { }, Routing: settingsapp.RoutingConfig{ StickyTTL: value.Routing.StickyTTL, CooldownBase: value.Routing.CooldownBase, - CooldownMax: value.Routing.CooldownMax, CapacityWait: value.Routing.CapacityWait, MaxAttempts: value.Routing.MaxAttempts, + CooldownMax: value.Routing.CooldownMax, CapacityWait: value.Routing.CapacityWait, MaxAttempts: value.Routing.MaxAttempts, VideoMaxAttempts: value.Routing.VideoMaxAttempts, PreferFreeBuild: value.Routing.PreferFreeBuild, MarkBuildChatDeniedAsReauth: boolValue(value.Routing.MarkBuildChatDeniedAsReauth), MarkBuildChatDeniedAsReauthProvided: value.Routing.MarkBuildChatDeniedAsReauth != nil, @@ -305,7 +306,7 @@ func newSettingsResponse(value settingsapp.Snapshot) settingsResponse { }, Routing: routingConfigDTO{ StickyTTL: config.Routing.StickyTTL, CooldownBase: config.Routing.CooldownBase, - CooldownMax: config.Routing.CooldownMax, CapacityWait: config.Routing.CapacityWait, MaxAttempts: config.Routing.MaxAttempts, + CooldownMax: config.Routing.CooldownMax, CapacityWait: config.Routing.CapacityWait, MaxAttempts: config.Routing.MaxAttempts, VideoMaxAttempts: config.Routing.VideoMaxAttempts, MarkBuildChatDeniedAsReauth: boolPointer(config.Routing.MarkBuildChatDeniedAsReauth), PreferFreeBuild: config.Routing.PreferFreeBuild, AccountIsolatedConnections: boolPointer(config.Routing.AccountIsolatedConnections), diff --git a/frontend/src/features/settings/settings-api.ts b/frontend/src/features/settings/settings-api.ts index efaf59aa..c09a3d4d 100644 --- a/frontend/src/features/settings/settings-api.ts +++ b/frontend/src/features/settings/settings-api.ts @@ -20,7 +20,7 @@ export type SettingsConfigDTO = { }; frontend: { publicApiBaseURL: string }; routing: { - stickyTTL: string; cooldownBase: string; cooldownMax: string; capacityWait: string; maxAttempts: number; preferFreeBuild: boolean; markBuildChatDeniedAsReauth: boolean; + stickyTTL: string; cooldownBase: string; cooldownMax: string; capacityWait: string; maxAttempts: number; videoMaxAttempts: number; preferFreeBuild: boolean; markBuildChatDeniedAsReauth: boolean; accountIsolatedConnections: boolean; segmentedSelector: { enabled: boolean; minCandidates: number; windowSize: number }; }; @@ -114,7 +114,7 @@ const settingsConfigValidator = hasShape({ media: hasShape({ maxImageBytes: isNumber, maxTotalBytes: isNumber, cleanupThresholdPercent: isNumber, cleanupInterval: isString }), frontend: hasShape({ publicApiBaseURL: isString }), routing: hasShape({ - stickyTTL: isString, cooldownBase: isString, cooldownMax: isString, capacityWait: isString, maxAttempts: isNumber, preferFreeBuild: isBoolean, markBuildChatDeniedAsReauth: isBoolean, + stickyTTL: isString, cooldownBase: isString, cooldownMax: isString, capacityWait: isString, maxAttempts: isNumber, videoMaxAttempts: isNumber, preferFreeBuild: isBoolean, markBuildChatDeniedAsReauth: isBoolean, accountIsolatedConnections: isOptional(isBoolean), segmentedSelector: isOptional(hasShape({ enabled: isBoolean, minCandidates: isNumber, windowSize: isNumber })), }), diff --git a/frontend/src/features/settings/settings-model.ts b/frontend/src/features/settings/settings-model.ts index 71909179..96c03fdf 100644 --- a/frontend/src/features/settings/settings-model.ts +++ b/frontend/src/features/settings/settings-model.ts @@ -141,6 +141,7 @@ export const settingsSchema = z.object({ cooldownMax: routingCooldownDuration, capacityWait: routingCapacityWaitDuration, maxAttempts: z.union([z.literal(UNLIMITED_ROUTING_ATTEMPTS), positiveInteger.max(65535)]), + videoMaxAttempts: z.union([z.literal(UNLIMITED_ROUTING_ATTEMPTS), positiveInteger.max(65535)]), preferFreeBuild: z.boolean(), markBuildChatDeniedAsReauth: z.boolean(), accountIsolatedConnections: z.boolean(), @@ -202,7 +203,7 @@ export function toSettingsForm(config: SettingsConfigDTO): SettingsForm { }, routing: { stickyTTL: parseDuration(config.routing.stickyTTL), cooldownBase: parseDuration(config.routing.cooldownBase), - cooldownMax: parseDuration(config.routing.cooldownMax), capacityWait: parseDuration(config.routing.capacityWait), maxAttempts: config.routing.maxAttempts, + cooldownMax: parseDuration(config.routing.cooldownMax), capacityWait: parseDuration(config.routing.capacityWait), maxAttempts: config.routing.maxAttempts, videoMaxAttempts: !config.routing.videoMaxAttempts || config.routing.videoMaxAttempts === 0 ? 999 : config.routing.videoMaxAttempts, preferFreeBuild: config.routing.preferFreeBuild, markBuildChatDeniedAsReauth: config.routing.markBuildChatDeniedAsReauth, accountIsolatedConnections: config.routing.accountIsolatedConnections, @@ -245,7 +246,7 @@ export function toSettingsDTO(config: SettingsForm): SettingsConfigDTO { }, routing: { stickyTTL: formatDuration(config.routing.stickyTTL), cooldownBase: formatDuration(config.routing.cooldownBase), - cooldownMax: formatDuration(config.routing.cooldownMax), capacityWait: formatDuration(config.routing.capacityWait), maxAttempts: config.routing.maxAttempts, + cooldownMax: formatDuration(config.routing.cooldownMax), capacityWait: formatDuration(config.routing.capacityWait), maxAttempts: config.routing.maxAttempts, videoMaxAttempts: !config.routing.videoMaxAttempts || config.routing.videoMaxAttempts === 0 ? 999 : config.routing.videoMaxAttempts, preferFreeBuild: config.routing.preferFreeBuild, markBuildChatDeniedAsReauth: config.routing.markBuildChatDeniedAsReauth, accountIsolatedConnections: config.routing.accountIsolatedConnections, diff --git a/frontend/src/features/settings/settings-page.tsx b/frontend/src/features/settings/settings-page.tsx index 457a691d..33e5a04a 100644 --- a/frontend/src/features/settings/settings-page.tsx +++ b/frontend/src/features/settings/settings-page.tsx @@ -273,6 +273,43 @@ export function SettingsPage() { ); }} /> + + { + const unlimited = field.value === UNLIMITED_ROUTING_ATTEMPTS; + return ( +
+ field.onChange(event.currentTarget.valueAsNumber)} + /> +
+ {t("settingsRoutingAttempts.unlimited")} + { + if (checked) { + field.onChange(UNLIMITED_ROUTING_ATTEMPTS); + return; + } + field.onChange(limitedRoutingAttemptsRef.current > 0 ? limitedRoutingAttemptsRef.current : 999); + }} + /> +
+
+ ); + }} /> +
} />
} />
} />
diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index bdf47d9c..f7502286 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -942,7 +942,7 @@ const resources = { 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/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 握手、内存和文件描述符占用,建议仅在确有外部连接级负载均衡需求时开启。" }, + routing: { title: "路由策略", stickyTTL: "会话粘性时长", stickyTTLHelp: "同一会话优先复用已选账号的有效时长;到期后重新参与调度。", cooldownBase: "基础冷却时间", cooldownBaseHelp: "账号发生可恢复故障后首次进入冷却的时长。", cooldownMax: "最大冷却时间", cooldownMaxHelp: "连续故障触发指数退避时允许达到的最长冷却时间。", capacityWait: "账号满载等待", capacityWaitHelp: "全部候选账号并发已满时,切换或失败前等待容量释放的时间。", maxAttempts: "最大尝试次数", maxAttemptsHelp: "单次请求在可用账号之间切换并重试的最大次数,范围为 1–200。", videoMaxAttempts: "视频最大尝试次数", videoMaxAttemptsHelp: "仅作用于视频任务创建阶段的切号重试,可单独设置数值,或开启无限制。创建成功后的轮询不会换号。", 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: "新建客户端密钥默认允许同时执行的请求数。" }, accounts: { @@ -1603,7 +1603,7 @@ const resources = { errorFrameCount_one: "{{count}} error frame", errorFrameCount_other: "{{count}} error frames", }, - settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies", about: "About" }, server: { title: "Service capacity", maxConcurrentRequests: "API request concurrency limit", maxConcurrentRequestsHelp: "Maximum simultaneous /v1 requests per instance. Lowering the limit does not interrupt active requests." }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", baseURLHelp: "Primary upstream endpoint used for Grok Build requests.", fallbackBaseURL: "XAI fallback URL", fallbackBaseURLHelp: "Endpoint used when routing to XAI or falling back from Grok Build.", clientVersion: "Client version", clientVersionHelp: "Version sent with Build requests. Use a version that has passed compatibility validation.", clientIdentifier: "Client identifier", clientIdentifierHelp: "Client identity sent with requests; keep it aligned with the upstream protocol.", tokenAuth: "Token auth", tokenAuthHelp: "Client protocol identifier sent with Grok Build requests; normally keep xai-grok-cli.", userAgent: "User-Agent", userAgentHelp: "Used by Grok Build inference requests and their egress nodes. Direct XAI media requests derive the official xai-grok-build User-Agent from the client version.", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync latest version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill the form with the validated version and User-Agent; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", baseURLHelp: "Base endpoint used for Grok Web API calls and account operations.", statsigMode: "x-statsig source", statsigModeHelp: "Use a fixed value or retrieve request identity dynamically from a signer service.", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigValueHelp: "Fixed x-statsig-id attached to Grok Web requests.", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", statsigSignerURLHelp: "Internal signer endpoint used to retrieve x-statsig-id per request.", quotaTimeout: "Quota timeout", quotaTimeoutHelp: "Maximum time to wait for upstream quota and account-status queries.", chatTimeout: "Chat timeout", chatTimeoutHelp: "Maximum time to wait for a Grok Web chat request to complete.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum period without upstream data for raw text-chat streams; image, video, and other media requests are unaffected.", imageTimeout: "Image timeout", imageTimeoutHelp: "Maximum time to wait for image generation or editing to complete.", videoTimeout: "Video timeout", videoTimeoutHelp: "Maximum time to wait for a Grok Web video generation request to complete.", mediaConcurrency: "Media job concurrency", mediaConcurrencyHelp: "Image and video jobs one instance may run concurrently. Changes require a restart.", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffBaseHelp: "Initial retry interval after consecutive quota-recovery check failures.", recoveryBackoffMax: "Maximum recovery backoff", recoveryBackoffMaxHelp: "Maximum interval reached by exponential backoff for quota-recovery checks.", allowNSFW: "Allow NSFW images", allowNSFWHelp: "Allow Grok Web image requests to enable the adult-content preference.", clearanceMode: "Clearance management", clearanceModeHelp: "Maintain Cloudflare credentials manually or let FlareSolverr acquire and refresh them on the actual egress.", clearanceManual: "Manual", clearanceFlareSolverr: "FlareSolverr", flareSolverrURL: "FlareSolverr URL", flareSolverrURLHelp: "Internal FlareSolverr endpoint used to solve Cloudflare Clearance.", clearanceTimeout: "Solve timeout", clearanceTimeoutHelp: "Maximum time allowed for one FlareSolverr solve.", clearanceRefresh: "Refresh interval", clearanceRefreshHelp: "Periodic refresh interval for fixed egress; account-bound proxies are maintained independently during requests." }, console: { baseURLHelp: "Base endpoint used for Grok Console requests and account operations.", chatTimeoutHelp: "Maximum time to wait for a Grok Console chat request to complete.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum period without upstream data for text SSE only; media and non-streaming requests are unaffected." }, batch: { title: "Batch tasks", importConcurrency: "Import sync concurrency", importConcurrencyHelp: "Accounts initialized and synchronized concurrently after a batch import.", conversionConcurrency: "Account conversion concurrency", conversionConcurrencyHelp: "Cross-provider account conversions that may run concurrently.", syncConcurrency: "Data sync concurrency", syncConcurrencyHelp: "Quota, status, and capability synchronizations that may run concurrently.", refreshConcurrency: "Credential refresh concurrency", refreshConcurrencyHelp: "Account credential refreshes that may run concurrently.", randomDelay: "Maximum random delay (ms)", randomDelayHelp: "Maximum randomized delay before batch work starts to smooth upstream request bursts." }, media: { title: "Media storage", maxImageSize: "Maximum image size", maxImageSizeHelp: "Largest individual image that may be written to local media storage.", maxTotalSize: "Media storage limit", maxTotalSizeHelp: "Total local storage available to image and video files.", cleanupThresholdPercent: "Automatic cleanup threshold", cleanupThresholdPercentHelp: "Storage utilization that triggers removal of older media files.", cleanupInterval: "Capacity check interval", cleanupIntervalHelp: "Interval between background storage checks and cleanup evaluation.", sizeUnit: "Storage unit", publicApiBaseURL: "Public API base URL", publicApiBaseURLHelp: "Used for public image URLs and docs examples. Leave empty to use the service startup value, which defaults to http://127.0.0.1:8000." }, egress: { title: "Egress proxies", description: "Nodes manage proxy and health independently for Grok Build, Grok Web, Grok Console, or Web assets. Build inherits the Provider User-Agent; Web and Console nodes manage their own browser User-Agent and cookies. Proxy URLs and Cloudflare cookies are write-only.", add: "Add node", saved: "Proxy node saved", deleted: "Proxy node deleted", name: "Name", scope: "Scope", proxy: "Proxy", clearance: "Clearance", health: "Health", directFallback: "Direct connection is used when no node is configured", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web (assets only)", configured: "Configured", direct: "Direct", none: "None", editTitle: "Edit proxy node", addTitle: "Add proxy node", dialogDescription: "Build nodes only configure the proxy and inherit the Provider User-Agent; Web and Console nodes use their own browser User-Agent and Cloudflare cookies.", enabled: "Enabled", proxyURL: "Proxy URL", proxyProtocols: "Supports HTTP, HTTPS, SOCKS4, SOCKS4A, SOCKS5, and SOCKS5H.\nResin users can put {account} in the username to bind one lease per account.", proxyPool: "Proxy pool mode", proxyPoolHelp: "A request-level connection failure does not cool the entire shared node. Proxies containing {account} use this policy automatically.", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "Configured; leave blank to keep unchanged", operationFailed: "Operation failed", refreshClearance: "Refresh Clearance", clearanceRefreshed: "Clearance refreshed", clearanceManaged: "Cloudflare cookies and User-Agent are managed by FlareSolverr; account-bound proxies are isolated per account." }, routing: { title: "Routing policy", stickyTTL: "Sticky session TTL", stickyTTLHelp: "How long a session prefers its selected account before returning to normal scheduling.", cooldownBase: "Base cooldown", cooldownBaseHelp: "Initial cooldown applied after a recoverable account failure.", cooldownMax: "Maximum cooldown", cooldownMaxHelp: "Longest cooldown allowed when repeated failures trigger exponential backoff.", capacityWait: "Saturated account wait", capacityWaitHelp: "How long to wait for capacity before switching accounts or failing when all candidates are saturated.", maxAttempts: "Maximum attempts", maxAttemptsHelp: "Maximum account switches and retries allowed for one request, from 1 to 200.", preferFreeBuild: "Prefer Grok Build Free accounts", preferFreeBuildHelp: "Prefer confirmed usable Free accounts without changing other routing eligibility rules.", accountIsolatedConnections: "Isolate upstream connections by account", accountIsolatedConnectionsHelp: "When enabled, each account uses its own upstream TCP/HTTP connection pool so external L4 or connection-hash load balancers can spread traffic; the same account still reuses connections. Applies to Build, Web, Console, and Web-to-Build traffic. This increases connections, TLS handshakes, memory, and file-descriptor usage, so enable it only when connection-level balancing is required." }, audit: { title: "Request audit", bufferSize: "Queue capacity", bufferSizeHelp: "Maximum audit records held in memory before persistence.", batchSize: "Batch size", batchSizeHelp: "Maximum audit records written in one database transaction.", flushInterval: "Flush interval", flushIntervalHelp: "Maximum time pending audit records wait before they are committed.", commitDelay: "Commit aggregation delay (ms)", commitDelayHelp: "Maximum time acknowledged writes wait to join an atomic batch before commit." }, clientKeys: { title: "Client key defaults", rpmLimit: "Default RPM", rpmLimitHelp: "Requests per minute assigned to newly created client keys.", maxConcurrent: "Default concurrency", maxConcurrentHelp: "Concurrent requests assigned to newly created client keys." }, accounts: { title: "Account maintenance", invalidationTitle: "Automatic interception", botRiskSchedulingTitle: "Bot-risk scheduling", excludeBuildBotFlaggedFromScheduling: "Exclude bot-risk Build accounts from scheduling", excludeBuildBotFlaggedFromSchedulingHelp: "When enabled, Grok Build accounts whose JWT bot_flag_source/bfs is 1 or 2 are removed from Build scheduling only. Linked Web/Console accounts keep their normal scheduling. Accounts remain in the pool for viewing and manual actions.", cleanupTitle: "Account cleanup", autoCleanReauthEnabled: "Automatic invalid-account cleanup", autoCleanReauthEnabledHelp: "Permanently deletes invalid accounts after the configured retention period. Accounts with active requests or video jobs are skipped.", autoCleanReauthInterval: "Cleanup interval", autoCleanReauthIntervalHelp: "How often to check for eligible accounts, from 1 minute to 1 hour.", autoCleanReauthMinAge: "Minimum retention", autoCleanReauthMinAgeHelp: "How long to retain an account after it is marked for reauthorization.", autoCleanIncludeDisabled: "Include disabled accounts", autoCleanIncludeDisabledHelp: "Includes disabled accounts that require reauthorization in automatic cleanup.", autoCleanEnableTitle: "Enable automatic cleanup?", autoCleanEnableDescription: "Eligible accounts will be permanently deleted and cannot be recovered. The first run starts after one full cleanup interval.", autoCleanIncludeDisabledTitle: "Include disabled accounts?", autoCleanIncludeDisabledDescription: "Disabled accounts that require reauthorization will also be permanently deleted. This action cannot be undone.", autoCleanConfirm: "Enable" }, units: { seconds: "Seconds", minutes: "Minutes", hours: "Hours", days: "Days" } }, + settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies", about: "About" }, server: { title: "Service capacity", maxConcurrentRequests: "API request concurrency limit", maxConcurrentRequestsHelp: "Maximum simultaneous /v1 requests per instance. Lowering the limit does not interrupt active requests." }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", baseURLHelp: "Primary upstream endpoint used for Grok Build requests.", fallbackBaseURL: "XAI fallback URL", fallbackBaseURLHelp: "Endpoint used when routing to XAI or falling back from Grok Build.", clientVersion: "Client version", clientVersionHelp: "Version sent with Build requests. Use a version that has passed compatibility validation.", clientIdentifier: "Client identifier", clientIdentifierHelp: "Client identity sent with requests; keep it aligned with the upstream protocol.", tokenAuth: "Token auth", tokenAuthHelp: "Client protocol identifier sent with Grok Build requests; normally keep xai-grok-cli.", userAgent: "User-Agent", userAgentHelp: "Used by Grok Build inference requests and their egress nodes. Direct XAI media requests derive the official xai-grok-build User-Agent from the client version.", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync latest version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill the form with the validated version and User-Agent; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", baseURLHelp: "Base endpoint used for Grok Web API calls and account operations.", statsigMode: "x-statsig source", statsigModeHelp: "Use a fixed value or retrieve request identity dynamically from a signer service.", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigValueHelp: "Fixed x-statsig-id attached to Grok Web requests.", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", statsigSignerURLHelp: "Internal signer endpoint used to retrieve x-statsig-id per request.", quotaTimeout: "Quota timeout", quotaTimeoutHelp: "Maximum time to wait for upstream quota and account-status queries.", chatTimeout: "Chat timeout", chatTimeoutHelp: "Maximum time to wait for a Grok Web chat request to complete.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum period without upstream data for raw text-chat streams; image, video, and other media requests are unaffected.", imageTimeout: "Image timeout", imageTimeoutHelp: "Maximum time to wait for image generation or editing to complete.", videoTimeout: "Video timeout", videoTimeoutHelp: "Maximum time to wait for a Grok Web video generation request to complete.", mediaConcurrency: "Media job concurrency", mediaConcurrencyHelp: "Image and video jobs one instance may run concurrently. Changes require a restart.", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffBaseHelp: "Initial retry interval after consecutive quota-recovery check failures.", recoveryBackoffMax: "Maximum recovery backoff", recoveryBackoffMaxHelp: "Maximum interval reached by exponential backoff for quota-recovery checks.", allowNSFW: "Allow NSFW images", allowNSFWHelp: "Allow Grok Web image requests to enable the adult-content preference.", clearanceMode: "Clearance management", clearanceModeHelp: "Maintain Cloudflare credentials manually or let FlareSolverr acquire and refresh them on the actual egress.", clearanceManual: "Manual", clearanceFlareSolverr: "FlareSolverr", flareSolverrURL: "FlareSolverr URL", flareSolverrURLHelp: "Internal FlareSolverr endpoint used to solve Cloudflare Clearance.", clearanceTimeout: "Solve timeout", clearanceTimeoutHelp: "Maximum time allowed for one FlareSolverr solve.", clearanceRefresh: "Refresh interval", clearanceRefreshHelp: "Periodic refresh interval for fixed egress; account-bound proxies are maintained independently during requests." }, console: { baseURLHelp: "Base endpoint used for Grok Console requests and account operations.", chatTimeoutHelp: "Maximum time to wait for a Grok Console chat request to complete.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum period without upstream data for text SSE only; media and non-streaming requests are unaffected." }, batch: { title: "Batch tasks", importConcurrency: "Import sync concurrency", importConcurrencyHelp: "Accounts initialized and synchronized concurrently after a batch import.", conversionConcurrency: "Account conversion concurrency", conversionConcurrencyHelp: "Cross-provider account conversions that may run concurrently.", syncConcurrency: "Data sync concurrency", syncConcurrencyHelp: "Quota, status, and capability synchronizations that may run concurrently.", refreshConcurrency: "Credential refresh concurrency", refreshConcurrencyHelp: "Account credential refreshes that may run concurrently.", randomDelay: "Maximum random delay (ms)", randomDelayHelp: "Maximum randomized delay before batch work starts to smooth upstream request bursts." }, media: { title: "Media storage", maxImageSize: "Maximum image size", maxImageSizeHelp: "Largest individual image that may be written to local media storage.", maxTotalSize: "Media storage limit", maxTotalSizeHelp: "Total local storage available to image and video files.", cleanupThresholdPercent: "Automatic cleanup threshold", cleanupThresholdPercentHelp: "Storage utilization that triggers removal of older media files.", cleanupInterval: "Capacity check interval", cleanupIntervalHelp: "Interval between background storage checks and cleanup evaluation.", sizeUnit: "Storage unit", publicApiBaseURL: "Public API base URL", publicApiBaseURLHelp: "Used for public image URLs and docs examples. Leave empty to use the service startup value, which defaults to http://127.0.0.1:8000." }, egress: { title: "Egress proxies", description: "Nodes manage proxy and health independently for Grok Build, Grok Web, Grok Console, or Web assets. Build inherits the Provider User-Agent; Web and Console nodes manage their own browser User-Agent and cookies. Proxy URLs and Cloudflare cookies are write-only.", add: "Add node", saved: "Proxy node saved", deleted: "Proxy node deleted", name: "Name", scope: "Scope", proxy: "Proxy", clearance: "Clearance", health: "Health", directFallback: "Direct connection is used when no node is configured", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web (assets only)", configured: "Configured", direct: "Direct", none: "None", editTitle: "Edit proxy node", addTitle: "Add proxy node", dialogDescription: "Build nodes only configure the proxy and inherit the Provider User-Agent; Web and Console nodes use their own browser User-Agent and Cloudflare cookies.", enabled: "Enabled", proxyURL: "Proxy URL", proxyProtocols: "Supports HTTP, HTTPS, SOCKS4, SOCKS4A, SOCKS5, and SOCKS5H.\nResin users can put {account} in the username to bind one lease per account.", proxyPool: "Proxy pool mode", proxyPoolHelp: "A request-level connection failure does not cool the entire shared node. Proxies containing {account} use this policy automatically.", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "Configured; leave blank to keep unchanged", operationFailed: "Operation failed", refreshClearance: "Refresh Clearance", clearanceRefreshed: "Clearance refreshed", clearanceManaged: "Cloudflare cookies and User-Agent are managed by FlareSolverr; account-bound proxies are isolated per account." }, routing: { title: "Routing policy", stickyTTL: "Sticky session TTL", stickyTTLHelp: "How long a session prefers its selected account before returning to normal scheduling.", cooldownBase: "Base cooldown", cooldownBaseHelp: "Initial cooldown applied after a recoverable account failure.", cooldownMax: "Maximum cooldown", cooldownMaxHelp: "Longest cooldown allowed when repeated failures trigger exponential backoff.", capacityWait: "Saturated account wait", capacityWaitHelp: "How long to wait for capacity before switching accounts or failing when all candidates are saturated.", maxAttempts: "Maximum attempts", maxAttemptsHelp: "Maximum account switches and retries allowed for one request, from 1 to 200.", videoMaxAttempts: "Video maximum attempts", videoMaxAttemptsHelp: "Create-phase account failover for video jobs only. Set a number or enable unlimited. Polling after create stays on the same account.", preferFreeBuild: "Prefer Grok Build Free accounts", preferFreeBuildHelp: "Prefer confirmed usable Free accounts without changing other routing eligibility rules.", accountIsolatedConnections: "Isolate upstream connections by account", accountIsolatedConnectionsHelp: "When enabled, each account uses its own upstream TCP/HTTP connection pool so external L4 or connection-hash load balancers can spread traffic; the same account still reuses connections. Applies to Build, Web, Console, and Web-to-Build traffic. This increases connections, TLS handshakes, memory, and file-descriptor usage, so enable it only when connection-level balancing is required." }, audit: { title: "Request audit", bufferSize: "Queue capacity", bufferSizeHelp: "Maximum audit records held in memory before persistence.", batchSize: "Batch size", batchSizeHelp: "Maximum audit records written in one database transaction.", flushInterval: "Flush interval", flushIntervalHelp: "Maximum time pending audit records wait before they are committed.", commitDelay: "Commit aggregation delay (ms)", commitDelayHelp: "Maximum time acknowledged writes wait to join an atomic batch before commit." }, clientKeys: { title: "Client key defaults", rpmLimit: "Default RPM", rpmLimitHelp: "Requests per minute assigned to newly created client keys.", maxConcurrent: "Default concurrency", maxConcurrentHelp: "Concurrent requests assigned to newly created client keys." }, accounts: { title: "Account maintenance", invalidationTitle: "Automatic interception", botRiskSchedulingTitle: "Bot-risk scheduling", excludeBuildBotFlaggedFromScheduling: "Exclude bot-risk Build accounts from scheduling", excludeBuildBotFlaggedFromSchedulingHelp: "When enabled, Grok Build accounts whose JWT bot_flag_source/bfs is 1 or 2 are removed from Build scheduling only. Linked Web/Console accounts keep their normal scheduling. Accounts remain in the pool for viewing and manual actions.", cleanupTitle: "Account cleanup", autoCleanReauthEnabled: "Automatic invalid-account cleanup", autoCleanReauthEnabledHelp: "Permanently deletes invalid accounts after the configured retention period. Accounts with active requests or video jobs are skipped.", autoCleanReauthInterval: "Cleanup interval", autoCleanReauthIntervalHelp: "How often to check for eligible accounts, from 1 minute to 1 hour.", autoCleanReauthMinAge: "Minimum retention", autoCleanReauthMinAgeHelp: "How long to retain an account after it is marked for reauthorization.", autoCleanIncludeDisabled: "Include disabled accounts", autoCleanIncludeDisabledHelp: "Includes disabled accounts that require reauthorization in automatic cleanup.", autoCleanEnableTitle: "Enable automatic cleanup?", autoCleanEnableDescription: "Eligible accounts will be permanently deleted and cannot be recovered. The first run starts after one full cleanup interval.", autoCleanIncludeDisabledTitle: "Include disabled accounts?", autoCleanIncludeDisabledDescription: "Disabled accounts that require reauthorization will also be permanently deleted. This action cannot be undone.", autoCleanConfirm: "Enable" }, units: { seconds: "Seconds", minutes: "Minutes", hours: "Hours", days: "Days" } }, settingsBuildTransport: { responseHeaderTimeout: "Response header timeout", responseHeaderTimeoutHelp: "Maximum time to wait for the first Grok Build response headers after the request body is sent.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum wait for new data on an open streaming response before aborting. Covers upstream connections that succeed but go silent mid-stream." }, settingsBuildForbidden: { markInvalid: "Invalidate matching error codes", markInvalidHelp: "When enabled, a Grok Build 403 with a matching error code marks the account invalid and removes it from scheduling.", codes: "Invalidation error codes", codesHelp: "Enter one code per line. Codes match the complete code or error.code value case-insensitively, up to 32 entries.", codesInvalid: "Enter 1–32 valid codes using letters, numbers, dots, underscores, colons, or hyphens.", codesPlaceholder: "permission-denied" }, From e257f3db4478b08c4602ba22710786df1c60b7ac Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Thu, 13 Aug 2026 22:13:54 +0800 Subject: [PATCH 21/48] feat: add progress reporting to model sync process with event streaming --- backend/internal/application/model/service.go | 29 +++-- .../internal/transport/http/model/handler.go | 100 +++++++++++++++++- .../transport/http/model/handler_test.go | 25 +++++ frontend/src/entities/model/model-api.ts | 47 +++++++- frontend/src/features/models/models-page.tsx | 15 ++- frontend/src/shared/i18n/index.ts | 4 +- 6 files changed, 199 insertions(+), 21 deletions(-) diff --git a/backend/internal/application/model/service.go b/backend/internal/application/model/service.go index 706b359d..57669170 100644 --- a/backend/internal/application/model/service.go +++ b/backend/internal/application/model/service.go @@ -6,6 +6,7 @@ import ( "fmt" "log/slog" "strings" + "sync/atomic" "time" accountapp "github.com/chenyme/grok2api/backend/internal/application/account" @@ -64,6 +65,8 @@ type ListFilter struct { Sort repository.SortQuery } +type SyncProgressObserver func(completed, total int) + // Service 负责上游模型发现、内部来源路由与对外模型名称维护。 type Service struct { models repository.ModelRepository @@ -398,8 +401,13 @@ func (s *Service) BatchSetEnabled(ctx context.Context, ids []uint64, enabled boo // Sync 从全部启用账号同步模型能力,并按 Provider 幂等更新公开路由表。 func (s *Service) Sync(ctx context.Context) (int, error) { + return s.SyncObserved(ctx, nil) +} + +// SyncObserved 执行全量模型同步,并按已完成账号数报告进度。 +func (s *Service) SyncObserved(ctx context.Context, observer SyncProgressObserver) (int, error) { result := s.syncAll.DoChan("all", func() (any, error) { - return s.syncAllAccounts(ctx) + return s.syncAllAccounts(ctx, observer) }) select { case <-ctx.Done(): @@ -412,14 +420,7 @@ func (s *Service) Sync(ctx context.Context) (int, error) { } } -// SyncAsync 异步触发全量模型同步,不阻塞调用方。用 context.Background 避免请求超时导致同步中断。 -func (s *Service) SyncAsync(_ context.Context) { - s.syncAll.DoChan("all", func() (any, error) { - return s.syncAllAccounts(context.Background()) - }) -} - -func (s *Service) syncAllAccounts(ctx context.Context) (int, error) { +func (s *Service) syncAllAccounts(ctx context.Context, observer SyncProgressObserver) (int, error) { if s.providers == nil { return 0, fmt.Errorf("Provider 注册表未初始化") } @@ -438,12 +439,20 @@ func (s *Service) syncAllAccounts(ctx context.Context) (int, error) { if len(credentials) == 0 { return 0, fmt.Errorf("没有可用于模型同步的账号") } - results, summary, runErr := batch.Map(ctx, credentials, batch.Options{Workers: s.bulkPool.Limit(), Pool: s.bulkPool}, func(workCtx context.Context, value account.Credential) ([]string, error) { + if observer != nil { + observer(0, len(credentials)) + } + var completed atomic.Int64 + results, summary, runErr := batch.MapObserved(ctx, credentials, batch.Options{Workers: s.bulkPool.Limit(), Pool: s.bulkPool}, func(workCtx context.Context, value account.Credential) ([]string, error) { adapter, ok := s.providers.Models(value.Provider) if !ok { return nil, fmt.Errorf("Provider %s 未注册模型同步能力", value.Provider) } return s.syncAccountCapabilities(workCtx, value, adapter) + }, func(_ int, _ batch.Result[[]string]) { + if observer != nil { + observer(int(completed.Add(1)), len(credentials)) + } }) pool := s.bulkPool.Snapshot() s.logger.Info("model_bulk_sync_completed", "total", summary.Total, "submitted", summary.Submitted, "succeeded", summary.Succeeded, "failed", summary.Failed, "panicked", summary.Panicked, "duration_ms", summary.Duration.Milliseconds(), "canceled", summary.Canceled, "pool_limit", pool.Limit, "pool_active", pool.Active, "pool_queued", pool.Queued, "pool_peak", pool.Peak, "error", runErr) diff --git a/backend/internal/transport/http/model/handler.go b/backend/internal/transport/http/model/handler.go index ab24a95c..9c955779 100644 --- a/backend/internal/transport/http/model/handler.go +++ b/backend/internal/transport/http/model/handler.go @@ -1,11 +1,14 @@ package model import ( + "context" + "encoding/json" "errors" "fmt" "net/http" "strconv" "strings" + "sync/atomic" "time" modelapp "github.com/chenyme/grok2api/backend/internal/application/model" @@ -18,6 +21,11 @@ import ( type Handler struct{ service *modelapp.Service } +const ( + modelSyncHeartbeatInterval = 15 * time.Second + modelSyncWriteTimeout = 30 * time.Second +) + func NewHandler(service *modelapp.Service) *Handler { return &Handler{service: service} } func (h *Handler) Register(router *gin.RouterGroup) { @@ -234,10 +242,94 @@ func (h *Handler) batchDelete(c *gin.Context) { } func (h *Handler) sync(c *gin.Context) { - // 异步触发全量同步,不阻塞 HTTP 响应。 - // 同步需要 2min+,Cloudflare 免费版 100s 超时,直接同步会 524 → 浏览器 Failed to fetch。 - go h.service.SyncAsync(c.Request.Context()) - response.Success(c, http.StatusOK, gin.H{"synced": 0, "async": true}) + c.Header("Content-Type", "text/event-stream; charset=utf-8") + c.Header("Cache-Control", "no-cache, no-transform") + c.Header("X-Accel-Buffering", "no") + if err := writeModelSyncComment(c, "connected"); err != nil { + return + } + + type syncResult struct { + synced int + err error + } + result := make(chan syncResult, 1) + ctx, cancel := context.WithCancel(c.Request.Context()) + defer cancel() + var completed atomic.Int64 + var total atomic.Int64 + go func() { + synced, err := h.service.SyncObserved(ctx, func(current, maximum int) { + completed.Store(int64(current)) + total.Store(int64(maximum)) + }) + result <- syncResult{synced: synced, err: err} + }() + + heartbeat := time.NewTicker(modelSyncHeartbeatInterval) + defer heartbeat.Stop() + progressTicker := time.NewTicker(250 * time.Millisecond) + defer progressTicker.Stop() + lastCompleted, lastTotal := -1, -1 + for { + select { + case <-c.Request.Context().Done(): + return + case value := <-result: + if value.err != nil { + _ = writeModelSyncEvent(c, "error", gin.H{"code": "modelSyncFailed", "message": "同步模型能力失败"}) + return + } + _ = writeModelSyncEvent(c, "complete", gin.H{"synced": value.synced}) + return + case <-heartbeat.C: + if err := writeModelSyncComment(c, "heartbeat"); err != nil { + return + } + case <-progressTicker.C: + current, maximum := int(completed.Load()), int(total.Load()) + if maximum > 0 && (current != lastCompleted || maximum != lastTotal) { + if err := writeModelSyncEvent(c, "progress", gin.H{"completed": current, "total": maximum}); err != nil { + return + } + lastCompleted, lastTotal = current, maximum + } + } + } +} + +func writeModelSyncEvent(c *gin.Context, event string, value any) error { + payload, err := json.Marshal(value) + if err != nil { + return err + } + if err := setModelSyncWriteDeadline(c.Writer); err != nil { + return err + } + if _, err := fmt.Fprintf(c.Writer, "event: %s\ndata: %s\n\n", event, payload); err != nil { + return err + } + c.Writer.Flush() + return c.Request.Context().Err() +} + +func writeModelSyncComment(c *gin.Context, comment string) error { + if err := setModelSyncWriteDeadline(c.Writer); err != nil { + return err + } + if _, err := fmt.Fprintf(c.Writer, ": %s\n\n", comment); err != nil { + return err + } + c.Writer.Flush() + return c.Request.Context().Err() +} + +func setModelSyncWriteDeadline(writer http.ResponseWriter) error { + err := http.NewResponseController(writer).SetWriteDeadline(time.Now().Add(modelSyncWriteTimeout)) + if errors.Is(err, http.ErrNotSupported) { + return nil + } + return err } func (h *Handler) update(c *gin.Context) { diff --git a/backend/internal/transport/http/model/handler_test.go b/backend/internal/transport/http/model/handler_test.go index 37a789c2..d6db6a19 100644 --- a/backend/internal/transport/http/model/handler_test.go +++ b/backend/internal/transport/http/model/handler_test.go @@ -1,13 +1,38 @@ package model import ( + "net/http" + "net/http/httptest" + "strings" "testing" modelapp "github.com/chenyme/grok2api/backend/internal/application/model" "github.com/chenyme/grok2api/backend/internal/domain/account" modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" + "github.com/gin-gonic/gin" ) +func TestSyncStreamsTerminalFailureInsteadOfAcknowledgingSuccess(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + context, _ := gin.CreateTestContext(recorder) + context.Request = httptest.NewRequest(http.MethodPost, "/api/admin/v1/models/sync", nil) + + handler := NewHandler(modelapp.NewService(nil, nil, nil, nil)) + handler.sync(context) + + if contentType := recorder.Header().Get("Content-Type"); !strings.HasPrefix(contentType, "text/event-stream") { + t.Fatalf("content type = %q", contentType) + } + body := recorder.Body.String() + if !strings.Contains(body, ": connected\n\n") || !strings.Contains(body, "event: error\ndata: {\"code\":\"modelSyncFailed\"") { + t.Fatalf("unexpected stream body: %q", body) + } + if strings.Contains(body, "event: complete") || strings.Contains(body, "\"synced\":0") { + t.Fatalf("failure was acknowledged as success: %q", body) + } +} + func TestNewModelResponseSeparatesPublicAndUpstreamNames(t *testing.T) { response := newModelResponse(modeldomain.Route{ ID: 1, PublicID: "Build/grok-4.5", Provider: account.ProviderBuild, UpstreamModel: "grok-4.5", diff --git a/frontend/src/entities/model/model-api.ts b/frontend/src/entities/model/model-api.ts index 2303e683..89baf636 100644 --- a/frontend/src/entities/model/model-api.ts +++ b/frontend/src/entities/model/model-api.ts @@ -1,6 +1,7 @@ import type { ModelRouteDTO, ModelRouteGroupDTO } from "@/entities/model/types"; -import { apiRequest, type PaginatedDTO } from "@/shared/api/client"; +import { ApiError, apiEventStream, apiRequest, type PaginatedDTO } from "@/shared/api/client"; import { createObjectDecoder, createPaginatedDecoder, decodeBooleanResult, decodeCountResult, hasShape, isArrayOf, isBoolean, isNumber, isOneOf, isOptional, isString } from "@/shared/api/decoder"; +import { i18n } from "@/shared/i18n"; import type { SortOrder } from "@/shared/lib/table-sort"; export type ListModelsInput = { @@ -76,8 +77,48 @@ export function listModelGroups(input: ListModelsInput): Promise { - return apiRequest("/api/admin/v1/models/sync", { method: "POST" }, decodeCountResult<{ synced: number }>("synced")); +type ModelSyncEventDTO = { + synced?: number; + completed?: number; + total?: number; + code?: string; + message?: string; +}; + +const decodeModelSyncEvent = createObjectDecoder("model sync event", { + synced: isOptional(isNumber), + completed: isOptional(isNumber), + total: isOptional(isNumber), + code: isOptional(isString), + message: isOptional(isString), +}); + +export type ModelSyncProgressDTO = { completed: number; total: number }; + +export async function syncModels(onProgress?: (progress: ModelSyncProgressDTO) => void): Promise<{ synced: number }> { + let result: { synced: number } | undefined; + await apiEventStream("/api/admin/v1/models/sync", { + method: "POST", + headers: { Accept: "text/event-stream" }, + }, decodeModelSyncEvent, ({ event, data }) => { + if (event === "progress" && typeof data.completed === "number" && typeof data.total === "number" && data.total > 0) { + onProgress?.({ completed: Math.min(Math.max(0, data.completed), data.total), total: data.total }); + return; + } + if (event === "complete" && typeof data.synced === "number") { + result = { synced: data.synced }; + return; + } + if (event === "error") { + const code = data.code ?? "modelSyncFailed"; + const message = i18n.exists(`apiErrors.${code}`) ? i18n.t(`apiErrors.${code}`) : (data.message ?? i18n.t("apiErrors.requestFailed")); + throw new ApiError(502, code, message); + } + }); + if (!result) { + throw new ApiError(502, "invalidResponse", i18n.t("apiErrors.invalidResponse")); + } + return result; } export type ModelAccountOptionDTO = { id: string; name: string }; diff --git a/frontend/src/features/models/models-page.tsx b/frontend/src/features/models/models-page.tsx index 8895513b..ec191b6e 100644 --- a/frontend/src/features/models/models-page.tsx +++ b/frontend/src/features/models/models-page.tsx @@ -34,6 +34,8 @@ import { cn } from "@/shared/lib/cn"; import { formatDateTime } from "@/shared/lib/format"; import { nextTableSort, type SortOrder, type TableSort } from "@/shared/lib/table-sort"; +const modelSyncToastID = "model-sync-progress"; + export function ModelsPage() { const { t, i18n } = useTranslation(); const queryClient = useQueryClient(); @@ -135,14 +137,21 @@ export function ModelsPage() { }); const syncMutation = useMutation({ - mutationFn: syncModels, + mutationFn: () => syncModels((progress) => { + toast.loading(t("models.syncingProgress", progress), { id: modelSyncToastID }); + }), + onMutate: () => { + toast.loading(t("models.syncing"), { id: modelSyncToastID }); + }, onSuccess: (result) => { setSelected(new Set()); setPage(1); void queryClient.invalidateQueries({ queryKey: ["models"] }); - toast.success(t("models.synced", { count: result.synced })); + toast.success(t("models.synced", { count: result.synced }), { id: modelSyncToastID }); + }, + onError: (error) => { + toast.error(error instanceof Error ? error.message : t("errors.generic"), { id: modelSyncToastID }); }, - onError: showError, }); function showError(error: unknown): void { diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index bef6f887..b604036c 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -687,6 +687,8 @@ const resources = { deleteDescription: "将删除 {{name}} 及其密钥权限关联;如果上游账号仍支持该模型,后续同步会重新创建。", batchDeleteTitle: "删除所选 {{count}} 个模型路由?", batchDeleteDescription: "将同时删除所选路由及其密钥权限关联;上游账号仍支持的模型会在后续同步时重新创建。", + syncing: "正在准备同步账号模型能力", + syncingProgress: "正在同步账号模型能力 {{completed}} / {{total}}", synced: "已同步 {{count}} 个模型", created: "模型路由已创建", updated: "模型路由已更新", @@ -1341,7 +1343,7 @@ const resources = { 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" }, - 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" }, + 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.", syncing: "Preparing account capability sync", syncingProgress: "Syncing account capabilities {{completed}} / {{total}}", 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: { title: "Request audits", From 9de5357619b158ae4bbfd65dab13f6270835c4ba Mon Sep 17 00:00:00 2001 From: 741075810 <31341354+741075810@users.noreply.github.com> Date: Thu, 13 Aug 2026 22:27:33 +0800 Subject: [PATCH 22/48] =?UTF-8?q?fix(media):=20=E8=A7=86=E9=A2=91=E4=B8=8B?= =?UTF-8?q?=E8=BD=BD=E6=96=87=E4=BB=B6=E5=90=8D=E8=A1=A5=E9=BD=90=E6=89=A9?= =?UTF-8?q?=E5=B1=95=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../transport/http/inference/handler.go | 47 +++++++++++++++++-- .../transport/http/inference/handler_test.go | 38 ++++++++++++++- .../internal/transport/http/media/handler.go | 17 ++++++- 3 files changed, 96 insertions(+), 6 deletions(-) diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index efc81731..490144ff 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -934,10 +934,10 @@ func (h *Handler) getVideoContent(c *gin.Context) { return } defer func() { _ = body.Close() }() - writeVideoContent(c, body, contentType, size) + writeVideoContent(c, body, contentType, size, strings.TrimSpace(c.Param("requestId"))) } -func writeVideoContent(c *gin.Context, body io.Reader, contentType string, size int64) { +func writeVideoContent(c *gin.Context, body io.Reader, contentType string, size int64, downloadName string) { if size > maxMediaResponseTransferBytes { writeOpenAIError(c, http.StatusBadGateway, "media_too_large", "上游媒体超过 2 GiB 安全上限") return @@ -947,7 +947,8 @@ func writeVideoContent(c *gin.Context, body io.Reader, contentType string, size writeOpenAIError(c, http.StatusBadGateway, "invalid_media_type", "上游视频服务返回了不受支持的内容类型") return } - c.Header("Content-Disposition", "inline") + // Clients that save the response need an extension to get a playable file. + c.Header("Content-Disposition", videoContentDisposition(downloadName, contentType)) c.Header("Cache-Control", "private, no-store") c.Header("X-Content-Type-Options", "nosniff") c.Header("Content-Security-Policy", "default-src 'none'; sandbox") @@ -966,6 +967,46 @@ func writeVideoContent(c *gin.Context, body io.Reader, contentType string, size } } +// videoContentDisposition names the download after the request and appends the +// extension implied by the response content type, so saved files stay playable. +func videoContentDisposition(name, contentType string) string { + name = strings.Map(func(r rune) rune { + switch { + case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9': + return r + case r == '-', r == '_': + return r + default: + return -1 + } + }, strings.TrimSpace(name)) + if name == "" { + name = "video" + } + if extension, ok := videoFileExtension(contentType); ok { + name += extension + } + return `inline; filename="` + name + `"` +} + +// videoFileExtension mirrors the extensions used by the media object store. +func videoFileExtension(contentType string) (string, bool) { + mediaType, _, err := mime.ParseMediaType(strings.TrimSpace(contentType)) + if err != nil { + return "", false + } + switch strings.ToLower(mediaType) { + case "video/mp4": + return ".mp4", true + case "video/webm": + return ".webm", true + case "video/quicktime": + return ".mov", true + default: + return "", false + } +} + func normalizeVideoResponseContentType(value string) (string, bool) { mediaType, _, err := mime.ParseMediaType(strings.TrimSpace(value)) if err != nil { diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go index 75a7dc69..0a7b5686 100644 --- a/backend/internal/transport/http/inference/handler_test.go +++ b/backend/internal/transport/http/inference/handler_test.go @@ -119,12 +119,46 @@ func TestWriteVideoContentRejectsDeclaredOversizeMedia(t *testing.T) { gin.SetMode(gin.TestMode) recorder := httptest.NewRecorder() context, _ := gin.CreateTestContext(recorder) - writeVideoContent(context, strings.NewReader("ignored"), "video/mp4", maxMediaResponseTransferBytes+1) + writeVideoContent(context, strings.NewReader("ignored"), "video/mp4", maxMediaResponseTransferBytes+1, "video_request_1") if recorder.Code != http.StatusBadGateway || !strings.Contains(recorder.Body.String(), "media_too_large") { t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String()) } } +// A saved response needs an extension or the file will not open in a player. +func TestWriteVideoContentNamesDownloadWithExtension(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, testCase := range []struct { + contentType string + want string + }{ + {"video/mp4", `inline; filename="video_request_1.mp4"`}, + {"video/webm", `inline; filename="video_request_1.webm"`}, + {"video/quicktime", `inline; filename="video_request_1.mov"`}, + } { + recorder := httptest.NewRecorder() + context, _ := gin.CreateTestContext(recorder) + writeVideoContent(context, strings.NewReader("body"), testCase.contentType, 4, "video_request_1") + if got := recorder.Header().Get("Content-Disposition"); got != testCase.want { + t.Fatalf("%s disposition = %q, want %q", testCase.contentType, got, testCase.want) + } + } +} + +// Request IDs reach the header, so anything outside [A-Za-z0-9_-] is dropped and an +// empty result falls back to a fixed name. +func TestVideoContentDispositionSanitizesName(t *testing.T) { + if got := videoContentDisposition(`bad"name; drop`, "video/mp4"); got != `inline; filename="badnamedrop.mp4"` { + t.Fatalf("sanitized disposition = %q", got) + } + if got := videoContentDisposition(" ", "video/mp4"); got != `inline; filename="video.mp4"` { + t.Fatalf("fallback disposition = %q", got) + } + if got := videoContentDisposition("video_request_1", "application/octet-stream"); got != `inline; filename="video_request_1"` { + t.Fatalf("unknown type disposition = %q", got) + } +} + func TestVideoContentURLUsesConfiguredPublicAPIBase(t *testing.T) { handler := NewHandler(nil, nil, 1<<20, "https://api.example.com/grok2api/") response := videoGenerationResponse(mediadomain.Job{ID: "video_request_1", Status: mediadomain.StatusCompleted, UpstreamURL: "https://assets.grok.com/source.mp4"}, handler.videoContentURL("video_request_1")) @@ -417,7 +451,7 @@ func TestVideoContentRejectsUnsafeContentType(t *testing.T) { gin.SetMode(gin.TestMode) recorder := httptest.NewRecorder() context, _ := gin.CreateTestContext(recorder) - writeVideoContent(context, strings.NewReader(``), "text/html", -1) + writeVideoContent(context, strings.NewReader(``), "text/html", -1, "video_request_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()) } diff --git a/backend/internal/transport/http/media/handler.go b/backend/internal/transport/http/media/handler.go index 7165f46e..dbc29e78 100644 --- a/backend/internal/transport/http/media/handler.go +++ b/backend/internal/transport/http/media/handler.go @@ -82,6 +82,21 @@ func (h *Handler) getImage(c *gin.Context) { _, _ = io.Copy(c.Writer, body) } +// videoContentDisposition appends the extension implied by the stored MIME type so +// saved files stay playable; the media object store uses the same mapping. +func videoContentDisposition(assetID, mimeType string) string { + name := assetID + switch strings.ToLower(strings.TrimSpace(mimeType)) { + case "video/mp4": + name += ".mp4" + case "video/webm": + name += ".webm" + case "video/quicktime": + name += ".mov" + } + return `inline; filename="` + name + `"` +} + func (h *Handler) getVideo(c *gin.Context) { asset, body, err := h.service.OpenVideo(c.Request.Context(), c.Param("assetId")) if errors.Is(err, mediaapp.ErrAssetNotFound) { @@ -99,7 +114,7 @@ func (h *Handler) getVideo(c *gin.Context) { return } c.Header("Content-Type", asset.MIMEType) - c.Header("Content-Disposition", `inline; filename="`+asset.ID+`"`) + c.Header("Content-Disposition", videoContentDisposition(asset.ID, asset.MIMEType)) c.Header("Cache-Control", "public, max-age=31536000, immutable") c.Header("ETag", `"`+asset.SHA256+`"`) c.Header("X-Content-Type-Options", "nosniff") From aebce71e6fca4d7fa5bc1c114b1679f95ca29d5e Mon Sep 17 00:00:00 2001 From: 741075810 <31341354+741075810@users.noreply.github.com> Date: Thu, 13 Aug 2026 22:28:16 +0800 Subject: [PATCH 23/48] =?UTF-8?q?fix(video):=20=E8=BF=94=E5=9B=9E=E5=8F=AF?= =?UTF-8?q?=E7=9B=B4=E6=8E=A5=E6=92=AD=E6=94=BE=E7=9A=84=E8=A7=86=E9=A2=91?= =?UTF-8?q?=E5=9C=B0=E5=9D=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../transport/http/inference/handler.go | 21 +++++++++++++--- .../transport/http/inference/handler_test.go | 25 +++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index efc81731..00d4f83d 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -908,11 +908,10 @@ func (h *Handler) getVideo(c *gin.Context) { writeGatewayError(c, err) return } - c.JSON(http.StatusOK, videoGenerationResponse(job, h.videoContentURL(job.ID))) + c.JSON(http.StatusOK, videoGenerationResponse(job, h.videoPlaybackURL(job))) } -func (h *Handler) videoContentURL(jobID string) string { - path := "/v1/videos/" + url.PathEscape(jobID) + "/content" +func (h *Handler) publicURL(path string) string { baseURL := h.publicAPIBaseURL if h.publicBaseURL != nil { baseURL = strings.TrimRight(strings.TrimSpace(h.publicBaseURL()), "/") @@ -923,6 +922,22 @@ func (h *Handler) videoContentURL(jobID string) string { return baseURL + path } +func (h *Handler) videoContentURL(jobID string) string { + return h.publicURL("/v1/videos/" + url.PathEscape(jobID) + "/content") +} + +// videoPlaybackURL prefers the stored asset served by the public media route, so the +// returned link opens directly in browsers and players. /v1/videos/{id}/content needs +// the client API key, which makes the URL unusable outside an authenticated client. +// Images already return their public media URL; this keeps video consistent. Jobs +// without a stored asset keep the protected content endpoint. +func (h *Handler) videoPlaybackURL(job mediadomain.Job) string { + if assetID := strings.TrimSpace(job.ResultAssetID); assetID != "" { + return h.publicURL("/v1/media/videos/" + url.PathEscape(assetID)) + } + return h.videoContentURL(job.ID) +} + func (h *Handler) getVideoContent(c *gin.Context) { clientKey, _, ok := requestIdentity(c) if !ok { diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go index 75a7dc69..9e70aa17 100644 --- a/backend/internal/transport/http/inference/handler_test.go +++ b/backend/internal/transport/http/inference/handler_test.go @@ -134,6 +134,31 @@ func TestVideoContentURLUsesConfiguredPublicAPIBase(t *testing.T) { } } +// A completed job carries a stored asset, so the returned URL must point at the +// public media route. /v1/videos/{id}/content requires the client API key and is +// therefore not usable in a browser or player. +func TestVideoPlaybackURLPrefersPublicAssetRoute(t *testing.T) { + handler := NewHandler(nil, nil, 1<<20, "https://api.example.com/grok2api/") + job := mediadomain.Job{ + ID: "video_request_1", Status: mediadomain.StatusCompleted, + UpstreamURL: "https://assets.grok.com/source.mp4", ResultAssetID: "vid_abc123", + } + response := videoGenerationResponse(job, handler.videoPlaybackURL(job)) + video, ok := response["video"].(gin.H) + if !ok || video["url"] != "https://api.example.com/grok2api/v1/media/videos/vid_abc123" { + t.Fatalf("response = %#v", response) + } +} + +// Without a stored asset the protected content endpoint remains the only option. +func TestVideoPlaybackURLFallsBackToContentEndpoint(t *testing.T) { + handler := NewHandler(nil, nil, 1<<20, "https://api.example.com/grok2api/") + job := mediadomain.Job{ID: "video_request_1", Status: mediadomain.StatusCompleted} + if got := handler.videoPlaybackURL(job); got != "https://api.example.com/grok2api/v1/videos/video_request_1/content" { + t.Fatalf("fallback URL = %q", got) + } +} + func TestVideoContentURLFollowsRuntimePublicAPIBase(t *testing.T) { baseURL := "https://old.example.com" handler := NewHandler(nil, nil, 1<<20, "https://static.example.com").SetPublicAPIBaseURLResolver(func() string { From d5da097512e0f50c0246bf5b2302fcc3be86d572 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Thu, 13 Aug 2026 22:41:44 +0800 Subject: [PATCH 24/48] feat: support grok-4.6 xhigh and map max to xhigh --- .../internal/domain/model/reasoning_test.go | 8 +++ .../internal/infra/provider/cli/normalize.go | 11 ++-- .../infra/provider/cli/normalize_test.go | 54 ++++++++++++++++++- .../http/inference/model_list_test.go | 18 +++++++ frontend/src/shared/i18n/index.ts | 4 +- 5 files changed, 88 insertions(+), 7 deletions(-) diff --git a/backend/internal/domain/model/reasoning_test.go b/backend/internal/domain/model/reasoning_test.go index 0ed814d1..48e1f482 100644 --- a/backend/internal/domain/model/reasoning_test.go +++ b/backend/internal/domain/model/reasoning_test.go @@ -19,6 +19,7 @@ func TestSupportedReasoningEffortsPerModel(t *testing.T) { {model: "grok-4.20-multi-agent-0309", want: []string{"low", "medium", "high", "xhigh"}}, {model: "grok-4.6", want: []string{"low", "medium", "high", "xhigh"}}, {model: "Build/grok-4.6", want: []string{"low", "medium", "high", "xhigh"}}, + {model: "Console/grok-4.6", want: []string{"low", "medium", "high", "xhigh"}}, {model: "grok-build-0.1", want: []string{"none"}}, {model: GrokComposer25Fast, want: []string{"none"}}, {model: "unknown-model", want: []string{"none"}}, @@ -43,6 +44,10 @@ func TestSupportedReasoningEffortsPerModel(t *testing.T) { if !SupportsReasoningEffort("grok-4.6", "xhigh") || !SupportsReasoningEffort("Build/grok-4.6-xhigh", "xhigh") { t.Fatal("grok-4.6 must advertise xhigh") } + if !SupportsReasoningEffortForProvider(account.ProviderBuild, "grok-4.6", "xhigh") || + !SupportsReasoningEffortForProvider(account.ProviderConsole, "grok-4.6", "xhigh") { + t.Fatal("grok-4.6 xhigh must remain available through Build and Console") + } if SupportsReasoningEffort("grok-4.6", "none") || SupportsReasoningEffort("grok-4.6", "max") { t.Fatal("grok-4.6 must not advertise none/max") } @@ -119,4 +124,7 @@ func TestReasoningAliasPublicIDs(t *testing.T) { if got := ReasoningAliasPublicIDsForProvider(account.ProviderBuild, "grok-4.20-0309-reasoning"); len(got) != 3 { t.Fatalf("Console restriction leaked into Build aliases: %#v", got) } + if got := ReasoningAliasPublicIDsForProvider(account.ProviderConsole, "grok-4.6"); len(got) != 4 || got[3] != "grok-4.6-xhigh" { + t.Fatalf("Console grok-4.6 aliases = %#v", got) + } } diff --git a/backend/internal/infra/provider/cli/normalize.go b/backend/internal/infra/provider/cli/normalize.go index b1d6b15f..1a50f12b 100644 --- a/backend/internal/infra/provider/cli/normalize.go +++ b/backend/internal/infra/provider/cli/normalize.go @@ -118,8 +118,9 @@ func applyBuildResponseDefaults(payload map[string]json.RawMessage) (bool, error // normalizeBuildReasoningEffortPayload maps client aliases to levels accepted by // the selected Grok model. Grok 4.5 and unknown models retain the proven defensive -// xhigh/max -> high behavior; grok-4.6 and other explicitly supported xhigh models -// keep their value. Unverified max remains guarded. +// xhigh/max -> high behavior for models without an xhigh wire contract. Models +// that explicitly support xhigh keep xhigh and map the client-only max alias to +// that highest verified upstream level. func normalizeBuildReasoningEffortPayload(payload map[string]json.RawMessage, model string) bool { raw, exists := payload["reasoning"] if !exists || isEmptyJSON(raw) { @@ -157,7 +158,11 @@ func normalizeBuildReasoningEffortPayload(payload map[string]json.RawMessage, mo normalized = modeldomain.ReasoningEffortHigh } case "max": - normalized = modeldomain.ReasoningEffortHigh + if modeldomain.SupportsReasoningEffort(model, modeldomain.ReasoningEffortXHigh) { + normalized = modeldomain.ReasoningEffortXHigh + } else { + normalized = modeldomain.ReasoningEffortHigh + } default: return false } diff --git a/backend/internal/infra/provider/cli/normalize_test.go b/backend/internal/infra/provider/cli/normalize_test.go index 2b1331c6..ceb32a4e 100644 --- a/backend/internal/infra/provider/cli/normalize_test.go +++ b/backend/internal/infra/provider/cli/normalize_test.go @@ -52,11 +52,13 @@ func TestNormalizeBuildReasoningEffort(t *testing.T) { {name: "4.5 uppercase max", model: "grok-4.5", effort: "MAX", want: "high"}, {name: "multi-agent xhigh", model: "grok-4.20-multi-agent-0309", effort: "xhigh", want: "xhigh"}, {name: "multi-agent uppercase xhigh", model: "grok-4.20-multi-agent-0309", effort: "XHIGH", want: "xhigh"}, - {name: "multi-agent max remains guarded", model: "grok-4.20-multi-agent-0309", effort: "max", want: "high"}, + {name: "multi-agent max maps to highest supported effort", model: "grok-4.20-multi-agent-0309", effort: "max", want: "xhigh"}, {name: "4.6 xhigh", model: "grok-4.6", effort: "xhigh", want: "xhigh"}, {name: "4.6 uppercase xhigh", model: "grok-4.6", effort: "XHIGH", want: "xhigh"}, - {name: "4.6 max remains guarded", model: "grok-4.6", effort: "max", want: "high"}, + {name: "4.6 max maps to xhigh", model: "grok-4.6", effort: "max", want: "xhigh"}, + {name: "prefixed 4.6 uppercase max maps to xhigh", model: "Build/grok-4.6", effort: "MAX", want: "xhigh"}, {name: "unknown xhigh remains guarded", model: "future-model", effort: "xhigh", want: "high"}, + {name: "unknown max remains guarded", model: "future-model", effort: "max", want: "high"}, {name: "high", model: "grok-4.5", effort: "high", want: "high"}, {name: "medium", model: "grok-4.5", effort: "medium", want: "medium"}, } @@ -79,6 +81,54 @@ func TestNormalizeBuildReasoningEffort(t *testing.T) { } } +func TestNormalizeBuildMaxAcrossCompatibilityProtocols(t *testing.T) { + tests := []struct { + name string + body []byte + }{ + {name: "responses", body: []byte(`{"reasoning":{"effort":"max"},"input":"hello"}`)}, + {name: "chat completions", body: func() []byte { + converted, _, err := conversation.ConvertRequestWithOptions( + []byte(`{"model":"public","messages":[{"role":"user","content":"hello"}],"reasoning_effort":"max"}`), + "grok-4.6", + conversation.OperationChat, + ) + if err != nil { + t.Fatal(err) + } + return converted + }()}, + {name: "anthropic messages", body: func() []byte { + converted, _, err := conversation.ConvertRequestWithOptions( + []byte(`{"model":"public","max_tokens":64,"messages":[{"role":"user","content":"hello"}],"thinking":{"type":"adaptive"},"output_config":{"effort":"max"}}`), + "grok-4.6", + conversation.OperationMessages, + ) + if err != nil { + t.Fatal(err) + } + return converted + }()}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + normalized, err := normalizeBuildRequest(test.body, "grok-4.6") + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(normalized, &payload); err != nil { + t.Fatal(err) + } + reasoning, ok := payload["reasoning"].(map[string]any) + if !ok || reasoning["effort"] != "xhigh" { + t.Fatalf("reasoning = %#v, want max normalized to xhigh", payload["reasoning"]) + } + }) + } +} + func TestNormalizeBuildComposerStripsReasoningEffort(t *testing.T) { tests := []struct { name string diff --git a/backend/internal/transport/http/inference/model_list_test.go b/backend/internal/transport/http/inference/model_list_test.go index 9301d21b..ae18757d 100644 --- a/backend/internal/transport/http/inference/model_list_test.go +++ b/backend/internal/transport/http/inference/model_list_test.go @@ -69,6 +69,24 @@ func TestAppendReasoningModelAliasesUsesRealSupportedLevels(t *testing.T) { } } +func TestAppendReasoningModelAliasesIncludesConsoleGrok46XHigh(t *testing.T) { + expanded := appendReasoningModelAliases([]modelListItem{{ + ID: "grok-4.6", Provider: account.ProviderConsole, Capability: modeldomain.CapabilityResponses, + }}) + ids := make(map[string]bool, len(expanded)) + for _, item := range expanded { + ids[item.ID] = true + } + for _, want := range []string{"grok-4.6-low", "grok-4.6-medium", "grok-4.6-high", "grok-4.6-xhigh"} { + if !ids[want] { + t.Fatalf("missing Console alias %q in %#v", want, expanded) + } + } + if ids["grok-4.6-max"] { + t.Fatalf("client compatibility value max must not be advertised as a model alias: %#v", expanded) + } +} + func TestNewCodexModelCatalogIncludesRequiredProtocolFields(t *testing.T) { now := time.Unix(100, 0).UTC() items := newModelListItems([]modeldomain.Route{ diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index 45e81c9c..b120075e 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -733,7 +733,7 @@ const resources = { modelAliases: "模型别名", modelAliasesDescription: "仅为当前可用且支持多个推理等级的模型生成后缀别名。", modelAliasesBuildSupport: "Grok Build:grok-4.6 支持 low / medium / high / xhigh;grok-4.5、grok-3-mini、grok-3-mini-fast 支持 low / medium / high。", - modelAliasesConsoleSupport: "Grok Console:grok-4.3 支持 none / low / medium / high;grok-4.20-0309-reasoning 为固定推理模式,不支持调节 effort;grok-4.20-multi-agent-0309 额外支持 xhigh。", + modelAliasesConsoleSupport: "Grok Console:grok-4.6 支持 low / medium / high / xhigh;grok-4.3 支持 none / low / medium / high;grok-4.20-0309-reasoning 为固定推理模式,不支持调节 effort;grok-4.20-multi-agent-0309 额外支持 xhigh。", modelAliasesUnsupported: "Grok Web、图片模型和视频模型不生成推理等级后缀。", modelAliasesOn: "已开启:可发现并调用当前模型支持的推理等级别名。", modelAliasesOff: "已关闭:不生成动态推理别名;既有 Console 兼容别名不受影响。", @@ -1342,7 +1342,7 @@ const resources = { 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" }, 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.6 supports low / medium / high / xhigh; 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?" }, + 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.6 supports low / medium / high / xhigh; grok-4.5, grok-3-mini, and grok-3-mini-fast support low / medium / high.", modelAliasesConsoleSupport: "Grok Console: grok-4.6 supports low / medium / high / xhigh; 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: { title: "Request audits", description: "Successful requests store metadata only. Failed requests retain a redacted and size-limited diagnostic snapshot.", From 6ed327b3d6d7e75dcc7fabac0b8097825a48fb24 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Thu, 13 Aug 2026 22:50:19 +0800 Subject: [PATCH 25/48] feat: add grok-4.6 xhigh and Codex metadata --- .../transport/http/inference/codex_models.go | 1 + .../http/inference/model_list_test.go | 36 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/backend/internal/transport/http/inference/codex_models.go b/backend/internal/transport/http/inference/codex_models.go index ee907cb9..da843eef 100644 --- a/backend/internal/transport/http/inference/codex_models.go +++ b/backend/internal/transport/http/inference/codex_models.go @@ -87,6 +87,7 @@ type grokModelCapability struct { // Codex catalogs never diverge from the levels each model actually supports. var grokCapabilities = map[string]grokModelCapability{ "grok-4.5": {500000, "xAI Grok 4.5 frontier model with reasoning and vision.", true}, + "grok-4.6": {500000, "xAI Grok 4.6 frontier model with reasoning and vision.", true}, "grok-4.3": {1000000, "xAI Grok 4.3 high-capacity reasoning model.", true}, "grok-build-0.1": {256000, "xAI Grok Build 0.1 coding model.", false}, "grok-4.20-0309-reasoning": {2000000, "xAI Grok 4.20 reasoning model.", true}, diff --git a/backend/internal/transport/http/inference/model_list_test.go b/backend/internal/transport/http/inference/model_list_test.go index ae18757d..49947352 100644 --- a/backend/internal/transport/http/inference/model_list_test.go +++ b/backend/internal/transport/http/inference/model_list_test.go @@ -128,6 +128,42 @@ func TestNewCodexModelCatalogIncludesRequiredProtocolFields(t *testing.T) { } } +func TestCodexCatalogUsesGrok46MetadataForBaseAndXHighAlias(t *testing.T) { + items := []modelListItem{ + {ID: "grok-4.6", Provider: account.ProviderBuild, Capability: modeldomain.CapabilityResponses}, + {ID: "grok-4.6-xhigh", Provider: account.ProviderBuild, Capability: modeldomain.CapabilityResponses}, + } + models := newCodexModelCatalog(items).Models + if len(models) != 2 { + t.Fatalf("model count = %d, want 2", len(models)) + } + + base := models[0] + if base.ContextWindow != 500000 || base.MaxContextWindow != 500000 { + t.Fatalf("grok-4.6 context window = %d/%d, want 500000/500000", base.ContextWindow, base.MaxContextWindow) + } + if base.Description != "xAI Grok 4.6 frontier model with reasoning and vision." { + t.Fatalf("grok-4.6 description = %q", base.Description) + } + if len(base.InputModalities) != 2 || base.InputModalities[0] != "text" || base.InputModalities[1] != "image" { + t.Fatalf("grok-4.6 input modalities = %#v, want text/image", base.InputModalities) + } + if base.DefaultReasoningLevel != "medium" || len(base.SupportedReasoningLevels) != 4 || base.SupportedReasoningLevels[3].Effort != "xhigh" { + t.Fatalf("grok-4.6 reasoning metadata = default %q, levels %#v", base.DefaultReasoningLevel, base.SupportedReasoningLevels) + } + if !base.SupportsReasoningSummaryParameter || !base.SupportsReasoningSummaries { + t.Fatalf("grok-4.6 reasoning support missing: %#v", base) + } + + alias := models[1] + if alias.ContextWindow != base.ContextWindow || alias.MaxContextWindow != base.MaxContextWindow || alias.Description != base.Description { + t.Fatalf("grok-4.6-xhigh did not inherit base metadata: %#v", alias) + } + if len(alias.InputModalities) != 2 || alias.DefaultReasoningLevel != "xhigh" || len(alias.SupportedReasoningLevels) != 1 || alias.SupportedReasoningLevels[0].Effort != "xhigh" { + t.Fatalf("grok-4.6-xhigh metadata = %#v", alias) + } +} + func TestCodexCatalogMarksConsoleGrok420AsFixedReasoning(t *testing.T) { entry := newCodexModelCatalog([]modelListItem{{ ID: "grok-4.20-0309-reasoning", Provider: account.ProviderConsole, Capability: modeldomain.CapabilityResponses, From ed594187b0be3597ea715b0a369e519db98440e9 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Thu, 13 Aug 2026 22:55:25 +0800 Subject: [PATCH 26/48] fix: recover Statsig meta from index 404 without weakening status validation --- .../internal/infra/provider/web/statsig.go | 84 ++++++----- .../infra/provider/web/statsig_test.go | 141 +++++++++++++++--- 2 files changed, 171 insertions(+), 54 deletions(-) diff --git a/backend/internal/infra/provider/web/statsig.go b/backend/internal/infra/provider/web/statsig.go index c313eff9..c7dfdae3 100644 --- a/backend/internal/infra/provider/web/statsig.go +++ b/backend/internal/infra/provider/web/statsig.go @@ -5,6 +5,7 @@ import ( "context" "encoding/base64" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -29,6 +30,8 @@ const ( statsigResponseLimit = 4 << 10 ) +var errStatsigMetaMissing = errors.New("Grok index 缺少 grok-site-verification") + type statsigCacheEntry struct { value string expiresAt time.Time @@ -279,41 +282,47 @@ func fetchStatsigMetaContentWithDo(ctx context.Context, baseURL, token string, l if do == nil { return "", fmt.Errorf("Statsig 获取缺少出口租约") } - var indexErr error - for _, path := range []string{"/index", "/"} { - content, err := fetchStatsigMetaContentPath(ctx, baseURL, token, lease, path, do) - if err == nil { - return content, nil - } - if path == "/index" { - indexErr = err - if !shouldFallbackStatsigMeta(err) { - return "", err - } - continue - } + index, err := fetchStatsigMetaResponse(ctx, baseURL, token, lease, "/index", do) + if err != nil { return "", err } - if indexErr != nil { - return "", indexErr + if index.statusCode >= 200 && index.statusCode < 300 { + // A successful index response without the verification meta remains a hard + // protocol failure. Falling back here would hide a changed upstream page. + return extractStatsigMetaContent(index.body) } - return "", fmt.Errorf("Grok index 缺少 grok-site-verification") + if index.statusCode != http.StatusNotFound { + return "", statsigMetaStatusError("/index", index.statusCode) + } + if content, extractErr := extractStatsigMetaContent(index.body); extractErr == nil { + return content, nil + } else if !errors.Is(extractErr, errStatsigMetaMissing) { + return "", extractErr + } + + // /index currently returns a branded 404. Only that exact status with a + // missing meta is allowed to fall back to the canonical root page. + root, err := fetchStatsigMetaResponse(ctx, baseURL, token, lease, "/", do) + if err != nil { + return "", err + } + if root.statusCode < 200 || root.statusCode >= 300 { + return "", statsigMetaStatusError("/", root.statusCode) + } + return extractStatsigMetaContent(root.body) } -func shouldFallbackStatsigMeta(err error) bool { - if err == nil { - return false - } - message := err.Error() - return strings.Contains(message, "缺少 grok-site-verification") || strings.Contains(message, "Grok index 返回 ") +type statsigMetaResponse struct { + statusCode int + body []byte } -func fetchStatsigMetaContentPath(ctx context.Context, baseURL, token string, lease *infraegress.Lease, path string, do func(*http.Request) (*http.Response, error)) (string, error) { +func fetchStatsigMetaResponse(ctx context.Context, baseURL, token string, lease *infraegress.Lease, path string, do func(*http.Request) (*http.Response, error)) (statsigMetaResponse, error) { requestCtx, cancel := context.WithTimeout(infraegress.WithPhysicalCallStage(ctx, "statsig_meta"), 15*time.Second) defer cancel() request, err := http.NewRequestWithContext(requestCtx, http.MethodGet, strings.TrimRight(baseURL, "/")+path, nil) if err != nil { - return "", err + return statsigMetaResponse{}, err } request.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") request.Header.Set("Accept-Encoding", "gzip, deflate, br, zstd") @@ -330,28 +339,31 @@ func fetchStatsigMetaContentPath(ctx context.Context, baseURL, token string, lea } response, err := do(request) if err != nil { - return "", err + return statsigMetaResponse{}, err } defer response.Body.Close() body, err := io.ReadAll(io.LimitReader(response.Body, statsigMetaBodyLimit+1)) if err != nil { - return "", err + return statsigMetaResponse{}, err } if len(body) > statsigMetaBodyLimit { - return "", fmt.Errorf("Grok index 超过安全上限") + return statsigMetaResponse{}, statsigMetaOversizeError(path) } - return statsigMetaFromHTTP(response.StatusCode, body) + return statsigMetaResponse{statusCode: response.StatusCode, body: body}, nil } -func statsigMetaFromHTTP(status int, body []byte) (string, error) { - content, err := extractStatsigMetaContent(body) - if err == nil { - return content, nil +func statsigMetaStatusError(path string, statusCode int) error { + if path == "/" { + return fmt.Errorf("Grok 首页返回 %d", statusCode) } - if status < 200 || status >= 300 { - return "", fmt.Errorf("Grok index 返回 %d", status) + return fmt.Errorf("Grok index 返回 %d", statusCode) +} + +func statsigMetaOversizeError(path string) error { + if path == "/" { + return fmt.Errorf("Grok 首页超过安全上限") } - return "", err + return fmt.Errorf("Grok index 超过安全上限") } func extractStatsigMetaContent(body []byte) (string, error) { @@ -360,7 +372,7 @@ func extractStatsigMetaContent(body []byte) (string, error) { switch tokenizer.Next() { case html.ErrorToken: if tokenizer.Err() == io.EOF { - return "", fmt.Errorf("Grok index 缺少 grok-site-verification") + return "", errStatsigMetaMissing } return "", tokenizer.Err() case html.StartTagToken, html.SelfClosingTagToken: diff --git a/backend/internal/infra/provider/web/statsig_test.go b/backend/internal/infra/provider/web/statsig_test.go index 0ac543d3..d7953366 100644 --- a/backend/internal/infra/provider/web/statsig_test.go +++ b/backend/internal/infra/provider/web/statsig_test.go @@ -19,25 +19,10 @@ type roundTripFunc func(*http.Request) (*http.Response, error) func (f roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) { return f(request) } -func TestStatsigMetaFromHTTPAcceptsIndexNotFoundWithVerification(t *testing.T) { - body := []byte(``) - value, err := statsigMetaFromHTTP(http.StatusNotFound, body) - if err != nil || value != "meta-value" { - t.Fatalf("value=%q err=%v", value, err) - } -} +type failingStatsigBody struct{} -func TestStatsigMetaFromHTTPKeepsMissingVerificationErrorOnSuccessStatus(t *testing.T) { - if _, err := statsigMetaFromHTTP(http.StatusOK, []byte(``)); err == nil || !strings.Contains(err.Error(), "缺少 grok-site-verification") { - t.Fatalf("err=%v", err) - } -} - -func TestStatsigMetaFromHTTPPreservesStatusWhenVerificationMissing(t *testing.T) { - if _, err := statsigMetaFromHTTP(http.StatusNotFound, []byte(``)); err == nil || !strings.Contains(err.Error(), "Grok index 返回 404") { - t.Fatalf("err=%v", err) - } -} +func (failingStatsigBody) Read([]byte) (int, error) { return 0, errors.New("read failed") } +func (failingStatsigBody) Close() error { return nil } func TestFetchStatsigMetaContentFallsBackToRootWhenIndexHasNoVerification(t *testing.T) { var paths []string @@ -80,6 +65,126 @@ func TestFetchStatsigMetaContentDoesNotFallbackWhenIndex404HasVerification(t *te } } +func TestFetchStatsigMetaContentDoesNotFallbackWhenSuccessfulIndexHasNoVerification(t *testing.T) { + var paths []string + do := func(request *http.Request) (*http.Response, error) { + paths = append(paths, request.URL.Path) + return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(``)), Header: http.Header{}}, nil + } + _, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do) + if !errors.Is(err, errStatsigMetaMissing) { + t.Fatalf("err=%v", err) + } + if len(paths) != 1 || paths[0] != "/index" { + t.Fatalf("successful index without verification must not fall back: paths=%v", paths) + } +} + +func TestFetchStatsigMetaContentRejectsNon404IndexStatuses(t *testing.T) { + for _, status := range []int{http.StatusMovedPermanently, http.StatusForbidden, http.StatusTooManyRequests, http.StatusInternalServerError, http.StatusServiceUnavailable} { + for _, withMeta := range []bool{false, true} { + t.Run(fmt.Sprintf("status_%d_meta_%t", status, withMeta), func(t *testing.T) { + body := `` + if withMeta { + body = `` + } + var calls int + do := func(request *http.Request) (*http.Response, error) { + calls++ + if request.URL.Path != "/index" { + t.Fatalf("unexpected fallback to %q", request.URL.Path) + } + return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(body)), Header: http.Header{}}, nil + } + _, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do) + if err == nil || !strings.Contains(err.Error(), fmt.Sprintf("Grok index 返回 %d", status)) { + t.Fatalf("err=%v", err) + } + if calls != 1 { + t.Fatalf("calls=%d", calls) + } + }) + } + } +} + +func TestFetchStatsigMetaContentRequiresSuccessfulRoot(t *testing.T) { + for _, withMeta := range []bool{false, true} { + t.Run(fmt.Sprintf("meta_%t", withMeta), func(t *testing.T) { + body := `` + if withMeta { + body = `` + } + do := func(request *http.Request) (*http.Response, error) { + if request.URL.Path == "/index" { + return &http.Response{StatusCode: http.StatusNotFound, Body: io.NopCloser(strings.NewReader(``)), Header: http.Header{}}, nil + } + return &http.Response{StatusCode: http.StatusServiceUnavailable, Body: io.NopCloser(strings.NewReader(body)), Header: http.Header{}}, nil + } + _, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do) + if err == nil || !strings.Contains(err.Error(), "Grok 首页返回 503") { + t.Fatalf("err=%v", err) + } + }) + } +} + +func TestFetchStatsigMetaContentRequiresVerificationOnSuccessfulRoot(t *testing.T) { + do := func(request *http.Request) (*http.Response, error) { + status := http.StatusOK + if request.URL.Path == "/index" { + status = http.StatusNotFound + } + return &http.Response{ + StatusCode: status, + Body: io.NopCloser(strings.NewReader(``)), + Header: http.Header{}, + }, nil + } + _, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do) + if !errors.Is(err, errStatsigMetaMissing) { + t.Fatalf("err=%v", err) + } +} + +func TestFetchStatsigMetaContentDoesNotFallbackOnTransportReadOrOversizeFailure(t *testing.T) { + t.Run("transport", func(t *testing.T) { + var calls int + do := func(*http.Request) (*http.Response, error) { + calls++ + return nil, errors.New("dial failed") + } + _, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do) + if err == nil || err.Error() != "dial failed" || calls != 1 { + t.Fatalf("err=%v calls=%d", err, calls) + } + }) + + t.Run("read", func(t *testing.T) { + var calls int + do := func(*http.Request) (*http.Response, error) { + calls++ + return &http.Response{StatusCode: http.StatusNotFound, Body: failingStatsigBody{}, Header: http.Header{}}, nil + } + _, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do) + if err == nil || err.Error() != "read failed" || calls != 1 { + t.Fatalf("err=%v calls=%d", err, calls) + } + }) + + t.Run("oversize", func(t *testing.T) { + var calls int + do := func(*http.Request) (*http.Response, error) { + calls++ + return &http.Response{StatusCode: http.StatusNotFound, Body: io.NopCloser(strings.NewReader(strings.Repeat("x", statsigMetaBodyLimit+1))), Header: http.Header{}}, nil + } + _, err := fetchStatsigMetaContentWithDo(context.Background(), "https://grok.com", "sso-token", &infraegress.Lease{UserAgent: "test-agent"}, do) + if err == nil || !strings.Contains(err.Error(), "超过安全上限") || calls != 1 { + t.Fatalf("err=%v calls=%d", err, calls) + } + }) +} + func TestExtractStatsigMetaContentAcceptsCurrentMetaName(t *testing.T) { for _, name := range []string{"grok-site―verification", "grok-site-verification"} { body := []byte(``) From 49daa16cf76bc7348533a79890cde383f98ac707 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Thu, 13 Aug 2026 23:00:26 +0800 Subject: [PATCH 27/48] fix: make serialized Build detect observers panic-safe --- .../application/account/build_detect_test.go | 110 +++++++++++++----- .../internal/application/account/service.go | 14 ++- 2 files changed, 86 insertions(+), 38 deletions(-) diff --git a/backend/internal/application/account/build_detect_test.go b/backend/internal/application/account/build_detect_test.go index 9fec90f7..9d0ab222 100644 --- a/backend/internal/application/account/build_detect_test.go +++ b/backend/internal/application/account/build_detect_test.go @@ -9,6 +9,7 @@ import ( "net/http" "path/filepath" "strconv" + "sync/atomic" "testing" "time" @@ -294,45 +295,15 @@ func TestDetectBuildAccountsStreamsInvalidOnlyForAll(t *testing.T) { } func TestDetectBuildAccountsSerializesItemObserver(t *testing.T) { - ctx := context.Background() - database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "detect-observer.db")) - if err != nil { - t.Fatal(err) - } - defer database.Close() - if err := database.InitializeSchema(ctx); err != nil { - t.Fatal(err) - } - cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) - if err != nil { - t.Fatal(err) - } - accessToken, err := cipher.Encrypt("access-token") - if err != nil { - t.Fatal(err) - } - repo := relational.NewAccountRepository(database) const accountCount = 8 - for index := range accountCount { - if _, _, err := repo.UpsertByIdentity(ctx, accountdomain.Credential{ - Provider: accountdomain.ProviderBuild, Name: "invalid-" + strconv.Itoa(index), UserID: "user-invalid-" + strconv.Itoa(index), - SourceKey: "detect-invalid-" + strconv.Itoa(index), EncryptedAccessToken: accessToken, - Enabled: true, AuthStatus: accountdomain.AuthStatusActive, RefreshPermanent: true, Priority: 1, MaxConcurrent: 1, - }); err != nil { - t.Fatal(err) - } - } - service := NewService(repo, nil, nil, nil, provider.NewRegistry(detectResponsesAdapter{ - status: http.StatusUnauthorized, - }), cipher, nil) - service.SetDetectPool(batch.NewPool(accountCount)) + service := newConcurrentInvalidBuildDetectService(t, accountCount) started := make(chan struct{}, accountCount) release := make(chan struct{}) var items []BuildDetectItemResult errCh := make(chan error, 1) go func() { - _, _, detectErr := service.DetectBuildAccountsWithProgress(ctx, nil, true, nil, func(item BuildDetectItemResult) error { + _, _, detectErr := service.DetectBuildAccountsWithProgress(context.Background(), nil, true, nil, func(item BuildDetectItemResult) error { started <- struct{}{} <-release items = append(items, item) @@ -355,3 +326,78 @@ func TestDetectBuildAccountsSerializesItemObserver(t *testing.T) { t.Fatalf("serialized items = %d, want %d", len(items), accountCount) } } + +func TestDetectBuildAccountsObserverPanicDoesNotDeadlock(t *testing.T) { + const accountCount = 8 + service := newConcurrentInvalidBuildDetectService(t, accountCount) + + type detectResult struct { + succeeded int + failed int + err error + } + var calls atomic.Int64 + resultCh := make(chan detectResult, 1) + go func() { + succeeded, failed, err := service.DetectBuildAccountsWithProgress(context.Background(), nil, true, nil, func(BuildDetectItemResult) error { + if calls.Add(1) == 1 { + panic("item observer panic") + } + return nil + }) + resultCh <- detectResult{succeeded: succeeded, failed: failed, err: err} + }() + + timer := time.NewTimer(2 * time.Second) + defer timer.Stop() + select { + case result := <-resultCh: + if result.err != nil { + t.Fatal(result.err) + } + if result.succeeded != 0 || result.failed != accountCount { + t.Fatalf("summary succeeded=%d failed=%d, want 0/%d", result.succeeded, result.failed, accountCount) + } + if got := calls.Load(); got != accountCount { + t.Fatalf("observer calls = %d, want %d", got, accountCount) + } + case <-timer.C: + t.Fatal("itemObserver panic deadlocked Build account detection") + } +} + +func newConcurrentInvalidBuildDetectService(t *testing.T, accountCount int) *Service { + t.Helper() + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "detect-observer.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = database.Close() }) + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + accessToken, err := cipher.Encrypt("access-token") + if err != nil { + t.Fatal(err) + } + repo := relational.NewAccountRepository(database) + for index := range accountCount { + if _, _, err := repo.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderBuild, Name: "invalid-" + strconv.Itoa(index), UserID: "user-invalid-" + strconv.Itoa(index), + SourceKey: "detect-invalid-" + strconv.Itoa(index), EncryptedAccessToken: accessToken, + Enabled: true, AuthStatus: accountdomain.AuthStatusActive, RefreshPermanent: true, Priority: 1, MaxConcurrent: 1, + }); err != nil { + t.Fatal(err) + } + } + service := NewService(repo, nil, nil, nil, provider.NewRegistry(detectResponsesAdapter{ + status: http.StatusUnauthorized, + }), cipher, nil) + service.SetDetectPool(batch.NewPool(accountCount)) + return service +} diff --git a/backend/internal/application/account/service.go b/backend/internal/application/account/service.go index 4261c6c7..5d45a0f7 100644 --- a/backend/internal/application/account/service.go +++ b/backend/internal/application/account/service.go @@ -3717,7 +3717,7 @@ func (s *Service) DetectBuildAccountsWithProgress(ctx context.Context, ids []uin return 0, 0, err } } - var progressMu sync.Mutex + var observerMu sync.Mutex var progressErr error completed := 0 runCtx, cancel := context.WithCancel(ctx) @@ -3725,9 +3725,11 @@ func (s *Service) DetectBuildAccountsWithProgress(ctx context.Context, ids []uin summary, err := batch.ForEachObserved(runCtx, ids, batch.Options{Workers: pool.Limit(), Pool: pool}, func(workCtx context.Context, id uint64) (BuildDetectItemResult, error) { item := s.detectBuildAccount(workCtx, id) if itemObserver != nil && (selectedMode || item.Outcome == BuildDetectOutcomeInvalid) { - progressMu.Lock() - notifyErr := itemObserver(item) - progressMu.Unlock() + notifyErr := func() error { + observerMu.Lock() + defer observerMu.Unlock() + return itemObserver(item) + }() if notifyErr != nil { return item, notifyErr } @@ -3744,8 +3746,8 @@ func (s *Service) DetectBuildAccountsWithProgress(ctx context.Context, ids []uin if errors.As(result.Err, &panicErr) { s.logger.Error("account_bulk_task_panicked", "operation", "build_detect", "account_id", ids[index], "error", panicErr, "stack", string(panicErr.Stack)) } - progressMu.Lock() - defer progressMu.Unlock() + observerMu.Lock() + defer observerMu.Unlock() completed++ if progress != nil { if notifyErr := progress(completed, len(ids)); notifyErr != nil && progressErr == nil { From 902c0d872783415aa46b31592eb82bf5a239fc9d Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Fri, 14 Aug 2026 08:43:19 +0800 Subject: [PATCH 28/48] feat: add scalable degraded-account monitoring --- backend/internal/application/audit/degrade.go | 330 ++++++++--------- .../application/audit/degrade_test.go | 158 +++++++- backend/internal/domain/audit/degrade.go | 10 +- backend/internal/domain/audit/degrade_test.go | 6 +- .../relational/audit_repository.go | 338 +++++++++++++++--- .../relational/audit_repository_test.go | 11 + .../infra/persistence/relational/schema.go | 1 + backend/internal/repository/audit.go | 96 ++++- .../internal/transport/http/audit/handler.go | 86 +++-- .../transport/http/audit/handler_test.go | 6 +- .../internal/transport/http/egress/handler.go | 3 + .../transport/http/egress/handler_test.go | 4 +- .../quality-guard/degrade-accounts-panel.tsx | 169 +++++---- .../quality-guard/quality-guard-api.ts | 34 +- .../quality-guard/quality-guard-page.tsx | 7 +- frontend/src/shared/components/pagination.tsx | 10 +- frontend/src/shared/i18n/index.ts | 16 +- 17 files changed, 887 insertions(+), 398 deletions(-) diff --git a/backend/internal/application/audit/degrade.go b/backend/internal/application/audit/degrade.go index 96758715..06880b28 100644 --- a/backend/internal/application/audit/degrade.go +++ b/backend/internal/application/audit/degrade.go @@ -3,7 +3,7 @@ package audit import ( "context" "math" - "sort" + "strings" "time" auditdomain "github.com/chenyme/grok2api/backend/internal/domain/audit" @@ -11,19 +11,31 @@ import ( ) const ( - degradeWindow1h = "1h" - degradeWindow6h = "6h" - degradeWindow24h = "24h" - degradeWindow7d = "7d" - degradeEventLimit = 20_000 - degradeRecentEventCap = 80 + degradeWindow1h = "1h" + degradeWindow6h = "6h" + degradeWindow24h = "24h" + degradeWindow7d = "7d" + degradeRecentEventCap = 80 + degradeDefaultPage = 1 + degradeDefaultPageSize = 50 + degradeMaxPageSize = 100 ) type DegradeThresholds struct { - SoftTPS float64 - HardTPS float64 - MinGenMS int64 - MinOut int64 + SoftTPS float64 + HardTPS float64 + MinGenMS int64 + MinOut int64 + FailClosed bool +} + +type DegradeAccountFilter struct { + Search string + Status string + Class string + MinHits int + Page int + PageSize int } type DegradeSummary struct { @@ -34,30 +46,39 @@ type DegradeSummary struct { Series []DegradeBucket Nodes []DegradeNode Accounts []DegradeAccount + AccountPage DegradeAccountPage Events []DegradeEventView } type DegradeTotals struct { - Hits int - Accounts int - StillEnabled int - Disabled int - Hard int - Soft int - Burst int + Hits int64 + Accounts int64 + StillEnabled int64 + Disabled int64 + Deleted int64 + Hard int64 + Soft int64 + Burst int64 MaxTPS float64 } +type DegradeAccountPage struct { + Page int + PageSize int + Total int64 + HasMore bool +} + type DegradeBucket struct { Label string `json:"label"` - Count int `json:"count"` - Severe int `json:"severe"` + Count int64 `json:"count"` + Severe int64 `json:"severe"` } type DegradeNode struct { Name string `json:"name"` - Hits int `json:"hits"` - Accounts int `json:"accounts"` + Hits int64 `json:"hits"` + Accounts int64 `json:"accounts"` MaxTPS float64 `json:"maxTPS"` } @@ -65,14 +86,14 @@ type DegradeAccount struct { ID uint64 Name string Email string - Hits int + Hits int64 MaxTPS float64 - Classes map[string]int + Classes map[string]int64 Nodes []string Last time.Time Enabled bool - BFS int Found bool + BFS int } type DegradeEventView struct { @@ -88,19 +109,34 @@ type DegradeEventView struct { Model string } -func (s *Service) DegradeSummary(ctx context.Context, window string, thresholds DegradeThresholds) (DegradeSummary, error) { +type degradeBucketSpec struct { + Range repository.DegradeBucketRange + Label string +} + +func (s *Service) DegradeSummary(ctx context.Context, window string, thresholds DegradeThresholds, filter DegradeAccountFilter) (DegradeSummary, error) { window, start, end, err := resolveDegradeWindow(window, s.now().UTC()) if err != nil { return DegradeSummary{}, err } thresholds = normalizeDegradeThresholds(thresholds) - events, err := s.audits.ListDegradeEvents(ctx, repository.DegradeEventQuery{ - Start: start, End: end, MinOutputTokens: thresholds.MinOut, Limit: degradeEventLimit, + filter = normalizeDegradeAccountFilter(filter) + bucketSpecs := degradeBucketSpecs(window, start, end) + bucketRanges := make([]repository.DegradeBucketRange, 0, len(bucketSpecs)) + for _, spec := range bucketSpecs { + bucketRanges = append(bucketRanges, spec.Range) + } + data, err := s.audits.SummarizeDegrade(ctx, repository.DegradeSummaryQuery{ + Start: start, End: end, SoftTPS: thresholds.SoftTPS, HardTPS: thresholds.HardTPS, + MinGenerationMS: thresholds.MinGenMS, MinOutputTokens: thresholds.MinOut, FailClosed: thresholds.FailClosed, + AccountSearch: filter.Search, AccountStatus: filter.Status, AccountClass: filter.Class, MinHits: filter.MinHits, + AccountOffset: (filter.Page - 1) * filter.PageSize, AccountLimit: filter.PageSize, + Buckets: bucketRanges, RecentLimit: degradeRecentEventCap, }) if err != nil { return DegradeSummary{}, err } - return buildDegradeSummary(window, end, thresholds, events), nil + return buildDegradeSummary(window, end, thresholds, filter, bucketSpecs, data), nil } func resolveDegradeWindow(value string, now time.Time) (string, time.Time, time.Time, error) { @@ -143,189 +179,109 @@ func normalizeDegradeThresholds(value DegradeThresholds) DegradeThresholds { return value } -func buildDegradeSummary(window string, now time.Time, thresholds DegradeThresholds, events []repository.DegradeEvent) DegradeSummary { - type accAgg struct { - hits int - maxTPS float64 - classes map[string]int - nodes map[string]struct{} - last time.Time - name string - email string - enabled bool - found bool - bfs int +func normalizeDegradeAccountFilter(value DegradeAccountFilter) DegradeAccountFilter { + value.Search = strings.TrimSpace(value.Search) + if value.Status != "enabled" && value.Status != "disabled" && value.Status != "deleted" { + value.Status = "" } - type nodeAgg struct { - hits int - accounts map[uint64]struct{} - maxTPS float64 + if value.Class != auditdomain.DegradeClassBurst && value.Class != auditdomain.DegradeClassSoft && value.Class != auditdomain.DegradeClassHard { + value.Class = "" } - accounts := map[uint64]*accAgg{} - nodes := map[string]*nodeAgg{} - classCounts := map[string]int{} - var classified []DegradeEventView - var maxTPS float64 + if value.MinHits < 1 { + value.MinHits = 1 + } + if value.Page < 1 { + value.Page = degradeDefaultPage + } + if value.PageSize < 1 || value.PageSize > degradeMaxPageSize { + value.PageSize = degradeDefaultPageSize + } + return value +} - for _, event := range events { - class, tps, _ := auditdomain.ClassifyOutputSpeed(event.OutputTokens, event.FirstTokenMS, event.DurationMS, thresholds.SoftTPS, thresholds.HardTPS, thresholds.MinGenMS) - if class == "" { - continue - } - classCounts[class]++ - if tps > maxTPS { - maxTPS = tps - } - nodeName := event.EgressNodeName +func buildDegradeSummary(window string, now time.Time, thresholds DegradeThresholds, filter DegradeAccountFilter, bucketSpecs []degradeBucketSpec, data repository.DegradeSummaryResult) DegradeSummary { + accounts := make([]DegradeAccount, 0, len(data.Accounts)) + for _, value := range data.Accounts { + accounts = append(accounts, DegradeAccount{ + ID: value.ID, Name: value.Name, Email: value.Email, Hits: value.Hits, MaxTPS: round(value.MaxTPS, 1), + Classes: map[string]int64{ + auditdomain.DegradeClassBurst: value.Burst, + auditdomain.DegradeClassSoft: value.Soft, + auditdomain.DegradeClassHard: value.Hard, + }, + Nodes: value.Nodes, Last: value.Last, Enabled: value.Enabled, Found: value.Found, BFS: value.BuildBotFlagSource, + }) + } + nodes := make([]DegradeNode, 0, len(data.Nodes)) + for _, value := range data.Nodes { + nodes = append(nodes, DegradeNode{Name: value.Name, Hits: value.Hits, Accounts: value.Accounts, MaxTPS: round(value.MaxTPS, 1)}) + } + events := make([]DegradeEventView, 0, len(data.Events)) + for _, value := range data.Events { + nodeName := value.EgressNodeName if nodeName == "" { nodeName = "?" } - classified = append(classified, DegradeEventView{ - ID: event.ID, RequestID: event.RequestID, AccountID: event.AccountID, AccountName: event.AccountName, - NodeName: nodeName, OutputTokens: event.OutputTokens, TPS: math.Round(tps*100) / 100, Class: class, - CreatedAt: event.CreatedAt, Model: event.Model, - }) - if event.AccountID == nil || *event.AccountID == 0 { - continue - } - id := *event.AccountID - rec := accounts[id] - if rec == nil { - rec = &accAgg{classes: map[string]int{}, nodes: map[string]struct{}{}} - accounts[id] = rec - } - rec.hits++ - if tps > rec.maxTPS { - rec.maxTPS = tps - } - rec.classes[class]++ - rec.nodes[nodeName] = struct{}{} - if event.CreatedAt.After(rec.last) { - rec.last = event.CreatedAt - rec.name = event.AccountName - } - if rec.name == "" { - rec.name = event.AccountName - } - if event.Email != "" { - rec.email = event.Email - } - if event.Enabled != nil { - rec.enabled = *event.Enabled - rec.found = true - } - if event.BuildBotFlagSource > rec.bfs { - rec.bfs = event.BuildBotFlagSource - } - nd := nodes[nodeName] - if nd == nil { - nd = &nodeAgg{accounts: map[uint64]struct{}{}} - nodes[nodeName] = nd - } - nd.hits++ - nd.accounts[id] = struct{}{} - if tps > nd.maxTPS { - nd.maxTPS = tps - } - } - - accountViews := make([]DegradeAccount, 0, len(accounts)) - enabled, disabled := 0, 0 - for id, rec := range accounts { - if rec.found && rec.enabled { - enabled++ - } else { - disabled++ - } - nodeNames := make([]string, 0, len(rec.nodes)) - for name := range rec.nodes { - nodeNames = append(nodeNames, name) - } - sort.Strings(nodeNames) - email := rec.email - if email == "" { - email = rec.name - } - accountViews = append(accountViews, DegradeAccount{ - ID: id, Name: rec.name, Email: email, Hits: rec.hits, MaxTPS: math.Round(rec.maxTPS*10) / 10, - Classes: rec.classes, Nodes: nodeNames, Last: rec.last, Enabled: rec.found && rec.enabled, BFS: rec.bfs, Found: rec.found, + events = append(events, DegradeEventView{ + ID: value.ID, RequestID: value.RequestID, AccountID: value.AccountID, AccountName: value.AccountName, + NodeName: nodeName, OutputTokens: value.OutputTokens, TPS: round(value.TPS, 2), Class: value.Class, + CreatedAt: value.CreatedAt, Model: value.Model, }) } - sort.Slice(accountViews, func(i, j int) bool { - if accountViews[i].Hits != accountViews[j].Hits { - return accountViews[i].Hits > accountViews[j].Hits + series := make([]DegradeBucket, len(bucketSpecs)) + for index, spec := range bucketSpecs { + series[index].Label = spec.Label + } + for _, value := range data.Buckets { + if value.Index >= 0 && value.Index < len(series) { + series[value.Index].Count = value.Count + series[value.Index].Severe = value.Severe } - return accountViews[i].MaxTPS > accountViews[j].MaxTPS - }) - - nodeViews := make([]DegradeNode, 0, len(nodes)) - for name, rec := range nodes { - nodeViews = append(nodeViews, DegradeNode{Name: name, Hits: rec.hits, Accounts: len(rec.accounts), MaxTPS: math.Round(rec.maxTPS*10) / 10}) } - sort.Slice(nodeViews, func(i, j int) bool { return nodeViews[i].Hits > nodeViews[j].Hits }) - - recent := classified - if len(recent) > degradeRecentEventCap { - recent = recent[:degradeRecentEventCap] - } - return DegradeSummary{ Window: window, GeneratedAt: now, Thresholds: thresholds, Totals: DegradeTotals{ - Hits: len(classified), Accounts: len(accounts), StillEnabled: enabled, Disabled: disabled, - Hard: classCounts[auditdomain.DegradeClassHard], Soft: classCounts[auditdomain.DegradeClassSoft], - Burst: classCounts[auditdomain.DegradeClassBurst], MaxTPS: maxTPS, + Hits: data.Totals.Hits, Accounts: data.Totals.Accounts, StillEnabled: data.Totals.StillEnabled, + Disabled: data.Totals.Disabled, Deleted: data.Totals.Deleted, Hard: data.Totals.Hard, + Soft: data.Totals.Soft, Burst: data.Totals.Burst, MaxTPS: round(data.Totals.MaxTPS, 2), }, - Series: bucketDegradeSeries(classified, window, now), - Nodes: nodeViews, Accounts: accountViews, Events: recent, + Series: series, Nodes: nodes, Accounts: accounts, + AccountPage: DegradeAccountPage{ + Page: data.AccountOffset/filter.PageSize + 1, PageSize: filter.PageSize, Total: data.AccountTotal, + HasMore: int64(data.AccountOffset+filter.PageSize) < data.AccountTotal, + }, + Events: events, } } -func bucketDegradeSeries(events []DegradeEventView, window string, now time.Time) []DegradeBucket { - var step time.Duration - var start time.Time - var label func(time.Time) string +func degradeBucketSpecs(window string, start, end time.Time) []degradeBucketSpec { + step := 5 * time.Minute + label := func(value time.Time) string { return value.Format("15:04") } switch window { case degradeWindow7d: step = 2 * time.Hour - start = now.Add(-7 * 24 * time.Hour) - label = func(t time.Time) string { return t.Format("01-02 15:00") } + label = func(value time.Time) string { return value.Format("01-02 15:00") } case degradeWindow24h: step = time.Hour - start = now.Add(-24 * time.Hour) - label = func(t time.Time) string { return t.Format("15:00") } + label = func(value time.Time) string { return value.Format("15:00") } case degradeWindow6h: step = 20 * time.Minute - start = now.Add(-6 * time.Hour) - label = func(t time.Time) string { return t.Format("15:04") } - default: - step = 5 * time.Minute - start = now.Add(-time.Hour) - label = func(t time.Time) string { return t.Format("15:04") } } - var buckets []time.Time - for cursor := start; cursor.Before(now); cursor = cursor.Add(step) { - buckets = append(buckets, cursor) - } - if len(buckets) == 0 { - return nil - } - counts := make([]int, len(buckets)) - severe := make([]int, len(buckets)) - stepSeconds := step.Seconds() - for _, event := range events { - idx := int(event.CreatedAt.Sub(start).Seconds() / stepSeconds) - if idx < 0 || idx >= len(counts) { - continue - } - counts[idx]++ - if event.Class == auditdomain.DegradeClassHard || event.Class == auditdomain.DegradeClassBurst { - severe[idx]++ + var result []degradeBucketSpec + for cursor := start; cursor.Before(end); cursor = cursor.Add(step) { + bucketEnd := cursor.Add(step) + if bucketEnd.After(end) { + bucketEnd = end } + result = append(result, degradeBucketSpec{ + Range: repository.DegradeBucketRange{Start: cursor, End: bucketEnd}, + Label: label(cursor), + }) } - out := make([]DegradeBucket, len(buckets)) - for i, bucket := range buckets { - out[i] = DegradeBucket{Label: label(bucket), Count: counts[i], Severe: severe[i]} - } - return out + return result +} + +func round(value float64, places int) float64 { + factor := math.Pow10(places) + return math.Round(value*factor) / factor } diff --git a/backend/internal/application/audit/degrade_test.go b/backend/internal/application/audit/degrade_test.go index 24d40fe7..4705aa37 100644 --- a/backend/internal/application/audit/degrade_test.go +++ b/backend/internal/application/audit/degrade_test.go @@ -2,11 +2,13 @@ package audit import ( "context" + "fmt" "log/slog" "path/filepath" "testing" "time" + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" auditdomain "github.com/chenyme/grok2api/backend/internal/domain/audit" "github.com/chenyme/grok2api/backend/internal/infra/persistence/relational" ) @@ -35,7 +37,7 @@ func TestDegradeSummaryClassifiesStreamingAnomalies(t *testing.T) { } service := NewService(repo, slog.Default(), 8, 4, time.Second) service.now = func() time.Time { return now } - summary, err := service.DegradeSummary(ctx, "24h", DegradeThresholds{SoftTPS: 500, HardTPS: 1000}) + summary, err := service.DegradeSummary(ctx, "24h", DegradeThresholds{SoftTPS: 500, HardTPS: 1000}, DegradeAccountFilter{}) if err != nil { t.Fatal(err) } @@ -45,6 +47,158 @@ func TestDegradeSummaryClassifiesStreamingAnomalies(t *testing.T) { if len(summary.Accounts) != 1 || summary.Accounts[0].ID != 7 || summary.Accounts[0].Hits != 1 { t.Fatalf("accounts = %#v", summary.Accounts) } + if summary.Totals.Deleted != 1 || summary.Totals.Disabled != 0 || summary.Accounts[0].Found { + t.Fatalf("deleted account state = totals %#v, account %#v", summary.Totals, summary.Accounts[0]) + } +} + +func TestDegradeSummaryDoesNotDropOlderAnomalyAfterTwentyThousandNewerRows(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-large.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + repo := relational.NewAuditRepository(database) + now := time.Now().UTC() + first := int64(100) + accountID := uint64(7) + records := make([]auditdomain.Record, 0, 20_001) + records = append(records, auditdomain.Record{ + RequestID: "older-real-anomaly", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", + AccountID: &accountID, StatusCode: 200, Streaming: true, OutputTokens: 2_000, + FirstTokenMS: &first, DurationMS: 1_100, CreatedAt: now.Add(-2 * time.Hour), + }) + for index := 0; index < 20_000; index++ { + records = append(records, auditdomain.Record{ + RequestID: fmt.Sprintf("newer-healthy-%05d", index), ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", + AccountID: &accountID, StatusCode: 200, Streaming: true, OutputTokens: 100, + FirstTokenMS: &first, DurationMS: 1_100, CreatedAt: now.Add(-time.Minute - time.Duration(index)*time.Millisecond), + }) + } + if err := repo.CreateBatch(ctx, records); err != nil { + t.Fatal(err) + } + service := NewService(repo, slog.Default(), 8, 4, time.Second) + service.now = func() time.Time { return now } + summary, err := service.DegradeSummary(ctx, "24h", DegradeThresholds{SoftTPS: 500, HardTPS: 1000}, DegradeAccountFilter{}) + if err != nil { + t.Fatal(err) + } + if summary.Totals.Hits != 1 || summary.Totals.Hard != 1 || len(summary.Events) != 1 || summary.Events[0].RequestID != "older-real-anomaly" { + t.Fatalf("summary silently dropped older anomaly: totals=%#v events=%#v", summary.Totals, summary.Events) + } +} + +func TestDegradeSummaryMatchesFailClosedShortWindowPolicy(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-policy.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + repo := relational.NewAuditRepository(database) + now := time.Now().UTC() + first := int64(50) + accountID := uint64(9) + if err := repo.Create(ctx, auditdomain.Record{ + RequestID: "short-window", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", + AccountID: &accountID, StatusCode: 200, Streaming: true, OutputTokens: 200, + FirstTokenMS: &first, DurationMS: 250, CreatedAt: now.Add(-time.Minute), + }); err != nil { + t.Fatal(err) + } + service := NewService(repo, slog.Default(), 8, 4, time.Second) + service.now = func() time.Time { return now } + open, err := service.DegradeSummary(ctx, "1h", DegradeThresholds{SoftTPS: 500, HardTPS: 1000, FailClosed: false}, DegradeAccountFilter{}) + if err != nil { + t.Fatal(err) + } + closed, err := service.DegradeSummary(ctx, "1h", DegradeThresholds{SoftTPS: 500, HardTPS: 1000, FailClosed: true}, DegradeAccountFilter{}) + if err != nil { + t.Fatal(err) + } + if open.Totals.Hard != 1 || open.Totals.Burst != 0 || closed.Totals.Hard != 0 || closed.Totals.Burst != 1 { + t.Fatalf("open=%#v closed=%#v", open.Totals, closed.Totals) + } +} + +func TestDegradeSummaryPaginatesAccountsInRepository(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-page.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + repo := relational.NewAuditRepository(database) + now := time.Now().UTC() + first := int64(100) + for id := uint64(1); id <= 3; id++ { + accountID := id + if err := repo.Create(ctx, auditdomain.Record{ + RequestID: fmt.Sprintf("page-account-%d", id), ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", + AccountID: &accountID, StatusCode: 200, Streaming: true, OutputTokens: 2_000, + FirstTokenMS: &first, DurationMS: 1_100, CreatedAt: now.Add(-time.Duration(id) * time.Minute), + }); err != nil { + t.Fatal(err) + } + } + service := NewService(repo, slog.Default(), 8, 4, time.Second) + service.now = func() time.Time { return now } + summary, err := service.DegradeSummary(ctx, "1h", DegradeThresholds{}, DegradeAccountFilter{Page: 2, PageSize: 2}) + if err != nil { + t.Fatal(err) + } + if summary.AccountPage.Total != 3 || summary.AccountPage.HasMore || len(summary.Accounts) != 1 { + t.Fatalf("page=%#v accounts=%#v", summary.AccountPage, summary.Accounts) + } +} + +func TestDegradeSummarySearchesEveryAccountIdentityField(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "degrade-search.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accountValue, _, err := relational.NewAccountRepository(database).UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderBuild, AuthType: accountdomain.AuthTypeOAuth, + Name: "Searchable Build Account", SourceKey: "searchable-build", + EncryptedAccessToken: "encrypted-token", AuthStatus: accountdomain.AuthStatusActive, Enabled: true, + }) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + first := int64(100) + if err := relational.NewAuditRepository(database).Create(ctx, auditdomain.Record{ + RequestID: "search-by-name", ClientKeyID: 1, ModelRouteID: 1, Provider: "grok_build", + AccountID: &accountValue.ID, AccountName: "stale audit name", StatusCode: 200, Streaming: true, + OutputTokens: 2_000, FirstTokenMS: &first, DurationMS: 1_100, CreatedAt: now.Add(-time.Minute), + }); err != nil { + t.Fatal(err) + } + service := NewService(relational.NewAuditRepository(database), slog.Default(), 8, 4, time.Second) + service.now = func() time.Time { return now } + summary, err := service.DegradeSummary(ctx, "1h", DegradeThresholds{}, DegradeAccountFilter{Search: "searchable build"}) + if err != nil { + t.Fatal(err) + } + if summary.AccountPage.Total != 1 || len(summary.Accounts) != 1 || summary.Accounts[0].ID != accountValue.ID { + t.Fatalf("account search result = %#v", summary) + } } func TestDegradeSummaryRejectsUnknownWindow(t *testing.T) { @@ -58,7 +212,7 @@ func TestDegradeSummaryRejectsUnknownWindow(t *testing.T) { t.Fatal(err) } service := NewService(relational.NewAuditRepository(database), slog.Default(), 8, 4, time.Second) - if _, err := service.DegradeSummary(ctx, "3h", DegradeThresholds{}); err != ErrInvalidPeriod { + if _, err := service.DegradeSummary(ctx, "3h", DegradeThresholds{}, DegradeAccountFilter{}); err != ErrInvalidPeriod { t.Fatalf("error = %v", err) } } diff --git a/backend/internal/domain/audit/degrade.go b/backend/internal/domain/audit/degrade.go index f1b57113..66af0667 100644 --- a/backend/internal/domain/audit/degrade.go +++ b/backend/internal/domain/audit/degrade.go @@ -14,16 +14,16 @@ const ( ) // ClassifyOutputSpeed matches the quality-guard panel formula: -// output tokens / (durationMs - firstTokenMs). Short generation windows with -// a soft-or-higher rate are buffered_burst; otherwise the hard and soft -// thresholds apply in that order. -func ClassifyOutputSpeed(outputTokens, firstTokenMS, durationMS int64, softTPS, hardTPS float64, minGenMS int64) (class string, tps float64, genMS int64) { +// output tokens / (durationMs - firstTokenMs). In fail-closed mode, short +// generation windows with a soft-or-higher rate are buffered_burst; otherwise +// the hard and soft thresholds apply in that order. +func ClassifyOutputSpeed(outputTokens, firstTokenMS, durationMS int64, softTPS, hardTPS float64, minGenMS int64, failClosed bool) (class string, tps float64, genMS int64) { genMS = durationMS - firstTokenMS if genMS <= 0 || outputTokens <= 0 { return "", 0, genMS } tps = float64(outputTokens) * 1000 / float64(genMS) - if minGenMS > 0 && genMS < minGenMS && tps >= softTPS { + if failClosed && minGenMS > 0 && genMS < minGenMS && tps >= softTPS { return DegradeClassBurst, tps, genMS } if tps >= hardTPS { diff --git a/backend/internal/domain/audit/degrade_test.go b/backend/internal/domain/audit/degrade_test.go index 24ac8c81..476ce742 100644 --- a/backend/internal/domain/audit/degrade_test.go +++ b/backend/internal/domain/audit/degrade_test.go @@ -8,17 +8,19 @@ func TestClassifyOutputSpeed(t *testing.T) { output, first, duration int64 soft, hard float64 minGen int64 + failClosed bool wantClass string }{ {name: "hard", output: 2000, first: 200, duration: 1200, soft: 500, hard: 1000, minGen: 1000, wantClass: DegradeClassHard}, {name: "soft", output: 600, first: 200, duration: 1400, soft: 500, hard: 1000, minGen: 1000, wantClass: DegradeClassSoft}, - {name: "burst short window", output: 200, first: 50, duration: 250, soft: 500, hard: 1000, minGen: 1000, wantClass: DegradeClassBurst}, + {name: "short window follows hard threshold by default", output: 200, first: 50, duration: 250, soft: 500, hard: 1000, minGen: 1000, wantClass: DegradeClassHard}, + {name: "burst short window when fail closed", output: 200, first: 50, duration: 250, soft: 500, hard: 1000, minGen: 1000, failClosed: true, wantClass: DegradeClassBurst}, {name: "healthy", output: 100, first: 200, duration: 2200, soft: 500, hard: 1000, minGen: 1000, wantClass: ""}, {name: "zero generation", output: 100, first: 500, duration: 500, soft: 500, hard: 1000, minGen: 1000, wantClass: ""}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - class, _, _ := ClassifyOutputSpeed(test.output, test.first, test.duration, test.soft, test.hard, test.minGen) + class, _, _ := ClassifyOutputSpeed(test.output, test.first, test.duration, test.soft, test.hard, test.minGen, test.failClosed) if class != test.wantClass { t.Fatalf("class = %q, want %q", class, test.wantClass) } diff --git a/backend/internal/infra/persistence/relational/audit_repository.go b/backend/internal/infra/persistence/relational/audit_repository.go index 6b2e8cde..d0e0d314 100644 --- a/backend/internal/infra/persistence/relational/audit_repository.go +++ b/backend/internal/infra/persistence/relational/audit_repository.go @@ -8,6 +8,7 @@ import ( "fmt" "math" "sort" + "strconv" "strings" "time" "unicode/utf8" @@ -683,66 +684,307 @@ func (r *AuditRepository) Summarize(ctx context.Context, input repository.AuditS return result, nil } -const degradeEventScanLimit = 20_000 - -type degradeEventRow struct { - ID uint64 `gorm:"column:id"` - RequestID string `gorm:"column:request_id"` - AccountID *uint64 `gorm:"column:account_id"` - AccountName string `gorm:"column:account_name"` - Email string `gorm:"column:email"` - Enabled *bool `gorm:"column:enabled"` - BuildBotFlagSource int `gorm:"column:build_bot_flag_source"` - EgressNodeID *uint64 `gorm:"column:egress_node_id"` - EgressNodeName string `gorm:"column:egress_node_name"` - OutputTokens int64 `gorm:"column:output_tokens"` - FirstTokenMS int64 `gorm:"column:first_token_ms"` - DurationMS int64 `gorm:"column:duration_ms"` - CreatedAt time.Time `gorm:"column:created_at"` - Model string `gorm:"column:model_upstream_model"` +type degradeTotalsRow struct { + Hits int64 `gorm:"column:hits"` + Accounts int64 `gorm:"column:accounts"` + StillEnabled int64 `gorm:"column:still_enabled"` + Disabled int64 `gorm:"column:disabled"` + Deleted int64 `gorm:"column:deleted"` + Hard int64 `gorm:"column:hard"` + Soft int64 `gorm:"column:soft"` + Burst int64 `gorm:"column:burst"` + MaxTPS float64 `gorm:"column:max_tps"` } -func (r *AuditRepository) ListDegradeEvents(ctx context.Context, input repository.DegradeEventQuery) ([]repository.DegradeEvent, error) { - limit := input.Limit - if limit <= 0 || limit > degradeEventScanLimit { - limit = degradeEventScanLimit +type degradeAccountRow struct { + ID uint64 `gorm:"column:id"` + Name string `gorm:"column:name"` + Email string `gorm:"column:email"` + Hits int64 `gorm:"column:hits"` + MaxTPS float64 `gorm:"column:max_tps"` + Burst int64 `gorm:"column:burst"` + Soft int64 `gorm:"column:soft"` + Hard int64 `gorm:"column:hard"` + Last degradeTimestamp `gorm:"column:last_seen"` + Enabled bool `gorm:"column:enabled"` + Found bool `gorm:"column:found"` + BuildBotFlagSource int `gorm:"column:build_bot_flag_source"` +} + +type degradeTimestamp time.Time + +func (value *degradeTimestamp) Scan(input any) error { + parsed, err := parseDegradeTimestamp(input) + if err != nil { + return err } - minOut := input.MinOutputTokens - if minOut <= 0 { - minOut = audit.DefaultDegradeMinOutput + *value = degradeTimestamp(parsed) + return nil +} + +func parseDegradeTimestamp(input any) (time.Time, error) { + if parsed, ok := input.(time.Time); ok { + return parsed, nil } - var rows []degradeEventRow - query := r.db.db.WithContext(ctx).Table("request_audits AS a"). - Select("a.id, a.request_id, a.account_id, a.account_name, a.egress_node_id, a.egress_node_name, a.output_tokens, a.first_token_ms, a.duration_ms, a.created_at, a.model_upstream_model, p.email, p.enabled, COALESCE(c.build_bot_flag_source, 0) AS build_bot_flag_source"). - Joins("LEFT JOIN provider_accounts p ON p.id = a.account_id"). - Joins("LEFT JOIN account_credentials c ON c.account_id = a.account_id"). - Where("a.provider = ?", "grok_build"). - Where("a.streaming = ?", true). - Where(auditSuccessPredicate). - Where("a.output_tokens >= ?", minOut). - Where("a.first_token_ms IS NOT NULL"). - Where("a.duration_ms > a.first_token_ms"). - Where("a.request_id NOT LIKE ?", "quality_%") + var raw string + switch value := input.(type) { + case string: + raw = value + case []byte: + raw = string(value) + case nil: + return time.Time{}, nil + default: + return time.Time{}, fmt.Errorf("unsupported degrade timestamp type %T", input) + } + for _, layout := range []string{ + time.RFC3339Nano, + "2006-01-02 15:04:05.999999999-07:00", + "2006-01-02 15:04:05.999999999Z07:00", + "2006-01-02 15:04:05.999999999", + "2006-01-02 15:04:05-07:00", + "2006-01-02 15:04:05", + } { + parsed, err := time.Parse(layout, raw) + if err == nil { + return parsed, nil + } + } + return time.Time{}, fmt.Errorf("invalid degrade timestamp") +} + +type degradeNodeRow struct { + Name string `gorm:"column:name"` + Hits int64 `gorm:"column:hits"` + Accounts int64 `gorm:"column:accounts"` + MaxTPS float64 `gorm:"column:max_tps"` +} + +type degradeBucketRow struct { + Index int `gorm:"column:bucket_index"` + Count int64 `gorm:"column:count"` + Severe int64 `gorm:"column:severe"` +} + +type degradeAccountNodeRow struct { + AccountID uint64 `gorm:"column:account_id"` + Name string `gorm:"column:name"` +} + +type degradeEventRow struct { + ID uint64 `gorm:"column:id"` + RequestID string `gorm:"column:request_id"` + AccountID *uint64 `gorm:"column:account_id"` + AccountName string `gorm:"column:account_name"` + EgressNodeID *uint64 `gorm:"column:egress_node_id"` + EgressNodeName string `gorm:"column:egress_node_name"` + OutputTokens int64 `gorm:"column:output_tokens"` + TPS float64 `gorm:"column:tps"` + Class string `gorm:"column:degrade_class"` + CreatedAt time.Time `gorm:"column:created_at"` + Model string `gorm:"column:model_upstream_model"` +} + +func (r *AuditRepository) SummarizeDegrade(ctx context.Context, input repository.DegradeSummaryQuery) (repository.DegradeSummaryResult, error) { + if input.AccountLimit <= 0 || input.AccountLimit > 100 { + input.AccountLimit = 50 + } + if input.AccountOffset < 0 { + input.AccountOffset = 0 + } + if input.RecentLimit <= 0 || input.RecentLimit > 200 { + input.RecentLimit = 80 + } + var result repository.DegradeSummaryResult + err := r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + classified := r.degradeClassifiedQuery(tx, input) + var totals degradeTotalsRow + if err := tx.Table("(?) AS d", classified). + Select(`COUNT(*) AS hits, + COUNT(DISTINCT d.account_id) AS accounts, + COUNT(DISTINCT CASE WHEN p.id IS NOT NULL AND p.enabled = TRUE THEN d.account_id END) AS still_enabled, + COUNT(DISTINCT CASE WHEN p.id IS NOT NULL AND p.enabled = FALSE THEN d.account_id END) AS disabled, + COUNT(DISTINCT CASE WHEN p.id IS NULL THEN d.account_id END) AS deleted, + COALESCE(SUM(CASE WHEN d.degrade_class = 'hard_tps' THEN 1 ELSE 0 END), 0) AS hard, + COALESCE(SUM(CASE WHEN d.degrade_class = 'soft_tps' THEN 1 ELSE 0 END), 0) AS soft, + COALESCE(SUM(CASE WHEN d.degrade_class = 'buffered_burst' THEN 1 ELSE 0 END), 0) AS burst, + COALESCE(MAX(d.tps), 0) AS max_tps`). + Joins("LEFT JOIN provider_accounts p ON p.id = d.account_id"). + Scan(&totals).Error; err != nil { + return err + } + result.Totals = repository.DegradeTotals{ + Hits: totals.Hits, Accounts: totals.Accounts, StillEnabled: totals.StillEnabled, + Disabled: totals.Disabled, Deleted: totals.Deleted, Hard: totals.Hard, Soft: totals.Soft, + Burst: totals.Burst, MaxTPS: totals.MaxTPS, + } + + accountQuery := r.degradeAccountAggregate(tx, classified, input) + if err := tx.Table("(?) AS filtered_accounts", accountQuery).Count(&result.AccountTotal).Error; err != nil { + return err + } + accountOffset := input.AccountOffset + if result.AccountTotal > 0 && int64(accountOffset) >= result.AccountTotal { + accountOffset = int((result.AccountTotal-1)/int64(input.AccountLimit)) * input.AccountLimit + } + result.AccountOffset = accountOffset + var accountRows []degradeAccountRow + if err := accountQuery.Order("hits DESC, max_tps DESC, id ASC"). + Offset(accountOffset).Limit(input.AccountLimit).Scan(&accountRows).Error; err != nil { + return err + } + accountIDs := make([]uint64, 0, len(accountRows)) + accountsByID := make(map[uint64]*repository.DegradeAccount, len(accountRows)) + result.Accounts = make([]repository.DegradeAccount, 0, len(accountRows)) + for _, row := range accountRows { + result.Accounts = append(result.Accounts, repository.DegradeAccount{ + ID: row.ID, Name: row.Name, Email: row.Email, Hits: row.Hits, MaxTPS: row.MaxTPS, + Burst: row.Burst, Soft: row.Soft, Hard: row.Hard, Last: time.Time(row.Last), Enabled: row.Enabled, + Found: row.Found, BuildBotFlagSource: row.BuildBotFlagSource, + }) + accountIDs = append(accountIDs, row.ID) + accountsByID[row.ID] = &result.Accounts[len(result.Accounts)-1] + } + if len(accountIDs) > 0 { + var nodeRows []degradeAccountNodeRow + if err := tx.Table("(?) AS d", classified). + Select("d.account_id, COALESCE(NULLIF(d.egress_node_name, ''), '?') AS name"). + Where("d.account_id IN ?", accountIDs). + Group("d.account_id, COALESCE(NULLIF(d.egress_node_name, ''), '?')"). + Order("d.account_id ASC, name ASC").Scan(&nodeRows).Error; err != nil { + return err + } + for _, row := range nodeRows { + if account := accountsByID[row.AccountID]; account != nil { + account.Nodes = append(account.Nodes, row.Name) + } + } + } + + var nodeRows []degradeNodeRow + if err := tx.Table("(?) AS d", classified). + Select("COALESCE(NULLIF(d.egress_node_name, ''), '?') AS name, COUNT(*) AS hits, COUNT(DISTINCT d.account_id) AS accounts, COALESCE(MAX(d.tps), 0) AS max_tps"). + Group("COALESCE(NULLIF(d.egress_node_name, ''), '?')").Order("hits DESC, name ASC").Scan(&nodeRows).Error; err != nil { + return err + } + result.Nodes = make([]repository.DegradeNode, 0, len(nodeRows)) + for _, row := range nodeRows { + result.Nodes = append(result.Nodes, repository.DegradeNode{Name: row.Name, Hits: row.Hits, Accounts: row.Accounts, MaxTPS: row.MaxTPS}) + } + + if len(input.Buckets) > 0 { + caseSQL, caseArgs := degradeBucketCase(input.Buckets) + bucketed := tx.Table("(?) AS d", classified).Select(caseSQL+" AS bucket_index, d.degrade_class", caseArgs...) + var bucketRows []degradeBucketRow + if err := tx.Table("(?) AS b", bucketed). + Select("b.bucket_index, COUNT(*) AS count, COALESCE(SUM(CASE WHEN b.degrade_class IN ('hard_tps', 'buffered_burst') THEN 1 ELSE 0 END), 0) AS severe"). + Where("b.bucket_index >= 0").Group("b.bucket_index").Order("b.bucket_index ASC").Scan(&bucketRows).Error; err != nil { + return err + } + result.Buckets = make([]repository.DegradeBucket, 0, len(bucketRows)) + for _, row := range bucketRows { + result.Buckets = append(result.Buckets, repository.DegradeBucket{Index: row.Index, Count: row.Count, Severe: row.Severe}) + } + } + + var eventRows []degradeEventRow + if err := tx.Table("(?) AS d", classified). + Select("d.id, d.request_id, d.account_id, d.account_name, d.egress_node_id, d.egress_node_name, d.output_tokens, d.tps, d.degrade_class, d.created_at, d.model_upstream_model"). + Order("d.created_at DESC, d.id DESC").Limit(input.RecentLimit).Scan(&eventRows).Error; err != nil { + return err + } + result.Events = make([]repository.DegradeEvent, 0, len(eventRows)) + for _, row := range eventRows { + result.Events = append(result.Events, repository.DegradeEvent{ + ID: row.ID, RequestID: row.RequestID, AccountID: row.AccountID, AccountName: row.AccountName, + EgressNodeID: row.EgressNodeID, EgressNodeName: row.EgressNodeName, OutputTokens: row.OutputTokens, + TPS: row.TPS, Class: row.Class, CreatedAt: row.CreatedAt, Model: row.Model, + }) + } + return nil + }) + return result, err +} + +func (r *AuditRepository) degradeClassifiedQuery(tx *gorm.DB, input repository.DegradeSummaryQuery) *gorm.DB { + castType := "REAL" + if r.db.dialect == "postgres" { + castType = "DOUBLE PRECISION" + } + generationExpression := "(a.duration_ms - a.first_token_ms)" + // NULLIF keeps PostgreSQL safe even if its planner evaluates the throughput + // expression before the duration guard in the WHERE clause. + tpsExpression := fmt.Sprintf("(CAST(a.output_tokens AS %s) * 1000.0 / NULLIF(%s, 0))", castType, generationExpression) + classExpression := fmt.Sprintf("CASE WHEN ? AND %s < ? THEN ? WHEN %s >= ? THEN ? ELSE ? END", generationExpression, tpsExpression) + query := tx.Table("request_audits AS a"). + Select("a.id, a.request_id, a.account_id, a.account_name, a.egress_node_id, a.egress_node_name, a.output_tokens, a.created_at, a.model_upstream_model, "+tpsExpression+" AS tps, "+classExpression+" AS degrade_class", + input.FailClosed, input.MinGenerationMS, audit.DegradeClassBurst, input.HardTPS, audit.DegradeClassHard, audit.DegradeClassSoft). + Where("a.provider = ?", "grok_build").Where("a.streaming = ?", true). + Where(auditSuccessPredicate).Where("a.output_tokens >= ?", input.MinOutputTokens). + Where("a.first_token_ms IS NOT NULL").Where("a.duration_ms > a.first_token_ms"). + Where("a.request_id NOT LIKE ?", "quality_%").Where(tpsExpression+" >= ?", input.SoftTPS) if !input.Start.IsZero() { query = query.Where("a.created_at >= ?", input.Start) } if !input.End.IsZero() { query = query.Where("a.created_at < ?", input.End) } - if err := query.Order("a.created_at DESC").Limit(limit).Scan(&rows).Error; err != nil { - return nil, err + return query +} + +func (r *AuditRepository) degradeAccountAggregate(tx *gorm.DB, classified *gorm.DB, input repository.DegradeSummaryQuery) *gorm.DB { + query := tx.Table("(?) AS d", classified). + Select(`d.account_id AS id, + COALESCE(NULLIF(p.name, ''), MAX(d.account_name), '') AS name, + COALESCE(p.email, '') AS email, + COUNT(*) AS hits, + COALESCE(MAX(d.tps), 0) AS max_tps, + COALESCE(SUM(CASE WHEN d.degrade_class = 'buffered_burst' THEN 1 ELSE 0 END), 0) AS burst, + COALESCE(SUM(CASE WHEN d.degrade_class = 'soft_tps' THEN 1 ELSE 0 END), 0) AS soft, + COALESCE(SUM(CASE WHEN d.degrade_class = 'hard_tps' THEN 1 ELSE 0 END), 0) AS hard, + MAX(d.created_at) AS last_seen, + COALESCE(p.enabled, FALSE) AS enabled, + CASE WHEN p.id IS NULL THEN FALSE ELSE TRUE END AS found, + COALESCE(c.build_bot_flag_source, 0) AS build_bot_flag_source`). + Joins("LEFT JOIN provider_accounts p ON p.id = d.account_id"). + Joins("LEFT JOIN account_credentials c ON c.account_id = d.account_id"). + Where("d.account_id IS NOT NULL"). + Group("d.account_id, p.id, p.name, p.email, p.enabled, c.build_bot_flag_source") + if search := strings.TrimSpace(input.AccountSearch); search != "" { + pattern := "%" + strings.ToLower(search) + "%" + query = query.Where( + "LOWER(COALESCE(p.email, '')) LIKE ? OR LOWER(COALESCE(p.name, '')) LIKE ? OR LOWER(COALESCE(d.account_name, '')) LIKE ? OR CAST(d.account_id AS TEXT) LIKE ?", + pattern, pattern, pattern, pattern, + ) } - out := make([]repository.DegradeEvent, 0, len(rows)) - for _, row := range rows { - out = append(out, repository.DegradeEvent{ - ID: row.ID, RequestID: row.RequestID, AccountID: row.AccountID, AccountName: row.AccountName, - Email: row.Email, Enabled: row.Enabled, BuildBotFlagSource: row.BuildBotFlagSource, - EgressNodeID: row.EgressNodeID, EgressNodeName: row.EgressNodeName, - OutputTokens: row.OutputTokens, FirstTokenMS: row.FirstTokenMS, DurationMS: row.DurationMS, - CreatedAt: row.CreatedAt, Model: row.Model, - }) + switch input.AccountStatus { + case "enabled": + query = query.Where("p.id IS NOT NULL AND p.enabled = TRUE") + case "disabled": + query = query.Where("p.id IS NOT NULL AND p.enabled = FALSE") + case "deleted": + query = query.Where("p.id IS NULL") } - return out, nil + if input.MinHits > 1 { + query = query.Having("COUNT(*) >= ?", input.MinHits) + } + if input.AccountClass != "" { + query = query.Having("SUM(CASE WHEN d.degrade_class = ? THEN 1 ELSE 0 END) > 0", input.AccountClass) + } + return query +} + +func degradeBucketCase(buckets []repository.DegradeBucketRange) (string, []any) { + var builder strings.Builder + args := make([]any, 0, len(buckets)*2) + builder.WriteString("CASE") + for index, bucket := range buckets { + builder.WriteString(" WHEN d.created_at >= ? AND d.created_at < ? THEN ") + builder.WriteString(strconv.Itoa(index)) + args = append(args, bucket.Start, bucket.End) + } + builder.WriteString(" ELSE -1 END") + return builder.String(), args } func applyAuditQuery(query *gorm.DB, search string, start, end time.Time, filter repository.AuditListFilter) *gorm.DB { diff --git a/backend/internal/infra/persistence/relational/audit_repository_test.go b/backend/internal/infra/persistence/relational/audit_repository_test.go index b53c0f1a..5525b12b 100644 --- a/backend/internal/infra/persistence/relational/audit_repository_test.go +++ b/backend/internal/infra/persistence/relational/audit_repository_test.go @@ -538,4 +538,15 @@ func TestAuditRepositoryStreamFailureKeepsHTTPStatusAndFiltersAsOther(t *testing } } +func TestDegradeTimestampScansPostgresTimeValue(t *testing.T) { + expected := time.Date(2026, time.August, 14, 8, 30, 0, 123, time.UTC) + var value degradeTimestamp + if err := value.Scan(expected); err != nil { + t.Fatal(err) + } + if actual := time.Time(value); !actual.Equal(expected) { + t.Fatalf("scanned timestamp = %s, want %s", actual, expected) + } +} + func uint64Pointer(value uint64) *uint64 { return &value } diff --git a/backend/internal/infra/persistence/relational/schema.go b/backend/internal/infra/persistence/relational/schema.go index dab56f5a..c9d79249 100644 --- a/backend/internal/infra/persistence/relational/schema.go +++ b/backend/internal/infra/persistence/relational/schema.go @@ -89,6 +89,7 @@ var schemaIndexes = []string{ "CREATE INDEX IF NOT EXISTS idx_audits_account_created_id ON request_audits(account_id, created_at DESC, id DESC)", "CREATE INDEX IF NOT EXISTS idx_audits_status_created_id ON request_audits(status_code, created_at DESC, id DESC)", "CREATE INDEX IF NOT EXISTS idx_audits_streaming_created_id ON request_audits(streaming, created_at DESC, id DESC)", + "CREATE INDEX IF NOT EXISTS idx_audits_provider_streaming_created_id ON request_audits(provider, streaming, created_at DESC, id DESC)", "CREATE INDEX IF NOT EXISTS idx_audit_attempts_audit_number ON request_audit_attempts(audit_id, number)", "CREATE INDEX IF NOT EXISTS idx_response_ownership_expires_id ON response_ownership(expires_at, response_id)", "CREATE INDEX IF NOT EXISTS idx_response_ownership_account ON response_ownership(account_id)", diff --git a/backend/internal/repository/audit.go b/backend/internal/repository/audit.go index 4be019aa..d421a5d0 100644 --- a/backend/internal/repository/audit.go +++ b/backend/internal/repository/audit.go @@ -16,30 +16,94 @@ type AuditRepository interface { ListCursor(ctx context.Context, query AuditCursorQuery) ([]audit.Record, bool, error) Summarize(ctx context.Context, query AuditSummaryQuery) (audit.Summary, error) SumTokensByAccountsSince(ctx context.Context, accountIDs []uint64, since time.Time) (map[uint64]int64, error) - ListDegradeEvents(ctx context.Context, query DegradeEventQuery) ([]DegradeEvent, error) + SummarizeDegrade(ctx context.Context, query DegradeSummaryQuery) (DegradeSummaryResult, error) } -type DegradeEventQuery struct { +type DegradeSummaryQuery struct { Start time.Time End time.Time + SoftTPS float64 + HardTPS float64 + MinGenerationMS int64 MinOutputTokens int64 - Limit int + FailClosed bool + AccountSearch string + AccountStatus string + AccountClass string + MinHits int + AccountOffset int + AccountLimit int + Buckets []DegradeBucketRange + RecentLimit int } -// DegradeEvent is a slim streaming-success audit plus optional account flags. -type DegradeEvent struct { +type DegradeBucketRange struct { + Start time.Time + End time.Time +} + +type DegradeSummaryResult struct { + Totals DegradeTotals + Accounts []DegradeAccount + AccountTotal int64 + AccountOffset int + Nodes []DegradeNode + Buckets []DegradeBucket + Events []DegradeEvent +} + +type DegradeTotals struct { + Hits int64 + Accounts int64 + StillEnabled int64 + Disabled int64 + Deleted int64 + Hard int64 + Soft int64 + Burst int64 + MaxTPS float64 +} + +type DegradeAccount struct { ID uint64 - RequestID string - AccountID *uint64 - AccountName string + Name string Email string - Enabled *bool + Hits int64 + MaxTPS float64 + Burst int64 + Soft int64 + Hard int64 + Last time.Time + Enabled bool + Found bool BuildBotFlagSource int - EgressNodeID *uint64 - EgressNodeName string - OutputTokens int64 - FirstTokenMS int64 - DurationMS int64 - CreatedAt time.Time - Model string + Nodes []string +} + +type DegradeNode struct { + Name string + Hits int64 + Accounts int64 + MaxTPS float64 +} + +type DegradeBucket struct { + Index int + Count int64 + Severe int64 +} + +// DegradeEvent is a classified streaming-success audit. +type DegradeEvent struct { + ID uint64 + RequestID string + AccountID *uint64 + AccountName string + EgressNodeID *uint64 + EgressNodeName string + OutputTokens int64 + TPS float64 + Class string + CreatedAt time.Time + Model string } diff --git a/backend/internal/transport/http/audit/handler.go b/backend/internal/transport/http/audit/handler.go index ccdb4500..bc3dbf6b 100644 --- a/backend/internal/transport/http/audit/handler.go +++ b/backend/internal/transport/http/audit/handler.go @@ -337,7 +337,19 @@ func (h *Handler) summary(c *gin.Context) { func (h *Handler) degradeAccounts(c *gin.Context) { softTPS, _ := strconv.ParseFloat(c.Query("softTPS"), 64) hardTPS, _ := strconv.ParseFloat(c.Query("hardTPS"), 64) - result, err := h.service.DegradeSummary(c.Request.Context(), c.DefaultQuery("window", "24h"), auditapp.DegradeThresholds{SoftTPS: softTPS, HardTPS: hardTPS}) + minGenMS, _ := strconv.ParseInt(c.Query("minGenMs"), 10, 64) + failClosed, _ := strconv.ParseBool(c.Query("failClosed")) + minHits, _ := strconv.Atoi(c.Query("minHits")) + page, _ := strconv.Atoi(c.Query("page")) + pageSize, _ := strconv.Atoi(c.Query("pageSize")) + result, err := h.service.DegradeSummary( + c.Request.Context(), c.DefaultQuery("window", "24h"), + auditapp.DegradeThresholds{SoftTPS: softTPS, HardTPS: hardTPS, MinGenMS: minGenMS, FailClosed: failClosed}, + auditapp.DegradeAccountFilter{ + Search: c.Query("search"), Status: c.Query("status"), Class: c.Query("class"), MinHits: minHits, + Page: page, PageSize: pageSize, + }, + ) if errors.Is(err, auditapp.ErrInvalidPeriod) { response.Error(c, http.StatusBadRequest, "invalidAuditPeriod", "window 仅支持 1h、6h、24h、7d") return @@ -351,7 +363,7 @@ func (h *Handler) degradeAccounts(c *gin.Context) { accounts = append(accounts, degradeAccountResponse{ ID: strconv.FormatUint(account.ID, 10), Name: account.Name, Email: account.Email, Hits: account.Hits, MaxTPS: account.MaxTPS, Classes: account.Classes, Nodes: account.Nodes, Last: account.Last, - Enabled: account.Enabled, BFS: account.BFS, + Enabled: account.Enabled, Found: account.Found, BFS: account.BFS, }) } events := make([]degradeEventResponse, 0, len(result.Events)) @@ -372,21 +384,35 @@ func (h *Handler) degradeAccounts(c *gin.Context) { Thresholds: degradeThresholdsResponse{SoftTPS: result.Thresholds.SoftTPS, HardTPS: result.Thresholds.HardTPS, MinGenMS: result.Thresholds.MinGenMS, MinOut: result.Thresholds.MinOut}, Totals: degradeTotalsResponse{ Hits: result.Totals.Hits, Accounts: result.Totals.Accounts, StillEnabled: result.Totals.StillEnabled, - Disabled: result.Totals.Disabled, Hard: result.Totals.Hard, Soft: result.Totals.Soft, Burst: result.Totals.Burst, MaxTPS: result.Totals.MaxTPS, + Disabled: result.Totals.Disabled, Deleted: result.Totals.Deleted, Hard: result.Totals.Hard, + Soft: result.Totals.Soft, Burst: result.Totals.Burst, MaxTPS: result.Totals.MaxTPS, }, - Series: result.Series, Nodes: result.Nodes, Accounts: accounts, Events: events, + Series: result.Series, Nodes: result.Nodes, Accounts: accounts, + AccountPage: degradeAccountPageResponse{ + Page: result.AccountPage.Page, PageSize: result.AccountPage.PageSize, + Total: result.AccountPage.Total, HasMore: result.AccountPage.HasMore, + }, + Events: events, }) } type degradeSummaryResponse struct { - Window string `json:"window"` - GeneratedAt time.Time `json:"generatedAt"` - Thresholds degradeThresholdsResponse `json:"thresholds"` - Totals degradeTotalsResponse `json:"totals"` - Series []auditapp.DegradeBucket `json:"series"` - Nodes []auditapp.DegradeNode `json:"nodes"` - Accounts []degradeAccountResponse `json:"accounts"` - Events []degradeEventResponse `json:"events"` + Window string `json:"window"` + GeneratedAt time.Time `json:"generatedAt"` + Thresholds degradeThresholdsResponse `json:"thresholds"` + Totals degradeTotalsResponse `json:"totals"` + Series []auditapp.DegradeBucket `json:"series"` + Nodes []auditapp.DegradeNode `json:"nodes"` + Accounts []degradeAccountResponse `json:"accounts"` + AccountPage degradeAccountPageResponse `json:"accountPage"` + Events []degradeEventResponse `json:"events"` +} + +type degradeAccountPageResponse struct { + Page int `json:"page"` + PageSize int `json:"pageSize"` + Total int64 `json:"total"` + HasMore bool `json:"hasMore"` } type degradeThresholdsResponse struct { @@ -397,27 +423,29 @@ type degradeThresholdsResponse struct { } type degradeTotalsResponse struct { - Hits int `json:"hits"` - Accounts int `json:"accounts"` - StillEnabled int `json:"stillEnabled"` - Disabled int `json:"disabled"` - Hard int `json:"hard"` - Soft int `json:"soft"` - Burst int `json:"burst"` + Hits int64 `json:"hits"` + Accounts int64 `json:"accounts"` + StillEnabled int64 `json:"stillEnabled"` + Disabled int64 `json:"disabled"` + Deleted int64 `json:"deleted"` + Hard int64 `json:"hard"` + Soft int64 `json:"soft"` + Burst int64 `json:"burst"` MaxTPS float64 `json:"maxTPS"` } type degradeAccountResponse struct { - ID string `json:"id"` - Name string `json:"name"` - Email string `json:"email"` - Hits int `json:"hits"` - MaxTPS float64 `json:"maxTPS"` - Classes map[string]int `json:"classes"` - Nodes []string `json:"nodes"` - Last time.Time `json:"last"` - Enabled bool `json:"enabled"` - BFS int `json:"bfs"` + ID string `json:"id"` + Name string `json:"name"` + Email string `json:"email"` + Hits int64 `json:"hits"` + MaxTPS float64 `json:"maxTPS"` + Classes map[string]int64 `json:"classes"` + Nodes []string `json:"nodes"` + Last time.Time `json:"last"` + Enabled bool `json:"enabled"` + Found bool `json:"found"` + BFS int `json:"bfs"` } type degradeEventResponse struct { diff --git a/backend/internal/transport/http/audit/handler_test.go b/backend/internal/transport/http/audit/handler_test.go index 7e139f09..857b8af7 100644 --- a/backend/internal/transport/http/audit/handler_test.go +++ b/backend/internal/transport/http/audit/handler_test.go @@ -189,8 +189,10 @@ func TestDegradeAccountsListsHardHitsAndRejectsUnknownWindow(t *testing.T) { NewHandler(auditapp.NewService(repo, slog.Default(), 8, 4, time.Second)).Register(router.Group("/api/admin/v1")) ok := httptest.NewRecorder() - router.ServeHTTP(ok, httptest.NewRequest(http.MethodGet, "/api/admin/v1/request-audits/degrade-accounts?window=24h&softTPS=500&hardTPS=1000", nil)) - if ok.Code != http.StatusOK || !strings.Contains(ok.Body.String(), `"id":"11"`) || !strings.Contains(ok.Body.String(), `"hard":1`) { + router.ServeHTTP(ok, httptest.NewRequest(http.MethodGet, "/api/admin/v1/request-audits/degrade-accounts?window=24h&softTPS=500&hardTPS=1000&failClosed=false&page=1&pageSize=20", nil)) + if ok.Code != http.StatusOK || !strings.Contains(ok.Body.String(), `"id":"11"`) || !strings.Contains(ok.Body.String(), `"hard":1`) || + !strings.Contains(ok.Body.String(), `"found":false`) || !strings.Contains(ok.Body.String(), `"deleted":1`) || + !strings.Contains(ok.Body.String(), `"accountPage":{"page":1,"pageSize":20,"total":1,"hasMore":false}`) { t.Fatalf("status=%d body=%s", ok.Code, ok.Body.String()) } diff --git a/backend/internal/transport/http/egress/handler.go b/backend/internal/transport/http/egress/handler.go index c5d792eb..9846265c 100644 --- a/backend/internal/transport/http/egress/handler.go +++ b/backend/internal/transport/http/egress/handler.go @@ -139,6 +139,8 @@ type qualityGuardConfig struct { QuarantineSeconds int `json:"quarantine_seconds"` MinHealthyNodes int `json:"min_healthy_nodes"` MaxOutputTokens int `json:"max_output_tokens"` + FailClosed bool `json:"fail_closed"` + MinGenerationMS int `json:"min_generation_ms"` Prompt string `json:"prompt"` Expected string `json:"expected"` } @@ -194,6 +196,7 @@ func (h *Handler) qualityGuardStatus(c *gin.Context) { "hard_tps": state.Guard.HardTPS, "consecutive_soft": state.Guard.ConsecutiveSoft, "consecutive_errors": state.Guard.ConsecutiveErrors, "quarantine_seconds": state.Guard.QuarantineSeconds, "min_healthy_nodes": state.Guard.MinHealthyNodes, "max_output_tokens": state.Guard.MaxOutputTokens, + "fail_closed": state.Guard.FailClosed, "min_generation_ms": state.Guard.MinGenerationMS, }, "nodes": state.Nodes, "protectedNodeIds": state.ProtectedNodeIDs, "recentEvents": state.RecentEvents, } diff --git a/backend/internal/transport/http/egress/handler_test.go b/backend/internal/transport/http/egress/handler_test.go index 5e53991e..36c0b390 100644 --- a/backend/internal/transport/http/egress/handler_test.go +++ b/backend/internal/transport/http/egress/handler_test.go @@ -17,7 +17,7 @@ import ( func TestQualityGuardStatusReadsOnlyPublicState(t *testing.T) { path := t.TempDir() + "/state.json" - state := `{"version":1,"started_at":10,"updated_at":20,"last_active_cycle_at":15,"last_passive_poll_at":19,"password":"must-not-leak","guard":{"mode":"hybrid","model":"grok-4.5","client_key_id":"6","node_ids":["8"],"active_interval_seconds":1800,"passive_poll_seconds":5,"soft_tps":500,"hard_tps":1000,"consecutive_soft":2,"consecutive_errors":2,"quarantine_seconds":300,"min_healthy_nodes":3,"max_output_tokens":384,"prompt":"private-probe-prompt","expected":"private-marker"},"protected_node_ids":["9"],"nodes":{"8":{"active_soft_strikes":0,"passive_soft_strikes":0,"error_strikes":0,"quarantined_until":0,"disabled_by_guard":false,"last_reason":"","last_probe_at":15,"last_observed_at":19,"last_source":"passive","last_classification":"healthy","last_output_tps":42.5,"last_output_tokens":100,"last_first_token_ms":900,"last_duration_ms":4000}},"statistics":{"started_at":11,"active":{"total":7,"healthy":6,"soft":1,"hard":0,"errors":0,"output_tokens":1400},"passive":{"total":9,"healthy":8,"soft":0,"hard":1,"errors":0,"output_tokens":1800},"actions":{"quarantined":1,"restored":0,"suppressed":0}}}` + state := `{"version":1,"started_at":10,"updated_at":20,"last_active_cycle_at":15,"last_passive_poll_at":19,"password":"must-not-leak","guard":{"mode":"hybrid","model":"grok-4.5","client_key_id":"6","node_ids":["8"],"active_interval_seconds":1800,"passive_poll_seconds":5,"soft_tps":500,"hard_tps":1000,"consecutive_soft":2,"consecutive_errors":2,"quarantine_seconds":300,"min_healthy_nodes":3,"max_output_tokens":384,"fail_closed":true,"min_generation_ms":1234,"prompt":"private-probe-prompt","expected":"private-marker"},"protected_node_ids":["9"],"nodes":{"8":{"active_soft_strikes":0,"passive_soft_strikes":0,"error_strikes":0,"quarantined_until":0,"disabled_by_guard":false,"last_reason":"","last_probe_at":15,"last_observed_at":19,"last_source":"passive","last_classification":"healthy","last_output_tps":42.5,"last_output_tokens":100,"last_first_token_ms":900,"last_duration_ms":4000}},"statistics":{"started_at":11,"active":{"total":7,"healthy":6,"soft":1,"hard":0,"errors":0,"output_tokens":1400},"passive":{"total":9,"healthy":8,"soft":0,"hard":1,"errors":0,"output_tokens":1800},"actions":{"quarantined":1,"restored":0,"suppressed":0}}}` if err := os.WriteFile(path, []byte(state), 0o600); err != nil { t.Fatal(err) } @@ -25,7 +25,7 @@ func TestQualityGuardStatusReadsOnlyPublicState(t *testing.T) { context, _ := gin.CreateTestContext(recorder) context.Request = httptest.NewRequest("GET", "/egress-quality-guard", nil) NewHandler(nil, path).qualityGuardStatus(context) - if recorder.Code != 200 || !strings.Contains(recorder.Body.String(), `"available":true`) || !strings.Contains(recorder.Body.String(), `"last_output_tps":42.5`) || !strings.Contains(recorder.Body.String(), `"output_tokens":1400`) || !strings.Contains(recorder.Body.String(), `"protectedNodeIds":["9"]`) { + if recorder.Code != 200 || !strings.Contains(recorder.Body.String(), `"available":true`) || !strings.Contains(recorder.Body.String(), `"last_output_tps":42.5`) || !strings.Contains(recorder.Body.String(), `"output_tokens":1400`) || !strings.Contains(recorder.Body.String(), `"protectedNodeIds":["9"]`) || !strings.Contains(recorder.Body.String(), `"fail_closed":true`) || !strings.Contains(recorder.Body.String(), `"min_generation_ms":1234`) { t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String()) } if strings.Contains(recorder.Body.String(), "must-not-leak") || strings.Contains(recorder.Body.String(), "private-probe-prompt") || strings.Contains(recorder.Body.String(), "private-marker") || strings.Contains(recorder.Body.String(), "client_key_id") || !strings.Contains(recorder.Body.String(), `"recentEvents":[]`) { diff --git a/frontend/src/features/quality-guard/degrade-accounts-panel.tsx b/frontend/src/features/quality-guard/degrade-accounts-panel.tsx index 66dd821c..8d269ff8 100644 --- a/frontend/src/features/quality-guard/degrade-accounts-panel.tsx +++ b/frontend/src/features/quality-guard/degrade-accounts-panel.tsx @@ -1,5 +1,5 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { AlertTriangle, Gauge, Power, PowerOff, RefreshCw, Search, Users } from "lucide-react"; +import { AlertTriangle, Gauge, PowerOff, RefreshCw, Search, Users } from "lucide-react"; import { useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; @@ -13,33 +13,40 @@ import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@ import { updateAccountsEnabled } from "@/features/accounts/accounts-api"; import { getDegradeAccounts, type DegradeAccountDTO, type DegradeClass, type DegradeSummaryDTO, type DegradeWindow } from "@/features/quality-guard/quality-guard-api"; import { EmptyState, ErrorState } from "@/shared/components/data-state"; +import { Pagination } from "@/shared/components/pagination"; +import { useDebouncedValue } from "@/shared/hooks/use-debounced-value"; import { cn } from "@/shared/lib/cn"; import { formatCompactDateTime } from "@/shared/lib/format"; const MUTE_TOAST_ID = "quality-guard-degrade-mute"; -export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; hardTPS?: number }) { +export function DegradeAccountsPanel({ softTPS, hardTPS, failClosed, minGenMs }: { softTPS?: number; hardTPS?: number; failClosed?: boolean; minGenMs?: number }) { const { t, i18n } = useTranslation(); const queryClient = useQueryClient(); const [period, setPeriod] = useState("24h"); const [search, setSearch] = useState(""); - const [status, setStatus] = useState<"all" | "on" | "off">("all"); + const debouncedSearch = useDebouncedValue(search); + const [status, setStatus] = useState<"all" | "enabled" | "disabled" | "deleted">("all"); const [cls, setCls] = useState<"all" | DegradeClass>("all"); const [hitsMin, setHitsMin] = useState(1); + const [page, setPage] = useState(1); + const [pageSize, setPageSize] = useState(50); const [selected, setSelected] = useState>(() => new Set()); const query = useQuery({ - queryKey: ["quality-guard-degrade-accounts", period, softTPS, hardTPS], - queryFn: () => getDegradeAccounts({ window: period, softTPS, hardTPS }), + queryKey: ["quality-guard-degrade-accounts", period, softTPS, hardTPS, failClosed, minGenMs, debouncedSearch, status, cls, hitsMin, page, pageSize], + queryFn: () => getDegradeAccounts({ + window: period, softTPS, hardTPS, failClosed, minGenMs, search: debouncedSearch || undefined, + status: status === "all" ? undefined : status, class: cls === "all" ? undefined : cls, + minHits: hitsMin, page, pageSize, + }), refetchInterval: 15_000, }); const data = query.data; - const rows = useMemo(() => filterAccounts(data, { search, status, cls, hitsMin }), [data, search, status, cls, hitsMin]); - const selectable = rows; + const rows = useMemo(() => data?.accounts ?? [], [data?.accounts]); + const selectable = useMemo(() => rows.filter((account) => account.found && account.enabled), [rows]); const selectedRows = selectable.filter((account) => selected.has(account.id)); - const selectedEnabled = selectedRows.filter((account) => account.enabled); - const selectedMuted = selectedRows.filter((account) => !account.enabled); const allSelected = selectable.length > 0 && selectedRows.length === selectable.length; const muteMutation = useMutation({ @@ -53,18 +60,7 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h }, onError: (error) => toast.error(error instanceof Error ? error.message : t("qualityGuard.degrade.muteFailed"), { id: MUTE_TOAST_ID }), }); - const unmuteMutation = useMutation({ - mutationFn: (ids: string[]) => updateAccountsEnabled(ids, true, "grok_build"), - onMutate: () => toast.loading(t("qualityGuard.degrade.unmuting"), { id: MUTE_TOAST_ID }), - onSuccess: (_, ids) => { - setSelected(new Set()); - void queryClient.invalidateQueries({ queryKey: ["quality-guard-degrade-accounts"] }); - void queryClient.invalidateQueries({ queryKey: ["accounts"] }); - toast.success(t("qualityGuard.degrade.unmuted", { count: ids.length }), { id: MUTE_TOAST_ID }); - }, - onError: (error) => toast.error(error instanceof Error ? error.message : t("qualityGuard.degrade.unmuteFailed"), { id: MUTE_TOAST_ID }), - }); - const busy = muteMutation.isPending || unmuteMutation.isPending; + const busy = muteMutation.isPending; const toggleAll = (checked: boolean) => { setSelected((current) => { @@ -84,7 +80,7 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h
- + = data.thresholds.hardTPS ? "bad" : undefined} />
@@ -100,30 +96,24 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h

{t("qualityGuard.degrade.accountsTitle")}

{hitsMin > 1 - ? t("qualityGuard.degrade.accountsHintFiltered", { shown: rows.length, total: data.accounts.length, min: hitsMin }) - : t("qualityGuard.degrade.accountsHint", { shown: rows.length, total: data.accounts.length })} + ? t("qualityGuard.degrade.accountsHintFiltered", { shown: rows.length, total: data.accountPage.total, min: hitsMin }) + : t("qualityGuard.degrade.accountsHint", { shown: rows.length, total: data.accountPage.total })}

- setSearch(event.target.value)} placeholder={t("qualityGuard.degrade.search")} /> + { setSearch(event.target.value); setPage(1); setSelected(new Set()); }} placeholder={t("qualityGuard.degrade.search")} />
- { setSelected(new Set()); setPeriod(value as DegradeWindow); }} items={[["1h", t("qualityGuard.degrade.windows.1h")], ["6h", t("qualityGuard.degrade.windows.6h")], ["24h", t("qualityGuard.degrade.windows.24h")], ["7d", t("qualityGuard.degrade.windows.7d")]]} /> - setStatus(value as "all" | "on" | "off")} items={[["all", t("qualityGuard.degrade.statusAll")], ["on", t("qualityGuard.degrade.statusOn")], ["off", t("qualityGuard.degrade.statusOff")]]} /> - setCls(value as "all" | DegradeClass)} items={[["all", t("qualityGuard.degrade.classAll")], ["buffered_burst", "burst"], ["soft_tps", "soft"], ["hard_tps", "hard"]]} /> - setHitsMin(Number(value))} items={[["1", t("qualityGuard.degrade.hitsAll")], ["2", t("qualityGuard.degrade.hitsMin", { count: 2 })], ["3", t("qualityGuard.degrade.hitsMin", { count: 3 })], ["5", t("qualityGuard.degrade.hitsMin", { count: 5 })], ["10", t("qualityGuard.degrade.hitsMin", { count: 10 })]]} /> - -
+ {data.accountPage.total > 0 ? ( +
+ { setPage(value); setSelected(new Set()); }} + onPageSizeChange={(value) => { setPageSize(value); setPage(1); setSelected(new Set()); }} + /> +
+ ) : null}
@@ -205,19 +215,6 @@ export function DegradeAccountsPanel({ softTPS, hardTPS }: { softTPS?: number; h ); } -function filterAccounts(data: DegradeSummaryDTO | undefined, filters: { search: string; status: "all" | "on" | "off"; cls: "all" | DegradeClass; hitsMin: number }) { - if (!data) return []; - const search = filters.search.trim().toLowerCase(); - return data.accounts.filter((account) => { - if (account.hits < filters.hitsMin) return false; - if (filters.status === "on" && !account.enabled) return false; - if (filters.status === "off" && account.enabled) return false; - if (filters.cls !== "all" && (account.classes[filters.cls] ?? 0) <= 0) return false; - if (search && !`${account.id} ${account.email} ${account.name}`.toLowerCase().includes(search)) return false; - return true; - }); -} - function classSummary(classes: DegradeAccountDTO["classes"]) { return [ classes.buffered_burst ? `burst ${classes.buffered_burst}` : "", diff --git a/frontend/src/features/quality-guard/quality-guard-api.ts b/frontend/src/features/quality-guard/quality-guard-api.ts index 0ddffa14..f47d5149 100644 --- a/frontend/src/features/quality-guard/quality-guard-api.ts +++ b/frontend/src/features/quality-guard/quality-guard-api.ts @@ -76,6 +76,8 @@ export type QualityGuardStatus = { quarantine_seconds: number; min_healthy_nodes: number; max_output_tokens: number; + fail_closed: boolean; + min_generation_ms: number; }; nodes?: Record; protectedNodeIds?: string[]; @@ -110,6 +112,7 @@ const configValidator = hasShape({ node_ids: isArrayOf(isString), active_interval_seconds: isNumber, passive_poll_seconds: isNumber, soft_tps: isNumber, hard_tps: isNumber, consecutive_soft: isNumber, consecutive_errors: isNumber, quarantine_seconds: isNumber, min_healthy_nodes: isNumber, max_output_tokens: isNumber, + fail_closed: isBoolean, min_generation_ms: isNumber, }); const detectionStatsValidator = hasShape({ total: isNumber, healthy: isNumber, soft: isNumber, hard: isNumber, @@ -165,6 +168,7 @@ export type DegradeAccountDTO = { nodes: string[]; last: string; enabled: boolean; + found: boolean; bfs: number; }; @@ -185,10 +189,11 @@ export type DegradeSummaryDTO = { window: DegradeWindow; generatedAt: string; thresholds: { softTPS: number; hardTPS: number; minGenMs: number; minOutputTokens: number }; - totals: { hits: number; accounts: number; stillEnabled: number; disabled: number; hard: number; soft: number; burst: number; maxTPS: number }; + totals: { hits: number; accounts: number; stillEnabled: number; disabled: number; deleted: number; hard: number; soft: number; burst: number; maxTPS: number }; series: { label: string; count: number; severe: number }[]; nodes: { name: string; hits: number; accounts: number; maxTPS: number }[]; accounts: DegradeAccountDTO[]; + accountPage: { page: number; pageSize: number; total: number; hasMore: boolean }; events: DegradeEventDTO[]; }; @@ -198,13 +203,14 @@ const decodeDegradeSummary = createObjectDecoder("degrade acc window: isOneOf("1h", "6h", "24h", "7d"), generatedAt: isString, thresholds: hasShape({ softTPS: isNumber, hardTPS: isNumber, minGenMs: isNumber, minOutputTokens: isNumber }), - totals: hasShape({ hits: isNumber, accounts: isNumber, stillEnabled: isNumber, disabled: isNumber, hard: isNumber, soft: isNumber, burst: isNumber, maxTPS: isNumber }), + totals: hasShape({ hits: isNumber, accounts: isNumber, stillEnabled: isNumber, disabled: isNumber, deleted: isNumber, hard: isNumber, soft: isNumber, burst: isNumber, maxTPS: isNumber }), series: isArrayOf(hasShape({ label: isString, count: isNumber, severe: isNumber })), nodes: isArrayOf(hasShape({ name: isString, hits: isNumber, accounts: isNumber, maxTPS: isNumber })), accounts: isArrayOf(hasShape({ id: isString, name: isString, email: isString, hits: isNumber, maxTPS: isNumber, - classes: isObject, nodes: isArrayOf(isString), last: isString, enabled: isBoolean, bfs: isNumber, + classes: isObject, nodes: isArrayOf(isString), last: isString, enabled: isBoolean, found: isBoolean, bfs: isNumber, })), + accountPage: hasShape({ page: isNumber, pageSize: isNumber, total: isNumber, hasMore: isBoolean }), events: isArrayOf(hasShape({ id: isString, requestId: isString, accountId: isOptional(isString), accountName: isString, nodeName: isString, outputTokens: isNumber, tps: isNumber, class: degradeClassValidator, @@ -212,9 +218,27 @@ const decodeDegradeSummary = createObjectDecoder("degrade acc })), }); -export function getDegradeAccounts(input: { window: DegradeWindow; softTPS?: number; hardTPS?: number }): Promise { - const query = new URLSearchParams({ window: input.window }); +export function getDegradeAccounts(input: { + window: DegradeWindow; + softTPS?: number; + hardTPS?: number; + failClosed?: boolean; + minGenMs?: number; + search?: string; + status?: "enabled" | "disabled" | "deleted"; + class?: DegradeClass; + minHits?: number; + page: number; + pageSize: number; +}): Promise { + const query = new URLSearchParams({ window: input.window, page: String(input.page), pageSize: String(input.pageSize) }); if (input.softTPS) query.set("softTPS", String(input.softTPS)); if (input.hardTPS) query.set("hardTPS", String(input.hardTPS)); + if (input.failClosed !== undefined) query.set("failClosed", String(input.failClosed)); + if (input.minGenMs) query.set("minGenMs", String(input.minGenMs)); + if (input.search) query.set("search", input.search); + if (input.status) query.set("status", input.status); + if (input.class) query.set("class", input.class); + if (input.minHits && input.minHits > 1) query.set("minHits", String(input.minHits)); return apiRequest(`/api/admin/v1/request-audits/degrade-accounts?${query}`, {}, decodeDegradeSummary); } diff --git a/frontend/src/features/quality-guard/quality-guard-page.tsx b/frontend/src/features/quality-guard/quality-guard-page.tsx index ce682c16..34c4d1ba 100644 --- a/frontend/src/features/quality-guard/quality-guard-page.tsx +++ b/frontend/src/features/quality-guard/quality-guard-page.tsx @@ -167,7 +167,12 @@ export function QualityGuardPage() { {t("qualityGuard.degrade.tab")} - + {!status?.available ? : ( diff --git a/frontend/src/shared/components/pagination.tsx b/frontend/src/shared/components/pagination.tsx index 63c08bb9..de4c24d8 100644 --- a/frontend/src/shared/components/pagination.tsx +++ b/frontend/src/shared/components/pagination.tsx @@ -7,7 +7,7 @@ import { cn } from "@/shared/lib/cn"; const PAGE_SIZE_OPTIONS = [20, 100, 500, 1000, 2000] as const; -export function Pagination({ page, pageSize, total, onPageChange, onPageSizeChange, className }: { page: number; pageSize: number; total: number; onPageChange: (page: number) => void; onPageSizeChange?: (pageSize: number) => void; className?: string }) { +export function Pagination({ page, pageSize, total, onPageChange, onPageSizeChange, pageSizeOptions = PAGE_SIZE_OPTIONS, className }: { page: number; pageSize: number; total: number; onPageChange: (page: number) => void; onPageSizeChange?: (pageSize: number) => void; pageSizeOptions?: readonly number[]; className?: string }) { const { t } = useTranslation(); const pages = Math.max(1, Math.ceil(total / pageSize)); @@ -20,7 +20,7 @@ export function Pagination({ page, pageSize, total, onPageChange, onPageSizeChan - {onPageSizeChange ? : } + {onPageSizeChange ? : } ); } @@ -36,12 +36,12 @@ export function CursorPagination({ page, pageSize, hasMore, disabled = false, on {t("audits.cursorPage", { page })} - + ); } -function PageSizeSelector({ pageSize, disabled = false, onChange }: { pageSize: number; disabled?: boolean; onChange: (pageSize: number) => void }) { +function PageSizeSelector({ pageSize, disabled = false, options, onChange }: { pageSize: number; disabled?: boolean; options: readonly number[]; onChange: (pageSize: number) => void }) { const { t } = useTranslation(); return (
@@ -49,7 +49,7 @@ function PageSizeSelector({ pageSize, disabled = false, onChange }: { pageSize: {t("common.rows")} diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index 169df231..e3693e69 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -447,15 +447,15 @@ const resources = { degrade: { tab: "降智账号", overview: "降智账号概览", series: "降智时序", nodes: "按出口节点", hits: "降智次数", hitsHelp: "burst {{burst}} · soft {{soft}} · hard {{hard}}", - accounts: "涉及账号", accountsHelp: "窗口内去重", stillEnabled: "仍在调度", stillEnabledHelp: "漏网,可批量禁", + accounts: "涉及账号", accountsHelp: "窗口内去重 · 已删除 {{deleted}}", stillEnabled: "仍在调度", stillEnabledHelp: "漏网,可批量禁", maxTPS: "峰值 TPS", maxTPSHelp: "单次请求最高", accountsTitle: "降智账号", accountsHint: "显示 {{shown}} / {{total}}", accountsHintFiltered: "显示 {{shown}} / {{total}} · 命中≥{{min}}", - search: "搜邮箱 / ID", statusAll: "全部状态", statusOn: "仍在调度", statusOff: "已禁言", + search: "搜名称 / 邮箱 / ID", statusAll: "全部状态", statusOn: "仍在调度", statusOff: "已禁用", statusDeleted: "账号已删除", classAll: "全部类型", class: "类型", account: "账号", status: "状态", hitCount: "命中", hitsAll: "全部次数", hitsMin: "命中 ≥ {{count}}", windows: { "1h": "近 1 小时", "6h": "近 6 小时", "24h": "近 24 小时", "7d": "近 7 天" }, - muteSelected: "禁掉所选", muteSelectedCount: "禁掉所选 ({{count}})", muteConfirm: "确认禁掉 {{count}} 个仍在调度的降智账号?", muting: "正在禁言账号", muted: "已禁言 {{count}} 个账号", muteFailed: "禁言失败", unmuteSelected: "解除禁用", unmuteSelectedCount: "解除禁用 ({{count}})", unmuteConfirm: "确认恢复 {{count}} 个已禁账号到调度?", unmuting: "正在恢复账号", unmuted: "已恢复 {{count}} 个账号", unmuteFailed: "恢复失败", - scheduling: "调度", mutedStatus: "已禁", + muteSelected: "禁用所选", muteSelectedCount: "禁用所选 ({{count}})", muteConfirm: "确认禁用 {{count}} 个仍在调度的降智账号?", muting: "正在禁用账号", muted: "已禁用 {{count}} 个账号", muteFailed: "禁用失败", + scheduling: "调度中", disabledStatus: "已禁用", deletedStatus: "已删除", events: "最近事件", eventsHelp: "用户请求,不含 quality-test 探针", noHits: "这个窗口没有降智请求", noNodes: "无节点数据", noAccounts: "没有匹配账号", noEvents: "无事件", }, @@ -1356,15 +1356,15 @@ const resources = { degrade: { tab: "Degraded accounts", overview: "Degraded account overview", series: "Degrade timeline", nodes: "By egress node", hits: "Degrade hits", hitsHelp: "burst {{burst}} · soft {{soft}} · hard {{hard}}", - accounts: "Accounts", accountsHelp: "Unique in this window", stillEnabled: "Still scheduled", stillEnabledHelp: "Still enabled; can be muted in bulk", + accounts: "Accounts", accountsHelp: "Unique in this window · {{deleted}} deleted", stillEnabled: "Still scheduled", stillEnabledHelp: "Still enabled; can be disabled in bulk", maxTPS: "Peak TPS", maxTPSHelp: "Highest single request", accountsTitle: "Degraded accounts", accountsHint: "Showing {{shown}} / {{total}}", accountsHintFiltered: "Showing {{shown}} / {{total}} · hits ≥ {{min}}", - search: "Search email / ID", statusAll: "All statuses", statusOn: "Still scheduled", statusOff: "Muted", + search: "Search name / email / ID", statusAll: "All statuses", statusOn: "Still scheduled", statusOff: "Disabled", statusDeleted: "Deleted accounts", classAll: "All classes", class: "Class", account: "Account", status: "Status", hitCount: "Hits", hitsAll: "Any hit count", hitsMin: "Hits ≥ {{count}}", windows: { "1h": "Last 1 hour", "6h": "Last 6 hours", "24h": "Last 24 hours", "7d": "Last 7 days" }, - muteSelected: "Mute selected", muteSelectedCount: "Mute selected ({{count}})", muteConfirm: "Mute {{count}} still-scheduled degraded accounts?", muting: "Muting accounts", muted: "Muted {{count}} accounts", muteFailed: "Failed to mute accounts", unmuteSelected: "Unmute selected", unmuteSelectedCount: "Unmute selected ({{count}})", unmuteConfirm: "Restore {{count}} muted accounts to scheduling?", unmuting: "Restoring accounts", unmuted: "Restored {{count}} accounts", unmuteFailed: "Failed to restore accounts", - scheduling: "Scheduled", mutedStatus: "Muted", + muteSelected: "Disable selected", muteSelectedCount: "Disable selected ({{count}})", muteConfirm: "Disable {{count}} still-scheduled degraded accounts?", muting: "Disabling accounts", muted: "Disabled {{count}} accounts", muteFailed: "Failed to disable accounts", + scheduling: "Scheduled", disabledStatus: "Disabled", deletedStatus: "Deleted", events: "Recent events", eventsHelp: "User requests; quality-test probes are excluded", noHits: "No degrade requests in this window", noNodes: "No node data", noAccounts: "No matching accounts", noEvents: "No events", }, From 16e12bdc283a493a8eddce1271b1ede9a2ad1d58 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Fri, 14 Aug 2026 09:06:03 +0800 Subject: [PATCH 29/48] fix: use Responses stream state machine for image compatibility --- backend/internal/infra/provider/web/image.go | 40 ++++++++++++----- .../infra/provider/web/protocol_test.go | 44 +++++++++++++++++++ 2 files changed, 72 insertions(+), 12 deletions(-) diff --git a/backend/internal/infra/provider/web/image.go b/backend/internal/infra/provider/web/image.go index fb759985..cb2b1438 100644 --- a/backend/internal/infra/provider/web/image.go +++ b/backend/internal/infra/provider/web/image.go @@ -24,6 +24,7 @@ import ( mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media" "github.com/chenyme/grok2api/backend/internal/infra/egress" "github.com/chenyme/grok2api/backend/internal/infra/provider" + "github.com/chenyme/grok2api/backend/internal/infra/provider/conversation" ) const ( @@ -513,16 +514,14 @@ func (a *Adapter) forwardImageChatCompletion(ctx context.Context, request provid } parsed.appendText(liteImageMarkdown(item)) } - payload := buildOpenAIResult(request.Operation, responseID, input.Model, parsed, false) if input.Stream || request.Streaming { - var stream bytes.Buffer - writeStreamStart(&stream, request.Operation, responseID, input.Model, parsed.InputTokens) - if err := writeStreamDelta(&stream, request.Operation, responseID, input.Model, "text", parsed.Text.String()); err != nil { + stream, err := buildImageCompatibilityStream(request.Operation, responseID, input.Model, &parsed) + if err != nil { return nil, err } - writeStreamDone(&stream, request.Operation, responseID, input.Model, parsed, payload) - return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: io.NopCloser(bytes.NewReader(stream.Bytes())), QuotaUnits: count}, nil + return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: io.NopCloser(bytes.NewReader(stream)), QuotaUnits: count}, nil } + payload := buildOpenAIResult(request.Operation, responseID, input.Model, parsed, false) data, err := json.Marshal(payload) if err != nil { return nil, err @@ -568,16 +567,14 @@ func (a *Adapter) forwardQualityImageChatCompletion(ctx context.Context, request if parsed.Text.Len() == 0 { return nil, fmt.Errorf("图片生成兼容响应中没有图片") } - result := buildOpenAIResult(request.Operation, parsed.ResponseID, input.Model, parsed, false) if input.Stream || request.Streaming { - var stream bytes.Buffer - writeStreamStart(&stream, request.Operation, parsed.ResponseID, input.Model, parsed.InputTokens) - if err := writeStreamDelta(&stream, request.Operation, parsed.ResponseID, input.Model, "text", parsed.Text.String()); err != nil { + stream, err := buildImageCompatibilityStream(request.Operation, parsed.ResponseID, input.Model, &parsed) + if err != nil { return nil, err } - writeStreamDone(&stream, request.Operation, parsed.ResponseID, input.Model, parsed, result) - return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: io.NopCloser(bytes.NewReader(stream.Bytes())), QuotaUnits: generated.QuotaUnits}, nil + return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: io.NopCloser(bytes.NewReader(stream)), QuotaUnits: generated.QuotaUnits}, nil } + result := buildOpenAIResult(request.Operation, parsed.ResponseID, input.Model, parsed, false) data, err := json.Marshal(result) if err != nil { return nil, err @@ -585,6 +582,25 @@ func (a *Adapter) forwardQualityImageChatCompletion(ctx context.Context, request return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: jsonHeaders(), Body: io.NopCloser(bytes.NewReader(data)), QuotaUnits: generated.QuotaUnits}, nil } +func buildImageCompatibilityStream(operation, responseID, model string, parsed *parsedChat) ([]byte, error) { + var stream bytes.Buffer + writeStreamStart(&stream, operation, responseID, model, parsed.InputTokens) + if operation == conversation.OperationResponses { + responsesStream := newWebResponsesStream(&stream, responseID) + if err := responsesStream.Delta("text", parsed.Text.String()); err != nil { + return nil, err + } + if err := responsesStream.Finish(parsed); err != nil { + return nil, err + } + } else if err := writeStreamDelta(&stream, operation, responseID, model, "text", parsed.Text.String()); err != nil { + return nil, err + } + payload := buildOpenAIResult(operation, responseID, model, *parsed, false) + writeStreamDone(&stream, operation, responseID, model, *parsed, payload) + return stream.Bytes(), nil +} + func liteImageMarkdown(item map[string]any) string { if value, _ := item["url"].(string); value != "" { return "![image](" + value + ")" diff --git a/backend/internal/infra/provider/web/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index 3c848f22..ef00e67f 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -215,6 +215,50 @@ func TestQualityImageResponsesUsesImageCompatibilityValidation(t *testing.T) { } } +func TestImageCompatibilityResponsesStreamUsesOutputStateMachine(t *testing.T) { + parsed := parsedChat{ResponseID: "resp_image", InputTokens: 3} + parsed.appendText("![image](https://example.com/generated.png)") + body, err := buildImageCompatibilityStream( + conversation.OperationResponses, + parsed.ResponseID, + "grok-imagine-image-lite", + &parsed, + ) + if err != nil { + t.Fatal(err) + } + stream := string(body) + for _, event := range []string{ + "response.created", + "response.output_item.added", + "response.content_part.added", + "response.output_text.delta", + "response.output_text.done", + "response.content_part.done", + "response.output_item.done", + "response.completed", + } { + if !strings.Contains(stream, "event: "+event+"\n") { + t.Fatalf("stream missing %s: %s", event, stream) + } + } + if strings.Contains(stream, "chat.completion.chunk") || strings.Contains(stream, "data: [DONE]") { + t.Fatalf("Responses stream contains Chat Completions envelope: %s", stream) + } + if len(parsed.ResponseOutput) != 1 { + t.Fatalf("response output = %#v", parsed.ResponseOutput) + } + item := parsed.ResponseOutput[0].(map[string]any) + if item["type"] != "message" || item["status"] != "completed" { + t.Fatalf("response output item = %#v", item) + } + itemID, _ := item["id"].(string) + completedAt := strings.Index(stream, "event: response.completed\n") + if itemID == "" || completedAt < 0 || !strings.Contains(stream[completedAt:], `"id":"`+itemID+`"`) { + t.Fatalf("completed response does not reuse output item %q: %s", itemID, stream) + } +} + func TestNormalizeResponsesInputImage(t *testing.T) { dataURI := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=" input, _ := json.Marshal([]any{map[string]any{ From 852e44443e85b9331e1de59ba10e2c20bd3913f0 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Fri, 14 Aug 2026 09:15:35 +0800 Subject: [PATCH 30/48] fix: update resolution field descriptions for images and videos --- frontend/src/features/docs/api-docs-page.tsx | 4 ++-- frontend/src/shared/i18n/index.ts | 22 +++++++++++--------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/frontend/src/features/docs/api-docs-page.tsx b/frontend/src/features/docs/api-docs-page.tsx index c3677ca6..49caa853 100644 --- a/frontend/src/features/docs/api-docs-page.tsx +++ b/frontend/src/features/docs/api-docs-page.tsx @@ -96,7 +96,7 @@ const endpoints: Record = { { name: "prompt", required: true, descriptionKey: "docs.reference.fieldPrompt" }, { name: "n", descriptionKey: "docs.reference.fieldImageCount" }, { name: "aspect_ratio", descriptionKey: "docs.reference.fieldAspectRatio" }, - { name: "resolution", descriptionKey: "docs.reference.fieldResolution" }, + { name: "resolution", descriptionKey: "docs.reference.fieldImageResolution" }, { name: "quality", descriptionKey: "docs.reference.fieldQuality" }, { name: "response_format", descriptionKey: "docs.reference.fieldResponseFormat" }, { name: "stream", descriptionKey: "docs.reference.fieldImageStream" }, @@ -128,7 +128,7 @@ const endpoints: Record = { { name: "prompt", descriptionKey: "docs.reference.fieldVideoPrompt" }, { name: "duration", descriptionKey: "docs.reference.fieldDuration" }, { name: "aspect_ratio", descriptionKey: "docs.reference.fieldAspectRatio" }, - { name: "resolution", descriptionKey: "docs.reference.fieldResolution" }, + { name: "resolution", descriptionKey: "docs.reference.fieldVideoResolution" }, { name: "image", descriptionKey: "docs.reference.fieldVideoImage" }, { name: "reference_images", descriptionKey: "docs.reference.fieldReferenceImages" }, { name: "reference_audios", descriptionKey: "docs.reference.fieldReferenceAudios" }, diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index 08ae7f32..965fb1dc 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -1100,20 +1100,21 @@ const resources = { fieldPrompt: "用于生成或编辑图片的自然语言描述。", fieldImageCount: "需要返回的图片数量;网关会选择可满足数量的最小上游批次。", fieldAspectRatio: "输出媒体的宽高比,例如 1:1、2:3 或 16:9。", - fieldResolution: "输出分辨率;图片支持 1k/2k。视频 grok-imagine-video 支持 480p/720p,grok-imagine-video-1.5 额外支持 1080p,但 1080p 不能用于参考图生视频。", + fieldImageResolution: "图片输出分辨率,支持 1k/2k。", + fieldVideoResolution: "视频输出分辨率,支持 480p/720p;仅上游模型 grok-imagine-video-1.5 在非参考图模式下支持 1080p。", fieldQuality: "Image 2.0 的生成质量,可选 low 或 medium;默认 medium。", fieldResponseFormat: "图片返回格式,支持 url 或 b64_json。", fieldImageStream: "是否使用图片生成扩展 SSE 流;默认 false。", fieldEditImages: "待编辑图片,使用 image 或 images 传入 URL、Data URL 或已支持的图片引用。", fieldVideoPrompt: "视频描述;使用图片输入时可作为运动或镜头指令。", - fieldDuration: "视频时长(秒)。文生视频与首帧图生视频最长 15 秒;参考图生视频 grok-imagine-video 最长 10 秒、grok-imagine-video-1.5 最长 15 秒。", + fieldDuration: "视频时长(秒),范围 1–15。Console 路由中,grok-imagine-video 的参考图模式最长 10 秒;grok-imagine-video-1.5 最长 15 秒。", fieldVideoImage: "可选首帧图片引用,用于图生视频;最多 1 张,不可与 reference_images 同时使用。", fieldVideoEditPrompt: "描述希望如何修改原视频。", fieldVideoExtendPrompt: "描述视频接下来应发生的内容。", fieldVideoInput: "输入视频,支持 url 或本地上传后的 file_id。", fieldVideoExtendDuration: "延长片段时长,单位秒,范围 2 到 10,默认 6。", - fieldReferenceImages: "可选参考图片数组,用于参考图视频;最多 7 张,每项提供 url 或 file_id,不可与 image 同时使用。", - fieldReferenceAudios: "可选参考音频数组,最多 3 个内置 voice_id;可单独使用或与 reference_images 组合。需上游团队开启该能力,未开启时上游返回 403。", + fieldReferenceImages: "可选参考图片数组,用于参考图视频;网关最多接收 8 张,Console 路由最多 7 张。每项提供 url 或 file_id,不可与 image 同时使用。", + fieldReferenceAudios: "可选参考音频数组,最多 3 个内置 voice_id;可单独使用或与 reference_images 组合。该能力可能受上游团队权限控制;Console 未开通时上游返回 403。", fieldRequestId: "创建视频任务时返回的 request_id。", noteChatProviders: "Build、Web 与 Console 使用独立账号池和上游协议,但向客户端返回统一的 Chat Completions 结构。", noteChatImages: "对话图片会先完成校验与上传,再绑定到本次选择的账号;不会在流开始后切换账号。", @@ -1131,7 +1132,7 @@ const resources = { noteEditSources: "远程图片会经过 SSRF、防体积超限和内容类型校验后再上传到上游。", noteVideoAsync: "创建接口只返回 request_id;生成过程异步执行并持久化任务状态。", noteVideoDuration: "时长、比例、分辨率和图片输入按当前视频模型能力校验。", - noteVideoReference: "参考图视频走 /videos/generations + reference_images,最多 7 张;只传 1 张也保持参考图语义,不会被当成首帧。不可与 image 同用。参考图模式 resolution 最高 720p,grok-imagine-video-1.5 也不例外。reference_audios 使用内置 voice_id,需团队开启该能力。", + noteVideoReference: "参考图视频走 /videos/generations + reference_images;只传 1 张也保持参考图语义,不会被当成首帧。网关最多接收 8 张,Console 路由最多 7 张;不可与 image 同用。参考图模式最高 720p。Console 的 grok-imagine-video 参考图模式最长 10 秒,reference_audios 还需相应团队权限。", noteVideoStrict: "视频接口严格使用当前官方字段,不保留旧项目的兼容别名。", noteVideoEditModel: "视频编辑与延长的实际路由必须指向 Console/grok-imagine-video;对外模型名可以自定义。", noteVideoBilling: "视频编辑与延长暂未返回可可靠结算的输入视频时长,因此保持可调用,并在请求审计中标记为未计费;不会消耗 API Key 的金额额度。", @@ -1730,20 +1731,21 @@ const resources = { fieldPrompt: "Natural-language instructions for image generation or editing.", 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. For video, grok-imagine-video supports 480p/720p and grok-imagine-video-1.5 also supports 1080p, but 1080p cannot be used for reference-to-video.", + fieldImageResolution: "Image output resolution. Supported values are 1k and 2k.", + fieldVideoResolution: "Video output resolution. Supported values are 480p and 720p; only the upstream grok-imagine-video-1.5 model supports 1080p, and only without reference images.", 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 in seconds. Text-to-video and first-frame image-to-video allow up to 15s. For reference-to-video, grok-imagine-video allows up to 10s and grok-imagine-video-1.5 up to 15s.", + fieldDuration: "Video duration in seconds, from 1 to 15. On Console routes, reference-to-video is limited to 10s with grok-imagine-video and 15s with grok-imagine-video-1.5.", fieldVideoImage: "Optional first-frame image reference for image-to-video generation. At most one image, and it cannot be combined with reference_images.", 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, up to 7 items. 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. The upstream team must have the capability enabled; otherwise upstream returns 403.", + fieldReferenceImages: "Optional reference image array for reference-to-video. The gateway accepts up to 8 items, while Console routes accept up to 7. 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. It can be used alone or with reference_images and may require upstream team entitlement; Console returns an upstream 403 when the capability is not enabled.", 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.", @@ -1761,7 +1763,7 @@ const resources = { 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, up to 7 items. A single item still keeps reference semantics and is not promoted to a first frame. Do not combine with image. Resolution tops out at 720p in reference mode, including grok-imagine-video-1.5. reference_audios accepts built-in voice_id values and requires team entitlement.", + noteVideoReference: "Reference-to-video uses /videos/generations with reference_images. A single item keeps reference semantics and is not promoted to a first frame. The gateway accepts up to 8 items and Console routes up to 7; do not combine them with image. Reference mode tops out at 720p. On Console, grok-imagine-video reference mode is limited to 10s and reference_audios also requires the corresponding team entitlement.", 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.", From 690b92cff394ddc238c7607261be74195bdecbc9 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Fri, 14 Aug 2026 09:46:48 +0800 Subject: [PATCH 31/48] fix: harden create-phase failover and prevent duplicate jobs --- backend/internal/application/gateway/video.go | 45 +++-- .../application/gateway/video_test.go | 169 +++++++++++++++++- backend/internal/infra/provider/cli/video.go | 32 ++-- .../internal/infra/provider/cli/video_test.go | 64 ++++++- .../infra/provider/console/console_test.go | 35 ++++ .../internal/infra/provider/console/media.go | 4 +- backend/internal/infra/provider/provider.go | 31 +++- .../infra/provider/video_stage_test.go | 28 +++ .../infra/provider/web/protocol_test.go | 52 ++++++ backend/internal/infra/provider/web/video.go | 20 ++- .../src/features/settings/settings-page.tsx | 4 +- 11 files changed, 429 insertions(+), 55 deletions(-) create mode 100644 backend/internal/infra/provider/video_stage_test.go diff --git a/backend/internal/application/gateway/video.go b/backend/internal/application/gateway/video.go index 0ff4012d..e6d837f0 100644 --- a/backend/internal/application/gateway/video.go +++ b/backend/internal/application/gateway/video.go @@ -452,6 +452,8 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model quotaRefreshGroup := s.providers.QuotaRefreshGroup(route.Provider, route.UpstreamModel) attemptPolicy := s.videoAttemptPolicy() excluded := make(map[uint64]bool) + forbiddenEgressRetried := make(map[uint64]bool) + var retryPinnedAccountID uint64 failureAttempts := newFailureAttemptRecorder(http.MethodPost, "/videos/generations") var selection *selectionSession var lease *accountLease @@ -467,10 +469,15 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model } // First try stays on the account chosen when the local job was created. // Create-stage failures may switch accounts; poll failures never reach here as retries. - if attempt == 0 && job.AccountID > 0 && !excluded[job.AccountID] { - lease, err = s.selector.AcquirePinned(ctx, route.Provider, job.AccountID, route.ID, route.UpstreamModel, quotaMode, true) + pinnedAccountID := retryPinnedAccountID + retryPinnedAccountID = 0 + if attempt == 0 { + pinnedAccountID = job.AccountID + } + if pinnedAccountID > 0 && !excluded[pinnedAccountID] { + lease, err = s.selector.AcquirePinned(ctx, route.Provider, pinnedAccountID, route.ID, route.UpstreamModel, quotaMode, true) if err != nil { - excluded[job.AccountID] = true + excluded[pinnedAccountID] = true lease = nil } } @@ -548,26 +555,29 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model failureHandled := false retriableCreate := false stage, hasStage := provider.VideoErrorStage(err) + safeCreateFailure := hasStage && stage == provider.VideoStageCreate status, hasStatus := provider.ErrorHTTPStatus(err) if errors.Is(err, provider.ErrUnauthorized) { if lease.Credential.AuthType == account.AuthTypeSSO { s.markSSOCredentialRejected(failureCtx, lease.Credential, fmt.Sprintf("%s SSO credential rejected", lease.Credential.Provider)) } failureHandled = true - retriableCreate = !hasStage || stage == provider.VideoStageCreate + retriableCreate = safeCreateFailure } else if hasStatus { switch { case status == http.StatusUnauthorized && lease.Credential.AuthType == account.AuthTypeSSO: s.markSSOCredentialRejected(failureCtx, lease.Credential, fmt.Sprintf("%s SSO credential rejected", lease.Credential.Provider)) failureHandled = true - retriableCreate = !hasStage || stage == provider.VideoStageCreate + retriableCreate = safeCreateFailure case status == http.StatusForbidden && s.providers.RetryForbiddenAsEgress(lease.Credential.Provider): - // Web anti-bot 403 is egress-scoped. Retry create on same account once via policy budget. + // Web anti-bot 403 is egress-scoped. Retry the same account once so + // egress invalidation can rebuild the route, then move on normally. failureHandled = true - if !hasStage || stage == provider.VideoStageCreate { - delete(excluded, lease.Credential.ID) - if selection != nil { - selection.RetryAccount(lease.Credential.ID) + if safeCreateFailure { + if !forbiddenEgressRetried[lease.Credential.ID] { + forbiddenEgressRetried[lease.Credential.ID] = true + retryPinnedAccountID = lease.Credential.ID + delete(excluded, lease.Credential.ID) } retriableCreate = true } @@ -576,7 +586,7 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model s.selector.MarkFailure(failureCtx, lease.Credential, status, 0) } failureHandled = true - retriableCreate = (!hasStage || stage == provider.VideoStageCreate) && !account.IsBuildSuper(lease.Credential, lease.Billing) + retriableCreate = safeCreateFailure && !account.IsBuildSuper(lease.Credential, lease.Billing) case (status == http.StatusPaymentRequired || status == http.StatusTooManyRequests) && lease.QuotaMode != "": exhausted, reconcileErr := s.accounts.ReconcileRateLimit(failureCtx, lease.Credential.ID, lease.QuotaMode, 0) s.selector.MarkQuotaStateChanged(lease.Credential.Provider, lease.Credential.ID) @@ -584,24 +594,25 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model s.selector.MarkFailure(failureCtx, lease.Credential, status, 0) } failureHandled = true - retriableCreate = !hasStage || stage == provider.VideoStageCreate + retriableCreate = safeCreateFailure case status == http.StatusTooManyRequests || status == http.StatusPaymentRequired: s.selector.MarkFailure(failureCtx, lease.Credential, status, 0) failureHandled = true - retriableCreate = !hasStage || stage == provider.VideoStageCreate + retriableCreate = safeCreateFailure case status >= http.StatusInternalServerError: - // 5xx is provider-level; keep the account and allow create-stage failover. + // A 5xx may be returned after the upstream accepted the job. Never + // switch accounts without an idempotency guarantee. failureHandled = true - retriableCreate = !hasStage || stage == provider.VideoStageCreate + retriableCreate = false default: s.selector.MarkFailure(failureCtx, lease.Credential, status, 0) failureHandled = true - retriableCreate = (!hasStage || stage == provider.VideoStageCreate) && status != http.StatusBadRequest && status != http.StatusUnprocessableEntity + retriableCreate = false } } if !failureHandled && !provider.IsMediaPostProcessingError(err) { s.selector.MarkFailure(failureCtx, lease.Credential, 0, 0) - retriableCreate = !hasStage || stage == provider.VideoStageCreate + retriableCreate = safeCreateFailure } failureCancel() applyMediaJobEgress(&job, egressTrace, route.Provider) diff --git a/backend/internal/application/gateway/video_test.go b/backend/internal/application/gateway/video_test.go index fc050300..403e6d34 100644 --- a/backend/internal/application/gateway/video_test.go +++ b/backend/internal/application/gateway/video_test.go @@ -9,15 +9,22 @@ import ( "io" "log/slog" "net/http" + "path/filepath" "strings" + "sync" "testing" "time" + accountapp "github.com/chenyme/grok2api/backend/internal/application/account" + clientkeyapp "github.com/chenyme/grok2api/backend/internal/application/clientkey" "github.com/chenyme/grok2api/backend/internal/domain/account" "github.com/chenyme/grok2api/backend/internal/domain/audit" + "github.com/chenyme/grok2api/backend/internal/domain/clientkey" "github.com/chenyme/grok2api/backend/internal/domain/media" "github.com/chenyme/grok2api/backend/internal/domain/model" + "github.com/chenyme/grok2api/backend/internal/infra/persistence/relational" "github.com/chenyme/grok2api/backend/internal/infra/provider" + "github.com/chenyme/grok2api/backend/internal/infra/runtime/memory" "github.com/chenyme/grok2api/backend/internal/repository" ) @@ -501,7 +508,6 @@ func (r *videoUsageRepository) MarkMediaJobUsageRecorded(_ context.Context, _ st return nil } - func TestResolveVideoAuditStatusCodePrefersUpstream429(t *testing.T) { status429 := http.StatusTooManyRequests job := media.Job{Status: media.StatusFailed, ErrorCode: "generation_failed", ErrorMessage: "Console 媒体上游返回 429: Too many requests"} @@ -542,3 +548,164 @@ func TestVideoAttemptPolicyStandaloneAndUnlimited(t *testing.T) { t.Fatalf("standalone policy = %#v", policy) } } + +type videoCreateFailoverAdapter struct { + mu sync.Mutex + failures map[uint64]int + status int + attempts []uint64 +} + +func (a *videoCreateFailoverAdapter) Provider() account.Provider { return account.ProviderWeb } + +func (a *videoCreateFailoverAdapter) Definition() provider.Definition { + definition := testConversationDefinition(account.ProviderWeb) + definition.Media.VideoGeneration = true + return definition +} + +func (a *videoCreateFailoverAdapter) GenerateVideo(_ context.Context, request provider.VideoRequest) (provider.VideoResult, error) { + a.mu.Lock() + a.attempts = append(a.attempts, request.Credential.ID) + remaining := a.failures[request.Credential.ID] + if remaining > 0 { + a.failures[request.Credential.ID] = remaining - 1 + } + a.mu.Unlock() + if remaining > 0 { + if a.status == 0 { + return provider.VideoResult{}, errors.New("unclassified create failure") + } + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, a.status, videoHTTPStatusError{status: a.status}) + } + return provider.VideoResult{AssetID: "video_asset_00001", ContentType: "video/mp4"}, nil +} + +func (a *videoCreateFailoverAdapter) Attempts() []uint64 { + a.mu.Lock() + defer a.mu.Unlock() + return append([]uint64(nil), a.attempts...) +} + +type videoHTTPStatusError struct{ status int } + +func (e videoHTTPStatusError) Error() string { return http.StatusText(e.status) } +func (e videoHTTPStatusError) HTTPStatusCode() int { return e.status } + +func TestVideoWebForbiddenRetriesPinnedAccountOnceThenFailsOver(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "video-retry.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) + mediaRepo := relational.NewMediaJobRepository(database) + keyRepo := relational.NewClientKeyRepository(database) + key, err := keyRepo.Create(ctx, clientkey.Key{ + Name: "video-test", Prefix: "video-test", SecretHash: strings.Repeat("a", 64), + EncryptedSecret: "encrypted", Enabled: true, RPMLimit: 60, MaxConcurrent: 4, + }) + if err != nil { + t.Fatal(err) + } + createAccount := func(name string, priority int) account.Credential { + credential, _, createErr := accountRepo.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderWeb, AuthType: account.AuthTypeSSO, WebTier: account.WebTierSuper, + Name: name, SourceKey: name, EncryptedAccessToken: name + "-token", ExpiresAt: time.Now().Add(time.Hour), + Enabled: true, AuthStatus: account.AuthStatusActive, Priority: priority, MaxConcurrent: 1, + }) + if createErr != nil { + t.Fatal(createErr) + } + return credential + } + first := createAccount("first", 200) + second := createAccount("second", 100) + if err := modelRepo.UpsertDiscovered(ctx, account.ProviderWeb, []string{"grok-imagine-video"}); err != nil { + t.Fatal(err) + } + for _, accountID := range []uint64{first.ID, second.ID} { + if err := modelRepo.ReplaceAccountCapabilities(ctx, accountID, []string{"grok-imagine-video"}, time.Now().UTC()); err != nil { + t.Fatal(err) + } + } + route, err := modelRepo.GetByProviderUpstream(ctx, account.ProviderWeb, "grok-imagine-video") + if err != nil { + t.Fatal(err) + } + + adapter := &videoCreateFailoverAdapter{ + failures: map[uint64]int{first.ID: 2}, + status: http.StatusForbidden, + } + registry := provider.NewRegistry(adapter) + sticky := memory.NewStickyStore() + accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil) + selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute) + service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(keyRepo, nil, nil, 60, 4, nil), registry, selector, nil, 3) + service.ConfigureMedia(mediaRepo, 1) + service.UpdateVideoMaxAttempts(10) + + now := time.Now().UTC() + job := media.Job{ + ID: "video_forbidden_retry", RequestID: "request-video-retry", ClientKeyID: key.ID, ClientKeyName: key.Name, + AccountID: first.ID, AccountName: first.Name, Provider: string(account.ProviderWeb), + Model: route.PublicID, ModelRouteID: route.ID, UpstreamModel: route.UpstreamModel, + Operation: provider.VideoOperationGenerate, Prompt: "test", Seconds: 5, Quality: "720p", + Status: media.StatusInProgress, InputJSON: `{}`, CreatedAt: now, UpdatedAt: now, + } + if err := mediaRepo.CreateMediaJob(ctx, job); err != nil { + t.Fatal(err) + } + service.runVideoJob(ctx, job, route) + + if attempts := adapter.Attempts(); len(attempts) != 3 || attempts[0] != first.ID || attempts[1] != first.ID || attempts[2] != second.ID { + t.Fatalf("video attempts = %#v, want first, first, second", attempts) + } + stored, err := mediaRepo.GetMediaJob(ctx, job.ID, job.ClientKeyID) + if err != nil { + t.Fatal(err) + } + if stored.Status != media.StatusCompleted || stored.AccountID != second.ID || stored.ResultAssetID != "video_asset_00001" { + t.Fatalf("completed job = %#v", stored) + } + + adapter.mu.Lock() + adapter.failures = map[uint64]int{first.ID: 1} + adapter.status = 0 + adapter.attempts = nil + adapter.mu.Unlock() + unknownJob := job + unknownJob.ID = "video_unclassified_failure" + unknownJob.RequestID = "request-video-unclassified" + unknownJob.AccountID = first.ID + unknownJob.AccountName = first.Name + unknownJob.Status = media.StatusInProgress + unknownJob.Progress = 0 + unknownJob.ResultAssetID = "" + unknownJob.ContentType = "" + unknownJob.CompletedAt = nil + unknownJob.CreatedAt = time.Now().UTC() + unknownJob.UpdatedAt = unknownJob.CreatedAt + if err := mediaRepo.CreateMediaJob(ctx, unknownJob); err != nil { + t.Fatal(err) + } + service.runVideoJob(ctx, unknownJob, route) + if attempts := adapter.Attempts(); len(attempts) != 1 || attempts[0] != first.ID { + t.Fatalf("unclassified failure attempts = %#v, want pinned account once", attempts) + } + stored, err = mediaRepo.GetMediaJob(ctx, unknownJob.ID, unknownJob.ClientKeyID) + if err != nil { + t.Fatal(err) + } + if stored.Status != media.StatusFailed || stored.AccountID != first.ID { + t.Fatalf("unclassified failed job = %#v", stored) + } +} diff --git a/backend/internal/infra/provider/cli/video.go b/backend/internal/infra/provider/cli/video.go index 18408cf9..9b97423a 100644 --- a/backend/internal/infra/provider/cli/video.go +++ b/backend/internal/infra/provider/cli/video.go @@ -20,11 +20,11 @@ import ( ) const ( - buildVideoModel = "grok-imagine-video-1.5" - xaiVideoModel = "grok-imagine-video-1.5-preview" + buildVideoModel = "grok-imagine-video-1.5" + xaiVideoModel = "grok-imagine-video-1.5-preview" // 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 + buildVideoMaxImages = mediadomain.MaxInputImages buildVideoPollEvery = 2 * time.Second buildVideoMaxBodySize = 2 << 20 buildVideoErrorSummaryLimit = 256 @@ -157,11 +157,11 @@ func boundDiagnosticText(value string, limit int) string { // 其他 auto Super 账号仅在当次 Build 创建返回 403 后探测 XAI。 func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoRequest) (provider.VideoResult, error) { if total := buildVideoImageCount(request); total > buildVideoMaxImages { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, fmt.Errorf("Build grok-imagine-video-1.5 最多支持 %d 张输入图,当前为 %d 张", buildVideoMaxImages, total)) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStagePrepare, 0, fmt.Errorf("Build grok-imagine-video-1.5 最多支持 %d 张输入图,当前为 %d 张", buildVideoMaxImages, total)) } accessToken, err := a.cipher.Decrypt(request.Credential.EncryptedAccessToken) if err != nil { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStagePrepare, 0, err) } credential := request.Credential routeMode := normalizedBuildRouteMode(credential) @@ -173,17 +173,17 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque primaryBase := a.primaryBaseURL() payload, err := videoCreatePayload(request, "", buildVideoRequestProfile) if err != nil { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStagePrepare, 0, err) } body, err := json.Marshal(payload) if err != nil { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStagePrepare, 0, err) } createResp, createErr := a.doVideoJSON(ctx, credential, accessToken, http.MethodPost, primaryBase, "/videos/generations", body, buildVideoRequestProfile, true) if createErr == nil { jobID, parseErr := parseVideoCreateResponse(createResp) if parseErr != nil { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, parseErr) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageSubmitted, 0, parseErr) } if request.Progress != nil { request.Progress(1) @@ -192,10 +192,10 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque } var upstream *videoUpstreamError if !asVideoUpstreamError(createErr, &upstream) || !isHTTPForbidden(upstream.status) { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, createErr) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoCreateFailureStage(createErr), 0, createErr) } if routeMode == account.BuildRouteBuild || !xaiEligible { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, createErr) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoCreateFailureStage(createErr), 0, createErr) } // 已确认 Super 的主地址 403:签发 upload_url 后探测 XAI;创建成功才标记降级。 return a.generateVideoOnXAI(ctx, request, credential, accessToken, true) @@ -204,7 +204,7 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque func (a *Adapter) generateVideoOnXAI(ctx context.Context, request provider.VideoRequest, credential account.Credential, accessToken string, recordFallback bool) (provider.VideoResult, error) { issuer := a.uploadIssuerRef() if issuer == nil { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, fmt.Errorf("XAI 视频需要媒体上传接收服务")) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStagePrepare, 0, fmt.Errorf("XAI 视频需要媒体上传接收服务")) } jobKey := strings.TrimSpace(request.JobID) if jobKey == "" { @@ -213,25 +213,25 @@ func (a *Adapter) generateVideoOnXAI(ctx context.Context, request provider.Video uploadURL, assetID, err := issuer.IssueVideoUpload(ctx, jobKey) if err != nil { // 配置错误(例如 PublicAPIBaseURL 不可用)不得误标降级。 - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStagePrepare, 0, err) } payload, err := videoCreatePayload(request, uploadURL, xaiVideoRequestProfile) if err != nil { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStagePrepare, 0, err) } body, err := json.Marshal(payload) if err != nil { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStagePrepare, 0, err) } base := a.fallbackBaseURL() createResp, err := a.doVideoJSON(ctx, credential, accessToken, http.MethodPost, base, "/videos/generations", body, xaiVideoRequestProfile, true) if err != nil { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoCreateFailureStage(err), 0, err) } // 必须先解析到可用 job ID,再标记降级;畸形 2xx 不得激活或本地置位。 jobID, err := parseVideoCreateResponse(createResp) if err != nil { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageSubmitted, 0, err) } if recordFallback { a.activateBuildAPIFallback(ctx, &credential) diff --git a/backend/internal/infra/provider/cli/video_test.go b/backend/internal/infra/provider/cli/video_test.go index b24c935a..30ad19c9 100644 --- a/backend/internal/infra/provider/cli/video_test.go +++ b/backend/internal/infra/provider/cli/video_test.go @@ -187,12 +187,12 @@ func TestBuildVideoCreatePayloadRejectsImageWithReferences(t *testing.T) { 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"}, + 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) @@ -210,7 +210,6 @@ func TestBuildVideoCreatePayloadReferenceAudios(t *testing.T) { } } - func TestGenerateVideoRejectsTooManyImagesBeforeUpstream(t *testing.T) { adapter, encrypted := newTestBuildVideoAdapter(t) var hits atomic.Int32 @@ -607,6 +606,57 @@ func TestGenerateVideoRespectsContextCancelDuringPoll(t *testing.T) { } } +func TestBuildVideoCreateFailureStagesPreserveRetrySafety(t *testing.T) { + tests := []struct { + name string + transport func(*http.Request) (*http.Response, error) + wantStage provider.VideoStage + }{ + { + name: "transport result unknown", + transport: func(*http.Request) (*http.Response, error) { + return nil, errors.New("connection reset after request write") + }, + wantStage: provider.VideoStageSubmitted, + }, + { + name: "malformed successful response", + transport: func(request *http.Request) (*http.Response, error) { + return jsonResponse(http.StatusOK, `{"status":"queued"}`, request), nil + }, + wantStage: provider.VideoStageSubmitted, + }, + { + name: "explicit rate limit rejection", + transport: func(request *http.Request) (*http.Response, error) { + return jsonResponse(http.StatusTooManyRequests, `{"error":"rate limited"}`, request), nil + }, + wantStage: provider.VideoStageCreate, + }, + { + name: "server failure result unknown", + transport: func(request *http.Request) (*http.Response, error) { + return jsonResponse(http.StatusInternalServerError, `{"error":"failed"}`, request), nil + }, + wantStage: provider.VideoStageSubmitted, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + adapter, encrypted := newTestBuildVideoAdapter(t) + adapter.http.Transport = roundTripFunc(test.transport) + _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted}, + Prompt: "test", Duration: 5, + }) + stage, ok := provider.VideoErrorStage(err) + if !ok || stage != test.wantStage { + t.Fatalf("stage = %q, ok=%t, err=%v; want %q", stage, ok, err, test.wantStage) + } + }) + } +} + func TestRegistryExposesBuildVideoAdapter(t *testing.T) { registry := provider.NewRegistry(NewAdapter(Config{}, nil)) adapter, ok := registry.Videos(account.ProviderBuild) diff --git a/backend/internal/infra/provider/console/console_test.go b/backend/internal/infra/provider/console/console_test.go index 22658cfe..eee5f7ef 100644 --- a/backend/internal/infra/provider/console/console_test.go +++ b/backend/internal/infra/provider/console/console_test.go @@ -1588,6 +1588,41 @@ func TestConsoleVideoCreatesAndPollsStandardResources(t *testing.T) { } } +func TestConsoleVideoCreateFailureStagesPreserveRetrySafety(t *testing.T) { + tests := []struct { + name string + status int + body string + wantStage provider.VideoStage + }{ + {name: "malformed successful response", status: http.StatusOK, body: `{"status":"queued"}`, wantStage: provider.VideoStageSubmitted}, + {name: "explicit rate limit rejection", status: http.StatusTooManyRequests, body: `{"error":"rate limited"}`, wantStage: provider.VideoStageCreate}, + {name: "server failure result unknown", status: http.StatusInternalServerError, body: `{"error":"failed"}`, wantStage: provider.VideoStageSubmitted}, + } + for _, test := range tests { + t.Run(test.name, func(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") + writer.WriteHeader(test.status) + _, _ = io.WriteString(writer, test.body) + })) + t.Cleanup(server.Close) + adapter, credential := newConsoleTestAdapter(t, server.URL) + _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Model: "grok-imagine-video", Prompt: "test", Duration: 5, Resolution: "720p", + }) + stage, ok := provider.VideoErrorStage(err) + if !ok || stage != test.wantStage { + t.Fatalf("stage = %q, ok=%t, err=%v; want %q", stage, ok, err, test.wantStage) + } + }) + } +} + func TestConsoleVideoPostsReferenceImages(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { if serveTestDPoPToken(t, writer, request) { diff --git a/backend/internal/infra/provider/console/media.go b/backend/internal/infra/provider/console/media.go index 1f284bec..cd0c3b65 100644 --- a/backend/internal/infra/provider/console/media.go +++ b/backend/internal/infra/provider/console/media.go @@ -611,11 +611,11 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque } created, err := a.doConsoleVideoJSON(ctx, request.Credential, token, lease, http.MethodPost, consoleV1Endpoint(baseURL, createPath), body) if err != nil { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoCreateFailureStage(err), 0, err) } requestID, err := parseConsoleVideoCreate(created) if err != nil { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageSubmitted, 0, err) } if request.Progress != nil { request.Progress(1) diff --git a/backend/internal/infra/provider/provider.go b/backend/internal/infra/provider/provider.go index 5405fb38..9e882970 100644 --- a/backend/internal/infra/provider/provider.go +++ b/backend/internal/infra/provider/provider.go @@ -67,12 +67,23 @@ func ErrorHTTPStatus(err error) (int, bool) { type VideoStage string const ( + // VideoStagePrepare is local work performed before the create request is sent. + // It is not account-failover eligible because retrying deterministic local + // validation or configuration failures against another credential is useless. + VideoStagePrepare VideoStage = "prepare" + // VideoStageCreate means the upstream explicitly rejected the create request. + // Account failover is safe only for the retryable 4xx statuses selected by + // the gateway; 5xx responses remain indeterminate because work may already + // have been accepted before the server failed. VideoStageCreate VideoStage = "create" - VideoStagePoll VideoStage = "poll" + // VideoStageSubmitted means the create request may have reached upstream but + // no usable job identifier was obtained. Retrying could duplicate work. + VideoStageSubmitted VideoStage = "submitted" + VideoStagePoll VideoStage = "poll" ) -// VideoStageError marks whether a video failure happened before the upstream -// job was created (safe to switch accounts) or while polling an existing job. +// VideoStageError records the asynchronous video phase without treating every +// create-path error as safe for account failover. type VideoStageError struct { Stage VideoStage Status int @@ -127,6 +138,20 @@ func VideoErrorStage(err error) (VideoStage, bool) { return stageErr.Stage, true } +// VideoCreateFailureStage distinguishes an explicit upstream rejection from an +// indeterminate POST result. Explicit 4xx responses (including the 401 +// sentinel) are rejections; transport errors and 5xx responses remain +// submitted because the upstream may already have accepted the job. +func VideoCreateFailureStage(err error) VideoStage { + if errors.Is(err, ErrUnauthorized) { + return VideoStageCreate + } + if status, ok := ErrorHTTPStatus(err); ok && status >= http.StatusBadRequest && status < http.StatusInternalServerError { + return VideoStageCreate + } + return VideoStageSubmitted +} + // WrapVideoStage annotates err with the video phase and optional HTTP status. func WrapVideoStage(stage VideoStage, status int, err error) error { if err == nil { diff --git a/backend/internal/infra/provider/video_stage_test.go b/backend/internal/infra/provider/video_stage_test.go new file mode 100644 index 00000000..b6b26df3 --- /dev/null +++ b/backend/internal/infra/provider/video_stage_test.go @@ -0,0 +1,28 @@ +package provider + +import ( + "errors" + "fmt" + "net/http" + "testing" +) + +type videoStageStatusError struct{ status int } + +func (e videoStageStatusError) Error() string { return http.StatusText(e.status) } +func (e videoStageStatusError) HTTPStatusCode() int { return e.status } + +func TestVideoCreateFailureStageIsFailClosed(t *testing.T) { + if stage := VideoCreateFailureStage(errors.New("connection reset after write")); stage != VideoStageSubmitted { + t.Fatalf("transport failure stage = %q", stage) + } + if stage := VideoCreateFailureStage(fmt.Errorf("wrapped: %w", videoStageStatusError{status: http.StatusTooManyRequests})); stage != VideoStageCreate { + t.Fatalf("explicit 429 stage = %q", stage) + } + if stage := VideoCreateFailureStage(ErrUnauthorized); stage != VideoStageCreate { + t.Fatalf("explicit unauthorized stage = %q", stage) + } + if stage := VideoCreateFailureStage(videoStageStatusError{status: http.StatusInternalServerError}); stage != VideoStageSubmitted { + t.Fatalf("explicit 500 stage = %q", stage) + } +} diff --git a/backend/internal/infra/provider/web/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index 2377d375..5562bb7e 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -1436,6 +1436,58 @@ func TestParseVideoStreamPreservesUpstreamStatus(t *testing.T) { } } +func TestGenerateVideoClassifiesOnlyExplicitHTTPRejectionAsCreateFailure(t *testing.T) { + status := http.StatusOK + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + writer.Header().Set("Content-Type", "application/json") + switch request.URL.Path { + case "/rest/media/post/create": + _, _ = io.WriteString(writer, `{"post":{"id":"post_1"}}`) + case "/rest/app-chat/conversations/new": + writer.WriteHeader(status) + if status == http.StatusOK { + _, _ = io.WriteString(writer, `{}`) + } else { + _, _ = io.WriteString(writer, `{"error":"rate limited"}`) + } + default: + writer.WriteHeader(http.StatusNotFound) + } + })) + defer server.Close() + + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + encryptedToken, err := cipher.Encrypt("test-sso") + if err != nil { + t.Fatal(err) + } + manager := infraegress.NewManager(egressRepositoryStub{}, cipher) + adapter := NewAdapter(Config{BaseURL: server.URL, StatsigMode: "manual", StatsigManualValue: "test"}, manager, cipher, nil, nil) + request := provider.VideoRequest{ + Credential: account.Credential{ID: 1, Provider: account.ProviderWeb, EncryptedAccessToken: encryptedToken}, + Prompt: "test", + Duration: 5, + } + + _, err = adapter.GenerateVideo(context.Background(), request) + if stage, ok := provider.VideoErrorStage(err); !ok || stage != provider.VideoStagePoll { + t.Fatalf("successful response without a completed video stage = %q, ok=%t, err=%v", stage, ok, err) + } + status = http.StatusTooManyRequests + _, err = adapter.GenerateVideo(context.Background(), request) + if stage, ok := provider.VideoErrorStage(err); !ok || stage != provider.VideoStageCreate { + t.Fatalf("explicit HTTP rejection stage = %q, ok=%t, err=%v", stage, ok, err) + } + status = http.StatusInternalServerError + _, err = adapter.GenerateVideo(context.Background(), request) + if stage, ok := provider.VideoErrorStage(err); !ok || stage != provider.VideoStageSubmitted { + t.Fatalf("server failure stage = %q, ok=%t, err=%v", stage, ok, err) + } +} + func TestParseVideoConcatenatedJSONFixture(t *testing.T) { fixture := `{"result":{"conversation":{"conversationId":"conversation_1"}}}` + `{"result":{"response":{"streamingVideoGenerationResponse":{"videoId":"video_1","progress":1,"videoPostId":"post_1","resolutionName":"720p"}}}}` + diff --git a/backend/internal/infra/provider/web/video.go b/backend/internal/infra/provider/web/video.go index 82330a98..39e90d74 100644 --- a/backend/internal/infra/provider/web/video.go +++ b/backend/internal/infra/provider/web/video.go @@ -211,11 +211,11 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque cfg := a.config() token, err := a.cipher.Decrypt(request.Credential.EncryptedAccessToken) if err != nil { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStagePrepare, 0, err) } lease, err := a.egress.AcquireCredential(ctx, domainegress.ScopeWeb, request.Credential) if err != nil { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStagePrepare, 0, err) } defer lease.Release() parentID := "" @@ -232,7 +232,7 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque for _, rawReference := range rawReferences { reference, referenceErr := a.prepareVideoReference(ctx, cfg, lease, token, rawReference) if referenceErr != nil { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, referenceErr) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoCreateFailureStage(referenceErr), 0, referenceErr) } references = append(references, reference) } @@ -242,11 +242,11 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque parentID, err = a.createMediaPost(ctx, cfg, lease, token, "MEDIA_POST_TYPE_VIDEO", "", request.Prompt, "video_prompt_media_post") } if err != nil { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoCreateFailureStage(err), 0, err) } segments := videoSegments(request.Duration) if len(segments) == 0 { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, fmt.Errorf("duration 必须在 1 到 15 秒之间")) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStagePrepare, 0, fmt.Errorf("duration 必须在 1 到 15 秒之间")) } ratio := resolveAspectRatio(request.AspectRatio) resolution := request.Resolution @@ -256,7 +256,7 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque payload := videoCreatePayload(request.Prompt, parentID, ratio, resolution, segments[0], references) response, err := a.postJSON(ctx, cfg, lease, token, cfg.BaseURL+"/rest/app-chat/conversations/new", payload, time.Duration(cfg.VideoTimeoutSeconds)*time.Second) if err != nil { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, err) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoCreateFailureStage(err), 0, err) } result, _, parseErr := parseVideoStream(response, request.Progress) _ = response.Body.Close() @@ -264,10 +264,14 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque if upstreamErr, ok := parseErr.(*webMediaUpstreamError); ok { a.logWebMediaUpstreamRejection("video_generation", response, upstreamErr) } - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, parseErr) + stage := provider.VideoStagePoll + if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices { + stage = provider.VideoCreateFailureStage(parseErr) + } + return provider.VideoResult{}, provider.WrapVideoStage(stage, 0, parseErr) } if result.URL == "" { - return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStageCreate, 0, fmt.Errorf("视频生成完成但没有返回内容 URL")) + return provider.VideoResult{}, provider.WrapVideoStage(provider.VideoStagePoll, 0, fmt.Errorf("视频生成完成但没有返回内容 URL")) } return result, nil } diff --git a/frontend/src/features/settings/settings-page.tsx b/frontend/src/features/settings/settings-page.tsx index 33e5a04a..c88919d9 100644 --- a/frontend/src/features/settings/settings-page.tsx +++ b/frontend/src/features/settings/settings-page.tsx @@ -27,6 +27,7 @@ export function SettingsPage() { const [autoCleanConfirm, setAutoCleanConfirm] = useState<"enabled" | "includeDisabled" | null>(null); const [unlimitedAttemptsConfirm, setUnlimitedAttemptsConfirm] = useState(false); const limitedRoutingAttemptsRef = useRef(3); + const limitedVideoRoutingAttemptsRef = useRef(999); const autoCleanEnabled = form.watch("accounts.autoCleanReauthEnabled") === true; const buildForbiddenReauthEnabled = form.watch("accounts.markBuildForbiddenReauth") === true; const segmentedSelectorEnabled = form.watch("routing.segmentedSelector.enabled") === true; @@ -299,10 +300,11 @@ export function SettingsPage() { checked={unlimited} onCheckedChange={(checked) => { if (checked) { + if (field.value > 0) limitedVideoRoutingAttemptsRef.current = field.value; field.onChange(UNLIMITED_ROUTING_ATTEMPTS); return; } - field.onChange(limitedRoutingAttemptsRef.current > 0 ? limitedRoutingAttemptsRef.current : 999); + field.onChange(limitedVideoRoutingAttemptsRef.current); }} />
From 8a16931e1ffd8ba05c94093c4ba479d02d20a9e5 Mon Sep 17 00:00:00 2001 From: WuxiVIP Date: Fri, 14 Aug 2026 09:51:35 +0800 Subject: [PATCH 32/48] fix(frontend): make LAN key copy reliable Write fallback clipboard data through the copy event instead of relying on focus for an off-screen textarea. This keeps copying reliable inside focus-trapped dialogs on insecure LAN origins and avoids false success states.\n\nFixes #913 --- frontend/src/shared/clipboard.ts | 83 +++++++++++++++++--------------- 1 file changed, 44 insertions(+), 39 deletions(-) diff --git a/frontend/src/shared/clipboard.ts b/frontend/src/shared/clipboard.ts index 7ef5cb86..9a408b69 100644 --- a/frontend/src/shared/clipboard.ts +++ b/frontend/src/shared/clipboard.ts @@ -20,50 +20,55 @@ export async function copyToClipboard(text: string): Promise { // programmatically when the async Clipboard API is unavailable. function legacyCopy(text: string): boolean { if (typeof document === "undefined" || !document.body) return false; - const textarea = document.createElement("textarea"); - textarea.value = text; - textarea.setAttribute("readonly", ""); - textarea.setAttribute("aria-hidden", "true"); - textarea.style.position = "fixed"; - textarea.style.top = "0"; - textarea.style.left = "-9999px"; - textarea.style.width = "1em"; - textarea.style.height = "1em"; - // A large font keeps iOS Safari from zooming the page and lets the - // selection persist on the programmatically created element. - textarea.style.fontSize = "2em"; - textarea.style.padding = "0"; - textarea.style.border = "none"; - textarea.style.outline = "none"; - textarea.style.boxShadow = "none"; - textarea.style.background = "transparent"; - textarea.style.opacity = "0"; - textarea.style.pointerEvents = "none"; + const copyTarget = document.createElement("span"); + copyTarget.textContent = text; + copyTarget.setAttribute("aria-hidden", "true"); + copyTarget.style.position = "fixed"; + copyTarget.style.top = "0"; + copyTarget.style.left = "0"; + copyTarget.style.width = "1px"; + copyTarget.style.height = "1px"; + copyTarget.style.overflow = "hidden"; + copyTarget.style.clipPath = "inset(50%)"; + copyTarget.style.whiteSpace = "pre"; + copyTarget.style.userSelect = "text"; - const activeElement = document.activeElement as Element | null; + const activeElement = document.activeElement; const selection = document.getSelection(); - let savedRange: Range | null = null; - if (selection && selection.rangeCount > 0) savedRange = selection.getRangeAt(0); + const savedRanges = selection + ? Array.from({ length: selection.rangeCount }, (_, index) => selection.getRangeAt(index).cloneRange()) + : []; - document.body.appendChild(textarea); - textarea.focus({ preventScroll: true }); - textarea.select(); - textarea.setSelectionRange(0, text.length); + document.body.appendChild(copyTarget); + const range = document.createRange(); + range.selectNodeContents(copyTarget); + selection?.removeAllRanges(); + selection?.addRange(range); - let ok = false; + // Focus-trapped dialogs can steal focus from a hidden form control. Supply + // the value on the copy event so the selected text is only a compatibility + // fallback and cannot change what reaches the clipboard. + let clipboardDataWritten = false; + const handleCopy = (event: ClipboardEvent) => { + if (!event.clipboardData) return; + event.preventDefault(); + event.clipboardData.clearData(); + event.clipboardData.setData("text/plain", text); + clipboardDataWritten = true; + }; + document.addEventListener("copy", handleCopy, { capture: true, once: true }); + + let commandSucceeded = false; try { - ok = document.execCommand("copy"); + commandSucceeded = document.execCommand("copy"); } catch { - // execCommand may throw in restricted environments; ok stays false. + // execCommand may throw in restricted environments. + } finally { + document.removeEventListener("copy", handleCopy, true); + copyTarget.remove(); + selection?.removeAllRanges(); + for (const savedRange of savedRanges) selection?.addRange(savedRange); + if (activeElement instanceof HTMLElement) activeElement.focus({ preventScroll: true }); } - - document.body.removeChild(textarea); - if (savedRange && selection) { - selection.removeAllRanges(); - selection.addRange(savedRange); - } - if (activeElement instanceof HTMLElement && typeof activeElement.focus === "function") { - activeElement.focus(); - } - return ok; + return commandSucceeded && clipboardDataWritten; } From 2b1f53ce9f39b4d62c0ae8dca4a8c6f433109594 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Fri, 14 Aug 2026 09:58:29 +0800 Subject: [PATCH 33/48] fix: unify safe video download filenames and extensions --- backend/internal/infra/media/local_store.go | 19 ++------ backend/internal/pkg/mediafile/video.go | 48 +++++++++++++++++++ backend/internal/pkg/mediafile/video_test.go | 38 +++++++++++++++ .../transport/http/inference/handler.go | 43 +---------------- .../transport/http/inference/handler_test.go | 14 ------ .../internal/transport/http/media/handler.go | 18 +------ .../transport/http/media/handler_test.go | 7 +-- 7 files changed, 98 insertions(+), 89 deletions(-) create mode 100644 backend/internal/pkg/mediafile/video.go create mode 100644 backend/internal/pkg/mediafile/video_test.go diff --git a/backend/internal/infra/media/local_store.go b/backend/internal/infra/media/local_store.go index d195cb2b..58d1625e 100644 --- a/backend/internal/infra/media/local_store.go +++ b/backend/internal/infra/media/local_store.go @@ -9,6 +9,8 @@ import ( "os" "path/filepath" "strings" + + "github.com/chenyme/grok2api/backend/internal/pkg/mediafile" ) // LocalStore 将媒体对象限制在单一根目录内,并使用临时文件与原子硬链接完成提交。 @@ -35,7 +37,7 @@ func (s *LocalStore) SaveImage(ctx context.Context, id, mimeType string, data [] // SaveVideo 将视频对象写入 videos/ 子目录,提交语义与图片一致(原子硬链接、no-replace)。 func (s *LocalStore) SaveVideo(ctx context.Context, id, mimeType string, data []byte) (string, error) { - return s.saveObject(ctx, "videos", ".video-*", id, mimeType, data, videoExtension) + return s.saveObject(ctx, "videos", ".video-*", id, mimeType, data, mediafile.VideoExtension) } // BeginVideoUpload 创建视频临时文件,供流式限长写入后 CommitVideoUpload 提交。 @@ -43,7 +45,7 @@ func (s *LocalStore) BeginVideoUpload(ctx context.Context, id, mimeType string) if err := ctx.Err(); err != nil { return "", "", err } - extension, ok := videoExtension(mimeType) + extension, ok := mediafile.VideoExtension(mimeType) if !ok || len(id) < 2 { return "", "", fmt.Errorf("视频存储参数无效") } @@ -236,16 +238,3 @@ func imageExtension(mimeType string) (string, bool) { return "", false } } - -func videoExtension(mimeType string) (string, bool) { - switch strings.ToLower(strings.TrimSpace(mimeType)) { - case "video/mp4": - return ".mp4", true - case "video/webm": - return ".webm", true - case "video/quicktime": - return ".mov", true - default: - return "", false - } -} diff --git a/backend/internal/pkg/mediafile/video.go b/backend/internal/pkg/mediafile/video.go new file mode 100644 index 00000000..a0dcb742 --- /dev/null +++ b/backend/internal/pkg/mediafile/video.go @@ -0,0 +1,48 @@ +package mediafile + +import ( + "mime" + "strings" +) + +// VideoExtension returns the canonical file extension for a supported video +// media type. Parameters such as codecs are ignored when selecting the suffix. +func VideoExtension(contentType string) (string, bool) { + mediaType, _, err := mime.ParseMediaType(strings.TrimSpace(contentType)) + if err != nil { + return "", false + } + switch strings.ToLower(mediaType) { + case "video/mp4": + return ".mp4", true + case "video/webm": + return ".webm", true + case "video/quicktime": + return ".mov", true + default: + return "", false + } +} + +// VideoContentDisposition builds a safe inline filename for video responses. +// Public request and asset identifiers are restricted to a conservative ASCII +// subset before they are placed in an HTTP response header. +func VideoContentDisposition(name, contentType string) string { + name = strings.Map(func(r rune) rune { + switch { + case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9': + return r + case r == '-', r == '_': + return r + default: + return -1 + } + }, strings.TrimSpace(name)) + if name == "" { + name = "video" + } + if extension, ok := VideoExtension(contentType); ok { + name += extension + } + return `inline; filename="` + name + `"` +} diff --git a/backend/internal/pkg/mediafile/video_test.go b/backend/internal/pkg/mediafile/video_test.go new file mode 100644 index 00000000..2cd5b4e0 --- /dev/null +++ b/backend/internal/pkg/mediafile/video_test.go @@ -0,0 +1,38 @@ +package mediafile + +import "testing" + +func TestVideoExtension(t *testing.T) { + for _, testCase := range []struct { + contentType string + want string + ok bool + }{ + {contentType: "video/mp4", want: ".mp4", ok: true}, + {contentType: "video/webm; codecs=vp9", want: ".webm", ok: true}, + {contentType: "VIDEO/QUICKTIME", want: ".mov", ok: true}, + {contentType: "application/octet-stream"}, + {contentType: "video/mp4; invalid"}, + } { + got, ok := VideoExtension(testCase.contentType) + if got != testCase.want || ok != testCase.ok { + t.Errorf("VideoExtension(%q) = %q, %v; want %q, %v", testCase.contentType, got, ok, testCase.want, testCase.ok) + } + } +} + +func TestVideoContentDispositionSanitizesName(t *testing.T) { + for _, testCase := range []struct { + name string + contentType string + want string + }{ + {name: `bad"name; drop`, contentType: "video/mp4", want: `inline; filename="badnamedrop.mp4"`}, + {name: " ", contentType: "video/mp4", want: `inline; filename="video.mp4"`}, + {name: "video_request_1", contentType: "application/octet-stream", want: `inline; filename="video_request_1"`}, + } { + if got := VideoContentDisposition(testCase.name, testCase.contentType); got != testCase.want { + t.Errorf("VideoContentDisposition(%q, %q) = %q, want %q", testCase.name, testCase.contentType, got, testCase.want) + } + } +} diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index 490144ff..f6310d6e 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -23,6 +23,7 @@ import ( 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/mediafile" "github.com/chenyme/grok2api/backend/internal/pkg/neterror" "github.com/chenyme/grok2api/backend/internal/transport/http/middleware" "github.com/gin-gonic/gin" @@ -948,7 +949,7 @@ func writeVideoContent(c *gin.Context, body io.Reader, contentType string, size return } // Clients that save the response need an extension to get a playable file. - c.Header("Content-Disposition", videoContentDisposition(downloadName, contentType)) + c.Header("Content-Disposition", mediafile.VideoContentDisposition(downloadName, contentType)) c.Header("Cache-Control", "private, no-store") c.Header("X-Content-Type-Options", "nosniff") c.Header("Content-Security-Policy", "default-src 'none'; sandbox") @@ -967,46 +968,6 @@ func writeVideoContent(c *gin.Context, body io.Reader, contentType string, size } } -// videoContentDisposition names the download after the request and appends the -// extension implied by the response content type, so saved files stay playable. -func videoContentDisposition(name, contentType string) string { - name = strings.Map(func(r rune) rune { - switch { - case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9': - return r - case r == '-', r == '_': - return r - default: - return -1 - } - }, strings.TrimSpace(name)) - if name == "" { - name = "video" - } - if extension, ok := videoFileExtension(contentType); ok { - name += extension - } - return `inline; filename="` + name + `"` -} - -// videoFileExtension mirrors the extensions used by the media object store. -func videoFileExtension(contentType string) (string, bool) { - mediaType, _, err := mime.ParseMediaType(strings.TrimSpace(contentType)) - if err != nil { - return "", false - } - switch strings.ToLower(mediaType) { - case "video/mp4": - return ".mp4", true - case "video/webm": - return ".webm", true - case "video/quicktime": - return ".mov", true - default: - return "", false - } -} - func normalizeVideoResponseContentType(value string) (string, bool) { mediaType, _, err := mime.ParseMediaType(strings.TrimSpace(value)) if err != nil { diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go index 0a7b5686..0d27f278 100644 --- a/backend/internal/transport/http/inference/handler_test.go +++ b/backend/internal/transport/http/inference/handler_test.go @@ -145,20 +145,6 @@ func TestWriteVideoContentNamesDownloadWithExtension(t *testing.T) { } } -// Request IDs reach the header, so anything outside [A-Za-z0-9_-] is dropped and an -// empty result falls back to a fixed name. -func TestVideoContentDispositionSanitizesName(t *testing.T) { - if got := videoContentDisposition(`bad"name; drop`, "video/mp4"); got != `inline; filename="badnamedrop.mp4"` { - t.Fatalf("sanitized disposition = %q", got) - } - if got := videoContentDisposition(" ", "video/mp4"); got != `inline; filename="video.mp4"` { - t.Fatalf("fallback disposition = %q", got) - } - if got := videoContentDisposition("video_request_1", "application/octet-stream"); got != `inline; filename="video_request_1"` { - t.Fatalf("unknown type disposition = %q", got) - } -} - func TestVideoContentURLUsesConfiguredPublicAPIBase(t *testing.T) { handler := NewHandler(nil, nil, 1<<20, "https://api.example.com/grok2api/") response := videoGenerationResponse(mediadomain.Job{ID: "video_request_1", Status: mediadomain.StatusCompleted, UpstreamURL: "https://assets.grok.com/source.mp4"}, handler.videoContentURL("video_request_1")) diff --git a/backend/internal/transport/http/media/handler.go b/backend/internal/transport/http/media/handler.go index dbc29e78..dfbd494e 100644 --- a/backend/internal/transport/http/media/handler.go +++ b/backend/internal/transport/http/media/handler.go @@ -8,6 +8,7 @@ import ( "strings" mediaapp "github.com/chenyme/grok2api/backend/internal/application/media" + "github.com/chenyme/grok2api/backend/internal/pkg/mediafile" "github.com/chenyme/grok2api/backend/internal/repository" "github.com/chenyme/grok2api/backend/internal/shared/response" "github.com/gin-gonic/gin" @@ -82,21 +83,6 @@ func (h *Handler) getImage(c *gin.Context) { _, _ = io.Copy(c.Writer, body) } -// videoContentDisposition appends the extension implied by the stored MIME type so -// saved files stay playable; the media object store uses the same mapping. -func videoContentDisposition(assetID, mimeType string) string { - name := assetID - switch strings.ToLower(strings.TrimSpace(mimeType)) { - case "video/mp4": - name += ".mp4" - case "video/webm": - name += ".webm" - case "video/quicktime": - name += ".mov" - } - return `inline; filename="` + name + `"` -} - func (h *Handler) getVideo(c *gin.Context) { asset, body, err := h.service.OpenVideo(c.Request.Context(), c.Param("assetId")) if errors.Is(err, mediaapp.ErrAssetNotFound) { @@ -114,7 +100,7 @@ func (h *Handler) getVideo(c *gin.Context) { return } c.Header("Content-Type", asset.MIMEType) - c.Header("Content-Disposition", videoContentDisposition(asset.ID, asset.MIMEType)) + c.Header("Content-Disposition", mediafile.VideoContentDisposition(asset.ID, asset.MIMEType)) c.Header("Cache-Control", "public, max-age=31536000, immutable") c.Header("ETag", `"`+asset.SHA256+`"`) c.Header("X-Content-Type-Options", "nosniff") diff --git a/backend/internal/transport/http/media/handler_test.go b/backend/internal/transport/http/media/handler_test.go index 37b86296..a94725a1 100644 --- a/backend/internal/transport/http/media/handler_test.go +++ b/backend/internal/transport/http/media/handler_test.go @@ -97,19 +97,20 @@ func TestPublicVideoAssetSupportsGetHeadAndRange(t *testing.T) { get := httptest.NewRecorder() router.ServeHTTP(get, httptest.NewRequest(http.MethodGet, path, nil)) - if get.Code != http.StatusOK || get.Body.Len() != len(payload) || get.Header().Get("Content-Type") != "video/mp4" || get.Header().Get("ETag") == "" { + wantDisposition := `inline; filename="` + asset.ID + `.mp4"` + if get.Code != http.StatusOK || get.Body.Len() != len(payload) || get.Header().Get("Content-Type") != "video/mp4" || get.Header().Get("Content-Disposition") != wantDisposition || get.Header().Get("ETag") == "" { t.Fatalf("GET status=%d size=%d headers=%#v", get.Code, get.Body.Len(), get.Header()) } head := httptest.NewRecorder() router.ServeHTTP(head, httptest.NewRequest(http.MethodHead, path, nil)) - if head.Code != http.StatusOK || head.Body.Len() != 0 || head.Header().Get("Content-Length") == "" { + if head.Code != http.StatusOK || head.Body.Len() != 0 || head.Header().Get("Content-Length") == "" || head.Header().Get("Content-Disposition") != wantDisposition { t.Fatalf("HEAD status=%d size=%d headers=%#v", head.Code, head.Body.Len(), head.Header()) } rangeRequest := httptest.NewRequest(http.MethodGet, path, nil) rangeRequest.Header.Set("Range", "bytes=0-3") partial := httptest.NewRecorder() router.ServeHTTP(partial, rangeRequest) - if partial.Code != http.StatusPartialContent || partial.Body.Len() != 4 || partial.Header().Get("Content-Range") == "" { + if partial.Code != http.StatusPartialContent || partial.Body.Len() != 4 || partial.Header().Get("Content-Range") == "" || partial.Header().Get("Content-Disposition") != wantDisposition { t.Fatalf("Range status=%d size=%d headers=%#v", partial.Code, partial.Body.Len(), partial.Header()) } } From 72cc75b75119baa89dd94e984c6e1c8f5f6f34ee Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Fri, 14 Aug 2026 10:14:37 +0800 Subject: [PATCH 34/48] fix: return verified public playback URLs with safe fallback --- backend/internal/application/gateway/video.go | 28 ++++++- .../application/gateway/video_test.go | 75 ++++++++++++++++++- .../transport/http/inference/handler_test.go | 9 ++- 3 files changed, 104 insertions(+), 8 deletions(-) diff --git a/backend/internal/application/gateway/video.go b/backend/internal/application/gateway/video.go index 9b048876..ce2b6efe 100644 --- a/backend/internal/application/gateway/video.go +++ b/backend/internal/application/gateway/video.go @@ -233,7 +233,7 @@ func resolveVideoPricing(operation provider.VideoOperation, upstreamModel, resol return audit.PricingResult{}, false } -func (s *Service) GetVideo(ctx context.Context, id string, key clientkey.Key) (media.Job, error) { +func (s *Service) getVideoJob(ctx context.Context, id string, key clientkey.Key) (media.Job, error) { if s.mediaJobs == nil { return media.Job{}, ErrResponseNotFound } @@ -244,8 +244,32 @@ func (s *Service) GetVideo(ctx context.Context, id string, key clientkey.Key) (m return job, nil } +// GetVideo returns the client-facing job state. A result asset is exposed only +// while the local object can still be opened; completed assets are eligible for +// capacity cleanup, and a stale asset ID would otherwise produce a dead public URL. +func (s *Service) GetVideo(ctx context.Context, id string, key clientkey.Key) (media.Job, error) { + job, err := s.getVideoJob(ctx, id, key) + if err != nil { + return media.Job{}, err + } + if job.Status != media.StatusCompleted || strings.TrimSpace(job.ResultAssetID) == "" { + return job, nil + } + if s.mediaAssets == nil { + job.ResultAssetID = "" + return job, nil + } + _, body, openErr := s.mediaAssets.OpenVideo(ctx, job.ResultAssetID) + if openErr != nil || body == nil { + job.ResultAssetID = "" + return job, nil + } + _ = body.Close() + return job, nil +} + func (s *Service) OpenVideoContent(ctx context.Context, id string, key clientkey.Key) (io.ReadCloser, string, int64, error) { - job, err := s.GetVideo(ctx, id, key) + job, err := s.getVideoJob(ctx, id, key) if err != nil { return nil, "", 0, err } diff --git a/backend/internal/application/gateway/video_test.go b/backend/internal/application/gateway/video_test.go index 05f82ff0..46a29383 100644 --- a/backend/internal/application/gateway/video_test.go +++ b/backend/internal/application/gateway/video_test.go @@ -15,6 +15,7 @@ import ( "github.com/chenyme/grok2api/backend/internal/domain/account" "github.com/chenyme/grok2api/backend/internal/domain/audit" + "github.com/chenyme/grok2api/backend/internal/domain/clientkey" "github.com/chenyme/grok2api/backend/internal/domain/media" "github.com/chenyme/grok2api/backend/internal/domain/model" "github.com/chenyme/grok2api/backend/internal/infra/provider" @@ -39,6 +40,67 @@ func TestVideoQuotaModeUsesWeb720pProduct(t *testing.T) { } } +func TestGetVideoExposesOnlyReadableResultAsset(t *testing.T) { + completed := media.Job{ + ID: "video_status", ClientKeyID: 7, Status: media.StatusCompleted, + ResultAssetID: "vid_local", UpstreamURL: "https://assets.grok.com/video.mp4", + } + tests := []struct { + name string + store videoAssetStore + want string + }{ + { + name: "available", + store: &videoAssetStoreStub{ + openAsset: media.Asset{ID: "vid_local", Kind: "video", MIMEType: "video/mp4"}, + openData: []byte("video"), + }, + want: "vid_local", + }, + {name: "missing", store: &videoAssetStoreStub{openErr: errors.New("asset missing")}}, + {name: "storage unavailable"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + service := &Service{mediaJobs: &videoUsageRepository{job: completed}, mediaAssets: test.store} + job, err := service.GetVideo(context.Background(), completed.ID, clientkey.Key{ID: completed.ClientKeyID}) + if err != nil { + t.Fatal(err) + } + if job.ResultAssetID != test.want { + t.Fatalf("result asset ID = %q, want %q", job.ResultAssetID, test.want) + } + }) + } +} + +func TestOpenVideoContentKeepsLocalAssetFastPath(t *testing.T) { + completed := media.Job{ + ID: "video_content", ClientKeyID: 7, Status: media.StatusCompleted, + ResultAssetID: "vid_local", UpstreamURL: "https://assets.grok.com/video.mp4", + } + service := &Service{ + mediaJobs: &videoUsageRepository{job: completed}, + mediaAssets: &videoAssetStoreStub{ + openAsset: media.Asset{ID: "vid_local", Kind: "video", MIMEType: "video/mp4", SizeBytes: 5}, + openData: []byte("video"), + }, + } + body, contentType, size, err := service.OpenVideoContent(context.Background(), completed.ID, clientkey.Key{ID: completed.ClientKeyID}) + if err != nil { + t.Fatal(err) + } + defer body.Close() + data, err := io.ReadAll(body) + if err != nil { + t.Fatal(err) + } + if string(data) != "video" || contentType != "video/mp4" || size != 5 { + t.Fatalf("content = %q, type = %q, size = %d", data, contentType, size) + } +} + func TestRecoverVideoJobsRetriesUsageWithoutRegeneratingVideo(t *testing.T) { completedAt := time.Now().UTC() repository := &videoUsageRepository{job: media.Job{ @@ -393,6 +455,9 @@ func (a *videoPersistAdapter) DownloadVideo(_ context.Context, credential accoun type videoAssetStoreStub struct { saveCalls int + openAsset media.Asset + openData []byte + openErr error inputID string inputData []byte inputSize int64 @@ -415,8 +480,14 @@ func (s *videoAssetStoreStub) SaveVideo(_ context.Context, jobID, contentType st return media.Asset{ID: "vid_local", Kind: "video", MIMEType: "video/mp4", SizeBytes: int64(len(data))}, nil } -func (*videoAssetStoreStub) OpenVideo(context.Context, string) (media.Asset, io.ReadCloser, error) { - return media.Asset{}, nil, errors.New("not implemented") +func (s *videoAssetStoreStub) OpenVideo(_ context.Context, id string) (media.Asset, io.ReadCloser, error) { + if s.openErr != nil { + return media.Asset{}, nil, s.openErr + } + if s.openAsset.ID == "" || id != s.openAsset.ID { + return media.Asset{}, nil, errors.New("not implemented") + } + return s.openAsset, io.NopCloser(bytes.NewReader(s.openData)), nil } func (s *videoAssetStoreStub) OpenInputAsset(_ context.Context, id string) (media.Asset, io.ReadCloser, error) { diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go index 9e70aa17..3787428b 100644 --- a/backend/internal/transport/http/inference/handler_test.go +++ b/backend/internal/transport/http/inference/handler_test.go @@ -134,9 +134,9 @@ func TestVideoContentURLUsesConfiguredPublicAPIBase(t *testing.T) { } } -// A completed job carries a stored asset, so the returned URL must point at the -// public media route. /v1/videos/{id}/content requires the client API key and is -// therefore not usable in a browser or player. +// A completed job whose local asset has been verified by the gateway must point +// at the public media route. /v1/videos/{id}/content requires the client API key +// and is therefore not usable in a browser or player. func TestVideoPlaybackURLPrefersPublicAssetRoute(t *testing.T) { handler := NewHandler(nil, nil, 1<<20, "https://api.example.com/grok2api/") job := mediadomain.Job{ @@ -150,7 +150,8 @@ func TestVideoPlaybackURLPrefersPublicAssetRoute(t *testing.T) { } } -// Without a stored asset the protected content endpoint remains the only option. +// Without a readable stored asset the protected content endpoint remains the +// only option and can still fall back to the upstream download path. func TestVideoPlaybackURLFallsBackToContentEndpoint(t *testing.T) { handler := NewHandler(nil, nil, 1<<20, "https://api.example.com/grok2api/") job := mediadomain.Job{ID: "video_request_1", Status: mediadomain.StatusCompleted} From a2b21c00e731e941e3d5b669757e020de4297f08 Mon Sep 17 00:00:00 2001 From: WuxiVIP Date: Fri, 14 Aug 2026 10:55:11 +0800 Subject: [PATCH 35/48] fix(cli): enforce semantic stream idle timeout --- backend/internal/app/application.go | 2 + .../internal/infra/provider/cli/adapter.go | 13 ++ .../infra/provider/cli/adapter_test.go | 18 +- .../cli/responses_compaction_forward.go | 1 + .../provider/cli/responses_compaction_test.go | 41 ++++ .../infra/provider/cli/semantic_streamidle.go | 196 ++++++++++++++++++ .../provider/cli/semantic_streamidle_test.go | 166 +++++++++++++++ 7 files changed, 435 insertions(+), 2 deletions(-) create mode 100644 backend/internal/infra/provider/cli/semantic_streamidle.go create mode 100644 backend/internal/infra/provider/cli/semantic_streamidle_test.go diff --git a/backend/internal/app/application.go b/backend/internal/app/application.go index eb86333d..9d49bcdd 100644 --- a/backend/internal/app/application.go +++ b/backend/internal/app/application.go @@ -212,6 +212,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat ClientVersion: cfg.Provider.Build.ClientVersion, ClientIdentifier: cfg.Provider.Build.ClientIdentifier, TokenAuth: cfg.Provider.Build.TokenAuth, UserAgent: cfg.Provider.Build.UserAgent, ResponseHeaderTimeout: cfg.Provider.Build.ResponseHeaderTimeout.Value(), + StreamIdleTimeout: cfg.Provider.Build.StreamIdleTimeout.Value(), }, cipher) cliAdapter.SetLogger(logger) cliAdapter.SetEgress(egressManager) @@ -387,6 +388,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat ClientVersion: next.Provider.Build.ClientVersion, ClientIdentifier: next.Provider.Build.ClientIdentifier, TokenAuth: next.Provider.Build.TokenAuth, UserAgent: next.Provider.Build.UserAgent, ResponseHeaderTimeout: next.Provider.Build.ResponseHeaderTimeout.Value(), + StreamIdleTimeout: next.Provider.Build.StreamIdleTimeout.Value(), }) egressManager.UpdateBuildResponseHeaderTimeout(next.Provider.Build.ResponseHeaderTimeout.Value()) egressManager.UpdateBuildStreamIdleTimeout(next.Provider.Build.StreamIdleTimeout.Value()) diff --git a/backend/internal/infra/provider/cli/adapter.go b/backend/internal/infra/provider/cli/adapter.go index 763c278f..932b6eb5 100644 --- a/backend/internal/infra/provider/cli/adapter.go +++ b/backend/internal/infra/provider/cli/adapter.go @@ -39,6 +39,7 @@ type Config struct { TokenAuth string UserAgent string ResponseHeaderTimeout time.Duration + StreamIdleTimeout time.Duration } const ( @@ -68,6 +69,7 @@ type Adapter struct { func NewAdapter(cfg Config, cipher *security.Cipher) *Adapter { cfg.ResponseHeaderTimeout = normalizeBuildResponseHeaderTimeout(cfg.ResponseHeaderTimeout) + cfg.StreamIdleTimeout = normalizeBuildStreamIdleTimeout(cfg.StreamIdleTimeout) transport := newBuildDirectTransport(cfg.ResponseHeaderTimeout) httpClient := &http.Client{Transport: transport} // The official CLI uses a persistent machine identity. The gateway does not collect machine fingerprints; @@ -156,6 +158,7 @@ func buildBotFlaggedFromClaims(claims map[string]any) bool { func (a *Adapter) UpdateConfig(cfg Config) { cfg.ResponseHeaderTimeout = normalizeBuildResponseHeaderTimeout(cfg.ResponseHeaderTimeout) + cfg.StreamIdleTimeout = normalizeBuildStreamIdleTimeout(cfg.StreamIdleTimeout) a.cfgMu.Lock() previousTimeout := a.cfg.ResponseHeaderTimeout a.cfg = cfg @@ -204,6 +207,13 @@ func normalizeBuildResponseHeaderTimeout(value time.Duration) time.Duration { return value } +func normalizeBuildStreamIdleTimeout(value time.Duration) time.Duration { + if value <= 0 { + return settingsdomain.DefaultBuildStreamIdleTimeout + } + return value +} + func (a *Adapter) config() Config { a.cfgMu.RLock() defer a.cfgMu.RUnlock() @@ -364,6 +374,9 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response } } } + if request.Streaming && isHTTPSuccess(resp.StatusCode) && resp.Body != nil { + resp.Body = wrapBuildSemanticIdle(resp.Body, a.config().StreamIdleTimeout) + } modelCatalogChanged := a.modelCatalogChanged(request.Credential.ID, resp.Header.Get("x-models-etag")) // Capture or clear reasoning replay in the upstream Responses shape before protocol conversion. if a.shouldCaptureReplay(request, resp, replayKey) { diff --git a/backend/internal/infra/provider/cli/adapter_test.go b/backend/internal/infra/provider/cli/adapter_test.go index 27e89378..00f0afd9 100644 --- a/backend/internal/infra/provider/cli/adapter_test.go +++ b/backend/internal/infra/provider/cli/adapter_test.go @@ -17,6 +17,7 @@ import ( "github.com/chenyme/grok2api/backend/internal/domain/account" modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" + settingsdomain "github.com/chenyme/grok2api/backend/internal/domain/settings" infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" "github.com/chenyme/grok2api/backend/internal/infra/provider" "github.com/chenyme/grok2api/backend/internal/infra/provider/conversation" @@ -60,16 +61,29 @@ func TestResponseRequestForcedEgressOverridesCredentialBinding(t *testing.T) { } func TestAdapterHotUpdatesDirectResponseHeaderTimeout(t *testing.T) { - adapter := NewAdapter(Config{ResponseHeaderTimeout: 2 * time.Minute}, nil) + adapter := NewAdapter(Config{ResponseHeaderTimeout: 2 * time.Minute, StreamIdleTimeout: 3 * time.Minute}, nil) before := adapter.base.current.Load() if before.ResponseHeaderTimeout != 2*time.Minute { t.Fatalf("initial timeout = %s", before.ResponseHeaderTimeout) } - adapter.UpdateConfig(Config{ResponseHeaderTimeout: 7 * time.Minute}) + if got := adapter.config().StreamIdleTimeout; got != 3*time.Minute { + t.Fatalf("initial stream idle timeout = %s", got) + } + adapter.UpdateConfig(Config{ResponseHeaderTimeout: 7 * time.Minute, StreamIdleTimeout: 11 * time.Minute}) after := adapter.base.current.Load() if after == before || after.ResponseHeaderTimeout != 7*time.Minute { t.Fatalf("updated transport=%p timeout=%s", after, after.ResponseHeaderTimeout) } + if got := adapter.config().StreamIdleTimeout; got != 11*time.Minute { + t.Fatalf("updated stream idle timeout = %s", got) + } +} + +func TestAdapterDefaultsStreamIdleTimeout(t *testing.T) { + adapter := NewAdapter(Config{}, nil) + if got := adapter.config().StreamIdleTimeout; got != settingsdomain.DefaultBuildStreamIdleTimeout { + t.Fatalf("stream idle timeout = %s, want %s", got, settingsdomain.DefaultBuildStreamIdleTimeout) + } } func TestCredentialMetadataMarksNumericBotFlagOneOrTwo(t *testing.T) { diff --git a/backend/internal/infra/provider/cli/responses_compaction_forward.go b/backend/internal/infra/provider/cli/responses_compaction_forward.go index 340c76e5..ed0c5bde 100644 --- a/backend/internal/infra/provider/cli/responses_compaction_forward.go +++ b/backend/internal/infra/provider/cli/responses_compaction_forward.go @@ -134,6 +134,7 @@ func (a *Adapter) forwardGatewayCompactionWithPolicy( return result, nil } + resp.Body = wrapBuildSemanticIdle(resp.Body, a.config().StreamIdleTimeout) data, readErr := io.ReadAll(io.LimitReader(resp.Body, maxCompatibleResponseBytes+1)) _ = resp.Body.Close() if readErr != nil { diff --git a/backend/internal/infra/provider/cli/responses_compaction_test.go b/backend/internal/infra/provider/cli/responses_compaction_test.go index d48baeec..c7af848e 100644 --- a/backend/internal/infra/provider/cli/responses_compaction_test.go +++ b/backend/internal/infra/provider/cli/responses_compaction_test.go @@ -15,6 +15,7 @@ import ( "github.com/chenyme/grok2api/backend/internal/infra/provider" "github.com/chenyme/grok2api/backend/internal/infra/provider/conversation" "github.com/chenyme/grok2api/backend/internal/infra/security" + "github.com/chenyme/grok2api/backend/internal/pkg/neterror" ) func TestGatewayCompactionLifecycle(t *testing.T) { @@ -107,6 +108,46 @@ func TestGatewayCompactionRetryVetoStopsSameAccountRetries(t *testing.T) { } } +func TestGatewayCompactionSemanticIdleIgnoresKeepalives(t *testing.T) { + adapter, encrypted := newCompactionTestAdapter(t) + cfg := adapter.config() + cfg.StreamIdleTimeout = 60 * time.Millisecond + adapter.UpdateConfig(cfg) + + writeDone := make(chan struct{}) + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + reader, writer := io.Pipe() + go func() { + defer close(writeDone) + defer writer.Close() + for { + if _, err := io.WriteString(writer, ": keep-alive\n\n"); err != nil { + return + } + time.Sleep(10 * time.Millisecond) + } + }() + return &http.Response{ + StatusCode: http.StatusOK, + Status: "200 OK", + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: reader, + Request: request, + }, nil + }) + + request := compactionProviderRequest(encrypted) + _, err := adapter.forwardGatewayCompactionWithPolicy(t.Context(), request, "access-token", request.Body, "", 1, 0) + if !errors.Is(err, neterror.ErrUpstreamStreamIdleTimeout) { + t.Fatalf("compaction error = %v, want ErrUpstreamStreamIdleTimeout", err) + } + select { + case <-writeDone: + case <-time.After(time.Second): + t.Fatal("semantic timeout did not close the compaction response body") + } +} + func TestGatewayCompactionResponseNormalizesPartialUsage(t *testing.T) { response := map[string]any{ "id": "resp_usage", diff --git a/backend/internal/infra/provider/cli/semantic_streamidle.go b/backend/internal/infra/provider/cli/semantic_streamidle.go new file mode 100644 index 00000000..86926e3e --- /dev/null +++ b/backend/internal/infra/provider/cli/semantic_streamidle.go @@ -0,0 +1,196 @@ +package cli + +import ( + "bytes" + "encoding/json" + "io" + "strings" + "sync" + "time" + + "github.com/chenyme/grok2api/backend/internal/pkg/neterror" +) + +var buildGeneratedDeltaEvents = map[string]struct{}{ + "response.output_text.delta": {}, + "response.reasoning_summary_text.delta": {}, + "response.reasoning_text.delta": {}, + "response.refusal.delta": {}, + "response.function_call_arguments.delta": {}, + "response.custom_tool_call_input.delta": {}, +} + +// semanticIdleReadCloser measures useful generated output rather than raw +// transport bytes, so SSE keepalives and Build control events cannot keep a +// stalled generation alive indefinitely. +type semanticIdleReadCloser struct { + inner io.ReadCloser + idle time.Duration + timer *time.Timer + + mu sync.Mutex + detector buildSSEActivityDetector + finished bool + timedOut bool + + closeOnce sync.Once + closeErr error +} + +func wrapBuildSemanticIdle(body io.ReadCloser, idle time.Duration) io.ReadCloser { + if body == nil || idle <= 0 { + return body + } + wrapper := &semanticIdleReadCloser{inner: body, idle: idle} + wrapper.timer = time.AfterFunc(idle, wrapper.timeout) + return wrapper +} + +func (r *semanticIdleReadCloser) timeout() { + r.mu.Lock() + if r.finished { + r.mu.Unlock() + return + } + r.finished = true + r.timedOut = true + r.mu.Unlock() + _ = r.closeInner() +} + +func (r *semanticIdleReadCloser) Read(buffer []byte) (int, error) { + n, err := r.inner.Read(buffer) + + r.mu.Lock() + if n > 0 && !r.finished && r.detector.Observe(buffer[:n]) { + // A failed Stop means the deadline has already elapsed and its callback + // owns the outcome. Reset only while the prior deadline is still live. + if r.timer.Stop() { + r.timer.Reset(r.idle) + } + } + if err != nil && !r.finished { + r.finished = true + r.timer.Stop() + } + timedOut := r.timedOut + r.mu.Unlock() + + if timedOut { + return n, neterror.ErrUpstreamStreamIdleTimeout + } + return n, err +} + +func (r *semanticIdleReadCloser) Close() error { + r.mu.Lock() + if !r.finished { + r.finished = true + r.timer.Stop() + } + r.mu.Unlock() + return r.closeInner() +} + +func (r *semanticIdleReadCloser) closeInner() error { + r.closeOnce.Do(func() { + r.closeErr = r.inner.Close() + }) + return r.closeErr +} + +func (r *semanticIdleReadCloser) TimedOut() bool { + r.mu.Lock() + defer r.mu.Unlock() + return r.timedOut +} + +// buildSSEActivityDetector incrementally parses SSE framing without modifying +// the bytes returned to downstream response wrappers. +type buildSSEActivityDetector struct { + pending []byte + eventName string + data []byte + eventBytes int + overLimit bool + firstLine bool +} + +func (d *buildSSEActivityDetector) Observe(chunk []byte) bool { + if len(chunk) == 0 { + return false + } + d.pending = append(d.pending, chunk...) + active := false + for { + newline := bytes.IndexByte(d.pending, '\n') + if newline < 0 { + break + } + line := d.pending[:newline] + d.pending = d.pending[newline+1:] + line = bytes.TrimSuffix(line, []byte{'\r'}) + if !d.firstLine { + line = bytes.TrimPrefix(line, []byte("\xef\xbb\xbf")) + d.firstLine = true + } + if len(line) == 0 { + active = d.finishEvent() || active + continue + } + d.observeLine(line) + } + if len(d.pending)+d.eventBytes > maxCompatibleSSEEventBytes { + d.pending = nil + d.overLimit = true + } + return active +} + +func (d *buildSSEActivityDetector) observeLine(line []byte) { + d.eventBytes += len(line) + if d.eventBytes > maxCompatibleSSEEventBytes { + d.overLimit = true + d.eventName = "" + d.data = nil + return + } + if d.overLimit || len(line) == 0 || line[0] == ':' { + return + } + field, value, found := bytes.Cut(line, []byte{':'}) + if found && len(value) > 0 && value[0] == ' ' { + value = value[1:] + } + switch string(field) { + case "event": + d.eventName = string(value) + case "data": + if len(d.data) > 0 { + d.data = append(d.data, '\n') + } + d.data = append(d.data, value...) + } +} + +func (d *buildSSEActivityDetector) finishEvent() bool { + active := false + if !d.overLimit && len(d.data) > 0 { + var payload struct { + Type string `json:"type"` + Delta string `json:"delta"` + } + if json.Unmarshal(d.data, &payload) == nil && payload.Delta != "" { + kind := strings.TrimSpace(payload.Type) + if kind == "" { + kind = strings.TrimSpace(d.eventName) + } + _, active = buildGeneratedDeltaEvents[kind] + } + } + d.eventName = "" + d.data = nil + d.eventBytes = 0 + d.overLimit = false + return active +} diff --git a/backend/internal/infra/provider/cli/semantic_streamidle_test.go b/backend/internal/infra/provider/cli/semantic_streamidle_test.go new file mode 100644 index 00000000..4d059c2f --- /dev/null +++ b/backend/internal/infra/provider/cli/semantic_streamidle_test.go @@ -0,0 +1,166 @@ +package cli + +import ( + "errors" + "fmt" + "io" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/chenyme/grok2api/backend/internal/pkg/neterror" +) + +func TestBuildSemanticIdleIgnoresNonGeneratedEvents(t *testing.T) { + tests := []struct { + name string + chunk string + }{ + {name: "keepalive comment", chunk: ": keep-alive\n\n"}, + {name: "doom loop control", chunk: "event: response.doom_loop_check\ndata: {\"type\":\"response.doom_loop_check\"}\n\n"}, + {name: "lifecycle event", chunk: "event: response.in_progress\ndata: {\"type\":\"response.in_progress\"}\n\n"}, + {name: "empty generated delta", chunk: "event: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"\"}\n\n"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + reader, writer := io.Pipe() + body := wrapBuildSemanticIdle(reader, 60*time.Millisecond) + readDone := make(chan error, 1) + go func() { + _, err := io.Copy(io.Discard, body) + readDone <- err + }() + writeDone := make(chan struct{}) + go func() { + defer close(writeDone) + defer writer.Close() + for { + if _, err := io.WriteString(writer, test.chunk); err != nil { + return + } + time.Sleep(10 * time.Millisecond) + } + }() + + select { + case err := <-readDone: + if !errors.Is(err, neterror.ErrUpstreamStreamIdleTimeout) { + t.Fatalf("body read error = %v, want ErrUpstreamStreamIdleTimeout", err) + } + case <-time.After(time.Second): + t.Fatal("semantic idle timeout did not interrupt the stream") + } + <-writeDone + }) + } +} + +func TestBuildSemanticIdleResetsOnGeneratedDelta(t *testing.T) { + reader, writer := io.Pipe() + body := wrapBuildSemanticIdle(reader, 300*time.Millisecond) + readDone := make(chan error, 1) + go func() { + _, err := io.Copy(io.Discard, body) + readDone <- err + }() + + chunk := "event: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"x\"}\n\n" + if _, err := io.WriteString(writer, chunk); err != nil { + t.Fatal(err) + } + time.Sleep(180 * time.Millisecond) + if _, err := io.WriteString(writer, chunk); err != nil { + t.Fatal(err) + } + time.Sleep(180 * time.Millisecond) + if err := writer.Close(); err != nil { + t.Fatal(err) + } + + select { + case err := <-readDone: + if err != nil { + t.Fatalf("body read error = %v, want nil", err) + } + case <-time.After(time.Second): + t.Fatal("generated deltas did not keep the stream alive") + } +} + +func TestBuildSSEActivityDetectorRecognizesSplitGeneratedEvents(t *testing.T) { + for kind := range buildGeneratedDeltaEvents { + t.Run(kind, func(t *testing.T) { + var detector buildSSEActivityDetector + event := fmt.Sprintf("event: %s\r\ndata: {\"type\":%q,\"delta\":\"x\"}\r\n\r\n", kind, kind) + active := false + for index := range event { + active = detector.Observe([]byte(event[index:index+1])) || active + } + if !active { + t.Fatal("split generated event was not recognized") + } + }) + } +} + +func TestBuildSSEActivityDetectorRequiresJSONGeneratedEvent(t *testing.T) { + var detector buildSSEActivityDetector + if detector.Observe([]byte("event: response.output_text.delta\ndata: not-json\n\n")) { + t.Fatal("malformed event unexpectedly counted as generated activity") + } + if detector.Observe([]byte(": keep-alive\n\n")) { + t.Fatal("keepalive unexpectedly counted as generated activity") + } + if detector.Observe([]byte("event: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"\"}\n\n")) { + t.Fatal("empty delta unexpectedly counted as generated activity") + } +} + +func TestBuildSemanticIdleStopsAfterEOFOrClose(t *testing.T) { + t.Run("EOF", func(t *testing.T) { + inner := &countingReadCloser{Reader: strings.NewReader("done")} + body := wrapBuildSemanticIdle(inner, 20*time.Millisecond).(*semanticIdleReadCloser) + if _, err := io.ReadAll(body); err != nil { + t.Fatal(err) + } + time.Sleep(40 * time.Millisecond) + if body.TimedOut() { + t.Fatal("timer fired after EOF") + } + if err := body.Close(); err != nil { + t.Fatal(err) + } + if got := inner.closes.Load(); got != 1 { + t.Fatalf("inner Close calls = %d, want 1", got) + } + }) + + t.Run("Close", func(t *testing.T) { + inner := &countingReadCloser{Reader: strings.NewReader("")} + body := wrapBuildSemanticIdle(inner, 20*time.Millisecond).(*semanticIdleReadCloser) + if err := body.Close(); err != nil { + t.Fatal(err) + } + if err := body.Close(); err != nil { + t.Fatal(err) + } + time.Sleep(40 * time.Millisecond) + if body.TimedOut() { + t.Fatal("timer fired after Close") + } + if got := inner.closes.Load(); got != 1 { + t.Fatalf("inner Close calls = %d, want 1", got) + } + }) +} + +type countingReadCloser struct { + io.Reader + closes atomic.Int32 +} + +func (r *countingReadCloser) Close() error { + r.closes.Add(1) + return nil +} From c7ddda2366521aa1b1e34eca72b871273d1afac1 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Fri, 14 Aug 2026 11:30:45 +0800 Subject: [PATCH 36/48] perf: optimize large account pool selection and precise health invalidation --- README.md | 2 +- README.zh-CN.md | 2 +- .../internal/application/gateway/selector.go | 270 ++++++++++++++---- .../gateway/selector_layered_test.go | 99 +++++++ .../application/gateway/selector_plan.go | 27 +- .../application/gateway/selector_segmented.go | 8 + .../gateway/selector_segmented_active.go | 95 ++++-- .../gateway/selector_segmented_active_test.go | 86 ++++-- .../application/gateway/selector_session.go | 22 +- .../application/gateway/service_test.go | 6 +- .../application/invalidation/service.go | 5 + .../application/invalidation/service_test.go | 8 + backend/internal/infra/config/config.go | 2 +- backend/internal/infra/config/config_test.go | 2 +- .../relational/account_repository.go | 50 +++- .../relational/invalidation_test.go | 47 +++ .../persistence/relational/repository_test.go | 4 +- .../internal/infra/runtime/memory/store.go | 8 +- backend/internal/infra/runtime/redis/store.go | 14 +- backend/internal/repository/account.go | 5 +- backend/internal/repository/runtime.go | 18 +- config.example.yaml | 4 +- .../src/features/settings/settings-api.ts | 4 +- frontend/src/shared/i18n/index.ts | 4 +- 24 files changed, 638 insertions(+), 154 deletions(-) diff --git a/README.md b/README.md index 4c30939d..c1c47e2c 100644 --- a/README.md +++ b/README.md @@ -423,7 +423,7 @@ Important optional settings: - `audit.ledgerMode`: `observe` reports ledger faults; `enforce` can pause new inference to protect billing integrity. - `routing.accountIsolatedConnections`: partitions outbound TCP/HTTP pools by account for external L4 or connection-hash load balancers. It is off by default because it increases connections, TLS handshakes, memory, and file-descriptor usage. -- `routing.segmentedSelectorEnabled`: optimizes large account pools while retaining full-planner fallback and atomic guards. +- `routing.segmentedSelectorEnabled`: enabled by default for pools with at least 3,000 eligible accounts; bounds dynamic concurrency reads while retaining quota/tier priorities, sticky sessions, full-planner fallback, and atomic guards. - Build response-header timeout and exact-match 403 invalidation rules are hot-reloadable. - **Sync latest version** applies the validated Grok Build client version and User-Agent. diff --git a/README.zh-CN.md b/README.zh-CN.md index 497b4be8..7b81395b 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -417,7 +417,7 @@ GROK2API_DATABASE_URL='postgresql://user:password@host:5432/grok2api?sslmode=req - `audit.ledgerMode`:`observe` 仅报告账本故障;`enforce` 可暂停新推理以保护计费准确性。 - `routing.accountIsolatedConnections`:为外部 L4 或按连接哈希的负载均衡器按账号拆分出站 TCP/HTTP 连接池。默认关闭,因为会增加连接数、TLS 握手、内存和文件描述符占用。 -- `routing.segmentedSelectorEnabled`:用于大型账号池,同时保留完整选号回退与原子门禁。 +- `routing.segmentedSelectorEnabled`:默认对至少 3000 个可用账号的大号池启用,限制动态并发读取规模,同时保留额度/等级优先级、会话粘性、完整选号回退与原子门禁。 - Build 响应头超时和精确匹配的 403 失效规则支持热加载。 - “同步最新版本”可应用已验证的 Grok Build 客户端版本和 User-Agent。 diff --git a/backend/internal/application/gateway/selector.go b/backend/internal/application/gateway/selector.go index 9a9cc10f..b099a632 100644 --- a/backend/internal/application/gateway/selector.go +++ b/backend/internal/application/gateway/selector.go @@ -28,6 +28,7 @@ type accountLease struct { QuotaProbe bool QuotaProbeKind account.QuotaRecoveryKind QuotaMode string + routingCandidate *account.RoutingCandidate selectorObservation *selectorLeaseObservation release func() } @@ -51,6 +52,12 @@ const maxRoutingOverlayValues = 250_000 const concurrencySnapshotTTL = 25 * time.Millisecond const maxConcurrencySnapshots = 256 +// Health overrides bridge precise request-path mutations until the immutable +// provider snapshot naturally refreshes. Keep them through the snapshot's +// normal and stale lifetimes so a transient database error cannot resurrect a +// cooled account from an older snapshot. +const routingHealthOverrideTTL = candidateCacheTTL + candidateCacheStaleTTL + const modelAccessDeniedCooldown = 5 * time.Minute // softNetworkCooldown 网络/超时/5xx 仅短暂隔离本号,避免指数冷却掏空热池。 @@ -75,6 +82,16 @@ type accountQuotaConsumptionKey struct { mode string } +type routingHealthOverride struct { + provider account.Provider + failureCount int + cooldownUntil *time.Time + lastError string + updatedAt time.Time + revision uint64 + expiresAt time.Time +} + type candidateSnapshot struct { values []account.RoutingCandidate byAccount map[uint64]int @@ -268,6 +285,7 @@ type Selector struct { configMu sync.RWMutex candidateMu sync.Mutex selectionMu sync.RWMutex + healthMu sync.RWMutex quotaMu sync.RWMutex staleLogMu sync.Mutex logger *slog.Logger @@ -275,6 +293,7 @@ type Selector struct { leaseWake chan struct{} lastSelectedAt map[uint64]time.Time lastSuccessAt map[uint64]time.Time + healthOverrides map[uint64]routingHealthOverride quotaConsumed map[quotaConsumptionKey]int staleFallbackLoggedAt map[string]time.Time candidates map[candidateCacheKey]candidateSnapshot @@ -299,7 +318,7 @@ func NewSelector(accounts repository.AccountRepository, concurrency repository.C if len(capacityWait) > 0 && capacityWait[0] > 0 { wait = capacityWait[0] } - return &Selector{accounts: accounts, concurrency: concurrency, sticky: sticky, tierOrders: tierOrders, stickyTTL: stickyTTL, cooldownBase: cooldownBase, cooldownMax: cooldownMax, capacityWait: wait, leaseWake: make(chan struct{}), logger: slog.Default(), lastSelectedAt: make(map[uint64]time.Time), lastSuccessAt: make(map[uint64]time.Time), quotaConsumed: make(map[quotaConsumptionKey]int), staleFallbackLoggedAt: make(map[string]time.Time), candidates: make(map[candidateCacheKey]candidateSnapshot), routingBases: make(map[routingBaseCacheKey]routingBaseSnapshot), routingOverlays: make(map[routingOverlayCacheKey]routingOverlaySnapshot), routingAccountProvider: make(map[uint64]account.Provider), baseProviderVersion: make(map[account.Provider]uint64), overlayProviderVersion: make(map[account.Provider]uint64), concurrencySnapshots: resultcache.New[[32]byte, map[string]int](maxConcurrencySnapshots, concurrencySnapshotTTL)} + return &Selector{accounts: accounts, concurrency: concurrency, sticky: sticky, tierOrders: tierOrders, stickyTTL: stickyTTL, cooldownBase: cooldownBase, cooldownMax: cooldownMax, capacityWait: wait, leaseWake: make(chan struct{}), logger: slog.Default(), lastSelectedAt: make(map[uint64]time.Time), lastSuccessAt: make(map[uint64]time.Time), healthOverrides: make(map[uint64]routingHealthOverride), quotaConsumed: make(map[quotaConsumptionKey]int), staleFallbackLoggedAt: make(map[string]time.Time), candidates: make(map[candidateCacheKey]candidateSnapshot), routingBases: make(map[routingBaseCacheKey]routingBaseSnapshot), routingOverlays: make(map[routingOverlayCacheKey]routingOverlaySnapshot), routingAccountProvider: make(map[uint64]account.Provider), baseProviderVersion: make(map[account.Provider]uint64), overlayProviderVersion: make(map[account.Provider]uint64), concurrencySnapshots: resultcache.New[[32]byte, map[string]int](maxConcurrencySnapshots, concurrencySnapshotTTL)} } // SetLogger wires the application logger into routing degradation diagnostics. @@ -441,6 +460,7 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model return nil, err } quotaConsumed := s.quotaConsumptionSnapshot(provider) + healthOverrides := s.routingHealthSnapshot(provider, now) // 仅保留候选下标,避免每个请求复制包含凭据、计费和额度结构的完整账号切片。 normalCandidates := make([]int, 0, len(values)) probeCandidates := make([]int, 0, len(values)) @@ -451,7 +471,7 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model quotaCandidates := 0 var earliestRetry time.Time for index, candidate := range values { - value := candidate.Credential + value := applyHealthSnapshot(candidate.Credential, healthOverrides) if forcedEgressNodeID != 0 && value.EgressNodeID != forcedEgressNodeID { continue } @@ -615,11 +635,17 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model } return nil, &SelectionUnavailableError{Reason: SelectionSaturated, RetryAfter: time.Second} } - if stickyKey == "" { - activeRequest := s.nextSegmentedActiveRequest(provider, upstreamModel, quotaMode, len(normalCandidates)) - if activeRequest != nil { - return s.acquireSegmentedCandidates(ctx, values, normalCandidates, quotaMode, s.resolveTierOrder(provider, upstreamModel), *activeRequest) + activeRequest := s.nextSegmentedActiveRequest(provider, upstreamModel, quotaMode, len(normalCandidates)) + if activeRequest != nil { + lease, acquireErr := s.acquireSegmentedCandidates(ctx, values, normalCandidates, quotaMode, s.resolveTierOrder(provider, upstreamModel), *activeRequest) + if acquireErr != nil || lease == nil || stickyKey == "" { + return lease, acquireErr } + if lease.routingCandidate == nil { + lease.Release() + return nil, errors.New("分段选号缺少候选上下文") + } + return s.completeStickyLease(ctx, stickyKey, values, normalCandidates, *lease.routingCandidate, lease, quotaMode) } _, _, _, capacityWait := s.routingConfig() waitDeadline := time.Now().Add(capacityWait) @@ -644,42 +670,7 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model capacityMisses++ continue } - if stickyKey != "" { - stickyTTL, _, _, _ := s.routingConfig() - boundID, bindErr := s.sticky.Bind(ctx, stickyKey, candidate.Credential.ID, currentTime, currentTime.Add(stickyTTL)) - if bindErr != nil { - lease.Release() - return nil, fmt.Errorf("写入会话粘滞状态: %w", bindErr) - } - if boundID != candidate.Credential.ID { - if boundCandidate, eligible := routingCandidateByID(values, normalCandidates, boundID); eligible { - boundLease, boundErr := s.acquirePinnedCapacity(ctx, boundCandidate.Credential) - if boundErr == nil { - lease.Release() - boundLease.Billing = boundCandidate.Billing - boundLease.QuotaMode = effectiveQuotaMode(boundCandidate, quotaMode) - return boundLease, nil - } - if errors.Is(boundErr, errRoutingCredentialStale) { - _ = s.sticky.DeleteByAccount(ctx, boundID) - if err := s.sticky.Set(ctx, stickyKey, candidate.Credential.ID, currentTime.Add(stickyTTL)); err != nil { - lease.Release() - return nil, fmt.Errorf("重建会话粘滞状态: %w", err) - } - } else if !isSelectionUnavailable(boundErr, SelectionSaturated) { - lease.Release() - return nil, boundErr - } - // 已绑定账号满载时保留原绑定,本次请求使用已获取的临时账号。 - } else if err := s.sticky.Set(ctx, stickyKey, candidate.Credential.ID, currentTime.Add(stickyTTL)); err != nil { - lease.Release() - return nil, fmt.Errorf("重建会话粘滞状态: %w", err) - } - } - } - lease.Billing = candidate.Billing - lease.QuotaMode = effectiveQuotaMode(candidate, quotaMode) - return lease, nil + return s.completeStickyLease(ctx, stickyKey, values, normalCandidates, candidate, lease, quotaMode) } if staleClaims > 0 && capacityMisses == 0 { return nil, &SelectionUnavailableError{Reason: SelectionNoAccounts} @@ -697,6 +688,44 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model } } +func (s *Selector) completeStickyLease(ctx context.Context, stickyKey string, values []account.RoutingCandidate, normalCandidates []int, candidate account.RoutingCandidate, lease *accountLease, quotaMode string) (*accountLease, error) { + if stickyKey != "" { + stickyTTL, _, _, _ := s.routingConfig() + now := time.Now().UTC() + boundID, err := s.sticky.Bind(ctx, stickyKey, candidate.Credential.ID, now, now.Add(stickyTTL)) + if err != nil { + lease.Release() + return nil, fmt.Errorf("写入会话粘滞状态: %w", err) + } + if boundID != candidate.Credential.ID { + if boundCandidate, eligible := routingCandidateByID(values, normalCandidates, boundID); eligible { + boundLease, acquireErr := s.acquirePinnedCapacity(ctx, boundCandidate.Credential) + if acquireErr == nil { + lease.Release() + lease = boundLease + candidate = boundCandidate + } else if errors.Is(acquireErr, errRoutingCredentialStale) { + _ = s.sticky.DeleteByAccount(ctx, boundID) + if err := s.sticky.Set(ctx, stickyKey, candidate.Credential.ID, now.Add(stickyTTL)); err != nil { + lease.Release() + return nil, fmt.Errorf("重建会话粘滞状态: %w", err) + } + } else if !isSelectionUnavailable(acquireErr, SelectionSaturated) { + lease.Release() + return nil, acquireErr + } + // 已绑定账号满载时保留原绑定,本次请求使用已获取的临时账号。 + } else if err := s.sticky.Set(ctx, stickyKey, candidate.Credential.ID, now.Add(stickyTTL)); err != nil { + lease.Release() + return nil, fmt.Errorf("重建会话粘滞状态: %w", err) + } + } + } + lease.Billing = candidate.Billing + lease.QuotaMode = effectiveQuotaMode(candidate, quotaMode) + return lease, nil +} + // stickySessionKey 将调用方粘滞 identity 压缩为固定长度,仅用于账号粘滞索引。 func stickySessionKey(value string) string { if value == "" { @@ -742,8 +771,9 @@ func (s *Selector) acquirePinned(ctx context.Context, provider account.Provider, return nil, err } quotaConsumed := s.quotaConsumptionSnapshot(provider) + healthOverrides := s.routingHealthSnapshot(provider, now) for _, candidate := range values { - value := candidate.Credential + value := applyHealthSnapshot(candidate.Credential, healthOverrides) if value.ID != accountID { continue } @@ -869,22 +899,29 @@ func (s *Selector) MarkSuccess(ctx context.Context, credential account.Credentia func (s *Selector) markSuccess(ctx context.Context, credential account.Credential, quotaProbe bool) { now := time.Now().UTC() - persist := credential.FailureCount > 0 || credential.CooldownUntil != nil || credential.LastError != "" + healthChanged := credential.FailureCount > 0 || credential.CooldownUntil != nil || credential.LastError != "" + touchLastUsed := healthChanged s.selectionMu.Lock() if last := s.lastSuccessAt[credential.ID]; last.IsZero() || now.Sub(last) >= successPersistInterval { - persist = true + touchLastUsed = true } - if persist { + if touchLastUsed { s.lastSuccessAt[credential.ID] = now } s.selectionMu.Unlock() - if persist { - _ = s.accounts.UpdateHealth(ctx, credential.ID, 0, nil, "", true) + if healthChanged { + if err := s.accounts.UpdateHealth(ctx, credential.ID, credential.Provider, 0, nil, "", true); err == nil { + s.ApplyInvalidation(repository.InvalidationEvent{ + Kind: repository.InvalidationAccountHealthChanged, Provider: credential.Provider, AccountID: credential.ID, + }) + } + } else if touchLastUsed { + _ = s.accounts.TouchLastUsed(ctx, credential.ID, now) } if quotaProbe { _ = s.accounts.ClearQuotaRecovery(ctx, credential.ID) } - if quotaProbe || credential.FailureCount > 0 || credential.CooldownUntil != nil || credential.LastError != "" { + if quotaProbe { s.evictCandidate(credential.Provider, credential.ID) } } @@ -1083,8 +1120,14 @@ func (s *Selector) markFailure(ctx context.Context, credential account.Credentia } } until := time.Now().UTC().Add(cooldown) - healthErr := s.accounts.UpdateHealth(ctx, credential.ID, effectiveFailureCount, &until, fmt.Sprintf("upstream status %d", status), false) - s.invalidateCandidates(credential.Provider) + lastError := fmt.Sprintf("upstream status %d", status) + healthErr := s.accounts.UpdateHealth(ctx, credential.ID, credential.Provider, effectiveFailureCount, &until, lastError, false) + if healthErr == nil { + s.ApplyInvalidation(repository.InvalidationEvent{ + Kind: repository.InvalidationAccountHealthChanged, Provider: credential.Provider, AccountID: credential.ID, + FailureCount: effectiveFailureCount, CooldownUntil: &until, + }) + } if status == 401 || status == 402 || status == 403 || status == 429 { _ = s.sticky.DeleteByAccount(ctx, credential.ID) } @@ -1374,11 +1417,131 @@ func (s *Selector) routingVersionsStable(provider account.Provider, base, overla return base == s.routingBaseVersionLocked(provider) && overlay == s.routingOverlayVersionLocked(provider) } +func (s *Selector) applyHealthInvalidation(event repository.InvalidationEvent) { + updatedAt := event.PublishedAt.UTC() + if updatedAt.IsZero() { + updatedAt = time.Now().UTC() + } + expiresAt := updatedAt.Add(routingHealthOverrideTTL) + if !time.Now().UTC().Before(expiresAt) { + return + } + var cooldownUntil *time.Time + if event.CooldownUntil != nil { + value := event.CooldownUntil.UTC() + cooldownUntil = &value + } + overrideLastError := "" + if event.FailureCount > 0 || cooldownUntil != nil { + overrideLastError = "upstream failure" + } + value := routingHealthOverride{ + provider: event.Provider, failureCount: max(0, event.FailureCount), cooldownUntil: cooldownUntil, + lastError: overrideLastError, updatedAt: updatedAt, revision: event.Revision, expiresAt: expiresAt, + } + s.healthMu.Lock() + current, exists := s.healthOverrides[event.AccountID] + if exists { + if current.revision > 0 && value.revision > 0 && value.revision < current.revision { + s.healthMu.Unlock() + return + } + if (current.revision == 0 || value.revision == 0) && value.updatedAt.Before(current.updatedAt) { + s.healthMu.Unlock() + return + } + } + s.healthOverrides[event.AccountID] = value + s.healthMu.Unlock() +} + +func (s *Selector) applyRoutingHealth(value account.Credential, now time.Time) account.Credential { + s.healthMu.RLock() + override, exists := s.healthOverrides[value.ID] + s.healthMu.RUnlock() + if !exists || override.provider != value.Provider { + return value + } + if !now.Before(override.expiresAt) { + s.healthMu.Lock() + if current, ok := s.healthOverrides[value.ID]; ok && !now.Before(current.expiresAt) { + delete(s.healthOverrides, value.ID) + } + s.healthMu.Unlock() + return value + } + value.FailureCount = override.failureCount + value.CooldownUntil = override.cooldownUntil + value.LastError = override.lastError + return value +} + +func (s *Selector) routingHealthSnapshot(provider account.Provider, now time.Time) map[uint64]routingHealthOverride { + var result map[uint64]routingHealthOverride + expired := make([]uint64, 0) + s.healthMu.RLock() + for accountID, value := range s.healthOverrides { + if !now.Before(value.expiresAt) { + expired = append(expired, accountID) + continue + } + if value.provider == provider { + if result == nil { + result = make(map[uint64]routingHealthOverride) + } + result[accountID] = value + } + } + s.healthMu.RUnlock() + if len(expired) > 0 { + s.healthMu.Lock() + for _, accountID := range expired { + if value, ok := s.healthOverrides[accountID]; ok && !now.Before(value.expiresAt) { + delete(s.healthOverrides, accountID) + } + } + s.healthMu.Unlock() + } + return result +} + +func applyHealthSnapshot(value account.Credential, overrides map[uint64]routingHealthOverride) account.Credential { + if override, ok := overrides[value.ID]; ok && override.provider == value.Provider { + value.FailureCount = override.failureCount + value.CooldownUntil = override.cooldownUntil + value.LastError = override.lastError + } + return value +} + +func (s *Selector) clearHealthOverrides(provider account.Provider, accountID uint64) { + s.healthMu.Lock() + defer s.healthMu.Unlock() + if accountID != 0 { + delete(s.healthOverrides, accountID) + return + } + if provider == "" { + clear(s.healthOverrides) + return + } + for id, value := range s.healthOverrides { + if value.provider == provider { + delete(s.healthOverrides, id) + } + } +} + // ApplyInvalidation advances local layer generations before any remote publish. func (s *Selector) ApplyInvalidation(event repository.InvalidationEvent) { if !event.Valid() { return } + if event.Kind == repository.InvalidationAccountHealthChanged { + s.applyHealthInvalidation(event) + return + } + s.clearHealthOverrides(event.Provider, event.AccountID) layer := event.Layer() if layer != repository.InvalidationLayerRoute && layer != repository.InvalidationLayerBase && layer != repository.InvalidationLayerOverlay { return @@ -1696,6 +1859,11 @@ func (s *Selector) evictCandidate(provider account.Provider, accountID uint64) { } func (s *Selector) claimAccountSlot(ctx context.Context, value account.Credential) (*accountLease, error) { + now := time.Now().UTC() + value = s.applyRoutingHealth(value, now) + if value.CooldownUntil != nil && now.Before(*value.CooldownUntil) { + return nil, nil + } limit := value.MaxConcurrent if limit <= 0 { limit = account.DefaultMaxConcurrent diff --git a/backend/internal/application/gateway/selector_layered_test.go b/backend/internal/application/gateway/selector_layered_test.go index 68acd7ce..21788442 100644 --- a/backend/internal/application/gateway/selector_layered_test.go +++ b/backend/internal/application/gateway/selector_layered_test.go @@ -35,6 +35,8 @@ type layeredAccountRepository struct { materialErrors map[uint64]error materials map[uint64]account.CredentialMaterial materialCalls []uint64 + healthUpdates []repository.InvalidationEvent + lastUsedAt map[uint64]time.Time } type temporaryRoutingLoadError struct{ message string } @@ -94,6 +96,33 @@ func (r *layeredAccountRepository) GetCredentialMaterial(_ context.Context, acco return account.CredentialMaterial{AccountID: accountID, Provider: provider, AuthType: account.AuthTypeOAuth, EncryptedAccessToken: "encrypted"}, nil } +func (r *layeredAccountRepository) UpdateHealth(_ context.Context, id uint64, _ account.Provider, failureCount int, cooldownUntil *time.Time, lastError string, _ bool) error { + r.mu.Lock() + defer r.mu.Unlock() + provider := account.ProviderBuild + for _, base := range r.bases { + if base.Credential.ID == id { + provider = base.Credential.Provider + break + } + } + r.healthUpdates = append(r.healthUpdates, repository.InvalidationEvent{ + Kind: repository.InvalidationAccountHealthChanged, Provider: provider, AccountID: id, + FailureCount: failureCount, CooldownUntil: cooldownUntil, + }) + return nil +} + +func (r *layeredAccountRepository) TouchLastUsed(_ context.Context, id uint64, usedAt time.Time) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.lastUsedAt == nil { + r.lastUsedAt = make(map[uint64]time.Time) + } + r.lastUsedAt[id] = usedAt + return nil +} + func (r *layeredAccountRepository) ListRoutingAccountOverlays(_ context.Context, _ account.Provider, modelRouteID uint64, upstreamModel string) (account.RoutingOverlaySnapshot, error) { r.mu.Lock() defer r.mu.Unlock() @@ -151,6 +180,76 @@ func TestSelectorLayeredCacheReusesBaseAcrossModels(t *testing.T) { } } +func TestSelectorHealthInvalidationDoesNotRebuildProviderSnapshots(t *testing.T) { + repo := newLayeredRepositoryFixture() + selector := NewSelector(repo, nil, nil, nil, time.Hour, time.Second, time.Minute) + now := time.Now().UTC() + if _, err := selector.beginSelectionSession(context.Background(), account.ProviderBuild, 0, "model-a", "", "", nil, false); err != nil { + t.Fatal(err) + } + baseCalls, overlayCalls := repo.callCounts("model-a") + + cooldownUntil := now.Add(time.Minute) + selector.ApplyInvalidation(repository.InvalidationEvent{ + Kind: repository.InvalidationAccountHealthChanged, Provider: account.ProviderBuild, AccountID: 1, + FailureCount: 1, CooldownUntil: &cooldownUntil, PublishedAt: now, + }) + _, err := selector.beginSelectionSession(context.Background(), account.ProviderBuild, 0, "model-a", "", "", nil, false) + var unavailable *SelectionUnavailableError + if !errors.As(err, &unavailable) || unavailable.Reason != SelectionCooling { + t.Fatalf("selection error = %v, want cooling", err) + } + if currentBase, currentOverlay := repo.callCounts("model-a"); currentBase != baseCalls || currentOverlay != overlayCalls { + t.Fatalf("health update rebuilt snapshots: base %d->%d overlay %d->%d", baseCalls, currentBase, overlayCalls, currentOverlay) + } + + selector.ApplyInvalidation(repository.InvalidationEvent{ + Kind: repository.InvalidationAccountHealthChanged, Provider: account.ProviderBuild, AccountID: 1, PublishedAt: time.Now().UTC(), + }) + if _, err := selector.beginSelectionSession(context.Background(), account.ProviderBuild, 0, "model-a", "", "", nil, false); err != nil { + t.Fatalf("cleared health override did not restore account: %v", err) + } + if currentBase, currentOverlay := repo.callCounts("model-a"); currentBase != baseCalls || currentOverlay != overlayCalls { + t.Fatalf("health recovery rebuilt snapshots: base %d->%d overlay %d->%d", baseCalls, currentBase, overlayCalls, currentOverlay) + } + + selector.MarkFailure(context.Background(), repo.bases[0].Credential, 500, 0) + _, err = selector.beginSelectionSession(context.Background(), account.ProviderBuild, 0, "model-a", "", "", nil, false) + if !errors.As(err, &unavailable) || unavailable.Reason != SelectionCooling { + t.Fatalf("mark failure selection error = %v, want cooling", err) + } + if currentBase, currentOverlay := repo.callCounts("model-a"); currentBase != baseCalls || currentOverlay != overlayCalls { + t.Fatalf("mark failure rebuilt snapshots: base %d->%d overlay %d->%d", baseCalls, currentBase, overlayCalls, currentOverlay) + } +} + +func TestSelectorHealthInvalidationRejectsOlderAccountRevision(t *testing.T) { + selector := NewSelector(nil, nil, nil, nil, time.Hour, time.Second, time.Minute) + now := time.Now().UTC() + cooldownUntil := now.Add(time.Minute) + selector.ApplyInvalidation(repository.InvalidationEvent{ + Kind: repository.InvalidationAccountHealthChanged, Provider: account.ProviderBuild, AccountID: 7, + FailureCount: 2, CooldownUntil: &cooldownUntil, Revision: 20, PublishedAt: now, + }) + selector.ApplyInvalidation(repository.InvalidationEvent{ + Kind: repository.InvalidationAccountHealthChanged, Provider: account.ProviderBuild, AccountID: 7, + Revision: 19, PublishedAt: now.Add(time.Second), + }) + value := selector.applyRoutingHealth(account.Credential{ID: 7, Provider: account.ProviderBuild}, now) + if value.FailureCount != 2 || value.CooldownUntil == nil || !value.CooldownUntil.Equal(cooldownUntil) { + t.Fatalf("older recovery replaced newer cooldown: %#v", value) + } + + selector.ApplyInvalidation(repository.InvalidationEvent{ + Kind: repository.InvalidationAccountHealthChanged, Provider: account.ProviderBuild, AccountID: 7, + Revision: 21, PublishedAt: now.Add(2 * time.Second), + }) + value = selector.applyRoutingHealth(value, now) + if value.FailureCount != 0 || value.CooldownUntil != nil || value.LastError != "" { + t.Fatalf("newer recovery was not applied: %#v", value) + } +} + func TestSelectorLayeredCacheUsesLastGoodSnapshotOnTransientLoadFailure(t *testing.T) { repo := newLayeredRepositoryFixture() selector := NewSelector(repo, nil, nil, nil, time.Hour, time.Second, time.Minute) diff --git a/backend/internal/application/gateway/selector_plan.go b/backend/internal/application/gateway/selector_plan.go index d5943344..4565d3e8 100644 --- a/backend/internal/application/gateway/selector_plan.go +++ b/backend/internal/application/gateway/selector_plan.go @@ -111,7 +111,7 @@ func (s *Selector) planCandidateIndexes(ctx context.Context, values []account.Ro return s.planCandidateIndexesWithHints(ctx, values, indexes, now, tierOrder, nil, s.preferFreeBuildEnabled()) } -func (s *Selector) planCandidateIndexesWithHints(ctx context.Context, values []account.RoutingCandidate, indexes []int, now time.Time, tierOrder []account.WebTier, concurrencyHints []int, preferFreeBuild bool) (*candidatePlan, error) { +func (s *Selector) planCandidateIndexesWithHints(ctx context.Context, values []account.RoutingCandidate, indexes []int, now time.Time, tierOrder []account.WebTier, concurrencyHints map[int]int, preferFreeBuild bool) (*candidatePlan, error) { length := len(indexes) if indexes == nil { length = len(values) @@ -141,7 +141,7 @@ func (s *Selector) planCandidateIndexesWithHints(ctx context.Context, values []a if indexes != nil { index = indexes[position] } - if concurrencyHints[index] != 0 { + if _, exists := concurrencyHints[index]; exists { continue } missingIndexes = append(missingIndexes, index) @@ -153,7 +153,7 @@ func (s *Selector) planCandidateIndexesWithHints(ctx context.Context, values []a return nil, err } for position, index := range missingIndexes { - concurrencyHints[index] = concurrencySnapshot[keys[position]] + 1 + concurrencyHints[index] = concurrencySnapshot[keys[position]] } } for position := range length { @@ -161,7 +161,7 @@ func (s *Selector) planCandidateIndexesWithHints(ctx context.Context, values []a if indexes != nil { index = indexes[position] } - inFlight[position] = concurrencyHints[index] - 1 + inFlight[position] = concurrencyHints[index] } } @@ -210,21 +210,20 @@ func (s *Selector) planCandidateIndexesWithHints(ctx context.Context, values []a func (s *Selector) loadConcurrencySnapshot(ctx context.Context, keys []string) (map[string]int, error) { cacheKey := concurrencySnapshotKey(keys) load := func() (map[string]int, error) { - values := make(map[string]int, len(keys)) if batchReader, ok := s.concurrency.(repository.ConcurrencySnapshotReader); ok { - var err error - values, err = batchReader.CurrentMany(ctx, keys) + values, err := batchReader.CurrentMany(ctx, keys) if err != nil { return nil, fmt.Errorf("批量读取账号并发租约: %w", err) } - } else { - for _, key := range keys { - current, err := s.concurrency.Current(ctx, key) - if err != nil { - return nil, fmt.Errorf("读取账号并发租约: %w", err) - } - values[key] = current + return values, nil + } + values := make(map[string]int, len(keys)) + for _, key := range keys { + current, err := s.concurrency.Current(ctx, key) + if err != nil { + return nil, fmt.Errorf("读取账号并发租约: %w", err) } + values[key] = current } return values, nil } diff --git a/backend/internal/application/gateway/selector_segmented.go b/backend/internal/application/gateway/selector_segmented.go index 8ee6035e..580fef36 100644 --- a/backend/internal/application/gateway/selector_segmented.go +++ b/backend/internal/application/gateway/selector_segmented.go @@ -23,6 +23,8 @@ type segmentedSelectorState struct { type segmentedSelectorCohort struct { supportsModel bool capabilityKnown bool + quotaKnown bool + quotaAvailable bool preferFreeBuild bool tier int priority int @@ -95,6 +97,12 @@ func segmentedSelectorCohortBetter(left, right segmentedSelectorCohort) bool { if left.capabilityKnown != right.capabilityKnown { return left.capabilityKnown } + if left.quotaAvailable != right.quotaAvailable { + return left.quotaAvailable + } + if left.quotaKnown != right.quotaKnown { + return left.quotaKnown + } if left.preferFreeBuild != right.preferFreeBuild { return left.preferFreeBuild } diff --git a/backend/internal/application/gateway/selector_segmented_active.go b/backend/internal/application/gateway/selector_segmented_active.go index 948ff5b0..503b2ef9 100644 --- a/backend/internal/application/gateway/selector_segmented_active.go +++ b/backend/internal/application/gateway/selector_segmented_active.go @@ -21,6 +21,14 @@ type segmentedSelectorCohortBucket struct { indexes []int } +type segmentedCohortSelection struct { + count int + start int + take int + seen int + indexes []int +} + type segmentedClaimResult struct { lease *accountLease staleClaims int @@ -76,13 +84,13 @@ func (s *Selector) acquireSegmentedCandidates(ctx context.Context, values []acco return nil, &SelectionUnavailableError{Reason: SelectionNoAccounts} } } else { - concurrencyHints := make([]int, len(values)) - cohorts := segmentedCandidateCohorts(values, indexes, now, tierOrder, preferFreeBuild) + concurrencyHints := make(map[int]int, min(len(indexes), request.windowSize*segmentedWindowsBeforeFullFallback)) + cohorts := segmentedCandidateCohorts(values, indexes, now, tierOrder, preferFreeBuild, request.cursor, request.windowSize, segmentedWindowsBeforeFullFallback) roundWindows := 0 fallbackToFull := false for cohortIndex, bucket := range cohorts { for windowOffset := 0; windowOffset < len(bucket.indexes); windowOffset += request.windowSize { - windowIndexes := segmentedCohortWindow(bucket.indexes, request.cursor, windowOffset, request.windowSize) + windowIndexes := bucket.indexes[windowOffset:min(windowOffset+request.windowSize, len(bucket.indexes))] windowsScanned++ roundWindows++ candidatesScanned += len(windowIndexes) @@ -170,6 +178,8 @@ func (s *Selector) claimSegmentedPlan(ctx context.Context, plan *candidatePlan, } lease.Billing = candidate.Billing lease.QuotaMode = effectiveQuotaMode(candidate, quotaMode) + selected := candidate + lease.routingCandidate = &selected lease.selectorObservation = &selectorLeaseObservation{provider: provider, stage: stage} result.lease = lease return result, nil @@ -177,48 +187,85 @@ func (s *Selector) claimSegmentedPlan(ctx context.Context, plan *candidatePlan, return result, nil } -func segmentedCandidateCohorts(values []account.RoutingCandidate, indexes []int, now time.Time, tierOrder []account.WebTier, preferFreeBuild bool) []segmentedSelectorCohortBucket { - buckets := make(map[segmentedSelectorCohort][]int) - appendCandidate := func(index int) { +func segmentedCandidateCohorts(values []account.RoutingCandidate, indexes []int, now time.Time, tierOrder []account.WebTier, preferFreeBuild bool, cursor uint64, windowSize, maxWindows int) []segmentedSelectorCohortBucket { + if windowSize <= 0 || maxWindows <= 0 { + return nil + } + cohortFor := func(index int) segmentedSelectorCohort { candidate := values[index] cohort := segmentedSelectorCohort{ supportsModel: candidate.SupportsModel, capabilityKnown: candidate.ModelCapabilityKnown, preferFreeBuild: preferFreeBuild && candidate.IsKnownFreeBuild(), tier: tierOrderRank(tierOrder, candidate.Credential.WebTier), priority: candidate.Credential.Priority, } + if candidate.QuotaWindow != nil && candidate.QuotaWindow.Source == account.QuotaSourceUpstream { + cohort.quotaKnown = true + cohort.quotaAvailable = candidate.QuotaWindow.Remaining > 0 + } if candidate.Billing != nil { cohort.billingFresh = now.Sub(candidate.Billing.SyncedAt) <= 30*time.Minute } - buckets[cohort] = append(buckets[cohort], index) + return cohort } + counts := make(map[segmentedSelectorCohort]int) + countCandidate := func(index int) { counts[cohortFor(index)]++ } if indexes == nil { for index := range values { - appendCandidate(index) + countCandidate(index) } } else { for _, index := range indexes { - appendCandidate(index) + countCandidate(index) } } - result := make([]segmentedSelectorCohortBucket, 0, len(buckets)) - for cohort, cohortIndexes := range buckets { - result = append(result, segmentedSelectorCohortBucket{cohort: cohort, indexes: cohortIndexes}) + ordered := make([]segmentedSelectorCohort, 0, len(counts)) + for cohort := range counts { + ordered = append(ordered, cohort) } - sort.Slice(result, func(left, right int) bool { - return segmentedSelectorCohortBetter(result[left].cohort, result[right].cohort) + sort.Slice(ordered, func(left, right int) bool { + return segmentedSelectorCohortBetter(ordered[left], ordered[right]) }) - return result -} -func segmentedCohortWindow(indexes []int, cursor uint64, offset, windowSize int) []int { - if len(indexes) == 0 || offset >= len(indexes) || windowSize <= 0 { - return nil + remainingWindows := maxWindows + selections := make(map[segmentedSelectorCohort]*segmentedCohortSelection) + result := make([]segmentedSelectorCohortBucket, 0, min(len(ordered), maxWindows)) + for _, cohort := range ordered { + if remainingWindows == 0 { + break + } + count := counts[cohort] + take := min(count, remainingWindows*windowSize) + windows := (take + windowSize - 1) / windowSize + remainingWindows -= windows + selection := &segmentedCohortSelection{ + count: count, start: int(cursor % uint64(count)), take: take, indexes: make([]int, take), + } + selections[cohort] = selection + result = append(result, segmentedSelectorCohortBucket{cohort: cohort, indexes: selection.indexes}) } - count := min(windowSize, len(indexes)-offset) - start := int(cursor % uint64(len(indexes))) - result := make([]int, count) - for position := range count { - result[position] = indexes[(start+offset+position)%len(indexes)] + fillCandidate := func(index int) { + selection := selections[cohortFor(index)] + if selection == nil { + return + } + position := selection.seen + selection.seen++ + relative := position - selection.start + if relative < 0 { + relative += selection.count + } + if relative < selection.take { + selection.indexes[relative] = index + } + } + if indexes == nil { + for index := range values { + fillCandidate(index) + } + } else { + for _, index := range indexes { + fillCandidate(index) + } } return result } diff --git a/backend/internal/application/gateway/selector_segmented_active_test.go b/backend/internal/application/gateway/selector_segmented_active_test.go index 2552b87d..4546dae9 100644 --- a/backend/internal/application/gateway/selector_segmented_active_test.go +++ b/backend/internal/application/gateway/selector_segmented_active_test.go @@ -29,6 +29,23 @@ func BenchmarkSelectorSegmentedCandidatePlanning(b *testing.B) { } } +func TestSegmentedCandidateCohortsRetainOnlyBoundedRotatingWindows(t *testing.T) { + const candidateCount = 10_000 + values := make([]account.RoutingCandidate, candidateCount) + for index := range values { + values[index] = account.RoutingCandidate{Credential: account.Credential{ + ID: uint64(index + 1), Provider: account.ProviderBuild, Priority: account.DefaultPriority, + }} + } + buckets := segmentedCandidateCohorts(values, nil, time.Now().UTC(), nil, false, 9980, 64, segmentedWindowsBeforeFullFallback) + if len(buckets) != 1 || len(buckets[0].indexes) != 256 { + t.Fatalf("bounded cohorts = %#v", buckets) + } + if buckets[0].indexes[0] != 9980 || buckets[0].indexes[19] != 9999 || buckets[0].indexes[20] != 0 || buckets[0].indexes[255] != 235 { + t.Fatalf("rotating indexes = first:%d before-wrap:%d after-wrap:%d last:%d", buckets[0].indexes[0], buckets[0].indexes[19], buckets[0].indexes[20], buckets[0].indexes[255]) + } +} + func benchmarkSegmentedSelector(b *testing.B, candidateCount int, enabled, forceFullFallback bool) { b.Helper() limiter := newSegmentedSelectiveLimiter() @@ -187,15 +204,20 @@ func TestSegmentedActiveCohortOrderingMatchesFullPlannerHardOrder(t *testing.T) cohorts := make([]segmentedSelectorCohort, 0, 64) for _, supportsModel := range []bool{false, true} { for _, capabilityKnown := range []bool{false, true} { - for _, preferFreeBuild := range []bool{false, true} { - for _, tier := range []int{0, 2} { - for _, priority := range []int{1, 10} { - for _, billingFresh := range []bool{false, true} { - cohorts = append(cohorts, segmentedSelectorCohort{ - supportsModel: supportsModel, capabilityKnown: capabilityKnown, - preferFreeBuild: preferFreeBuild, tier: tier, priority: priority, - billingFresh: billingFresh, - }) + for _, quotaKnown := range []bool{false, true} { + for _, quotaAvailable := range []bool{false, true} { + for _, preferFreeBuild := range []bool{false, true} { + for _, tier := range []int{0, 2} { + for _, priority := range []int{1, 10} { + for _, billingFresh := range []bool{false, true} { + cohorts = append(cohorts, segmentedSelectorCohort{ + supportsModel: supportsModel, capabilityKnown: capabilityKnown, + quotaKnown: quotaKnown, quotaAvailable: quotaAvailable, + preferFreeBuild: preferFreeBuild, tier: tier, priority: priority, + billingFresh: billingFresh, + }) + } + } } } } @@ -212,8 +234,8 @@ func TestSegmentedActiveCohortOrderingMatchesFullPlannerHardOrder(t *testing.T) {Credential: account.Credential{ID: 2, Priority: right.priority}, SupportsModel: right.supportsModel, ModelCapabilityKnown: right.capabilityKnown}, } scores := []candidateScore{ - {index: 0, tier: left.tier, preferFreeBuild: left.preferFreeBuild, billingFresh: left.billingFresh}, - {index: 1, tier: right.tier, preferFreeBuild: right.preferFreeBuild, billingFresh: right.billingFresh}, + {index: 0, tier: left.tier, quotaKnown: left.quotaKnown, quotaAvailable: left.quotaAvailable, preferFreeBuild: left.preferFreeBuild, billingFresh: left.billingFresh}, + {index: 1, tier: right.tier, quotaKnown: right.quotaKnown, quotaAvailable: right.quotaAvailable, preferFreeBuild: right.preferFreeBuild, billingFresh: right.billingFresh}, } if got, want := segmentedSelectorCohortBetter(left, right), candidateScoreBetter(values, scores[0], scores[1]); got != want { t.Fatalf("cohort order mismatch at %d/%d: got %t want %t", leftIndex, rightIndex, got, want) @@ -320,6 +342,34 @@ func TestSegmentedActiveFallsBackToFullPlannerAfterBoundedWindows(t *testing.T) } } +func TestSegmentedActiveBindsAndReusesStickyAccount(t *testing.T) { + limiter := newSegmentedSelectiveLimiter() + selector := newSegmentedActiveTestSelector(100, limiter, nil) + selector.UpdateSegmentedSelector(true, 100, 8) + + first, err := selector.Acquire(context.Background(), account.ProviderBuild, 0, "model", "", "sticky-session", nil, false) + if err != nil { + t.Fatal(err) + } + selectedID := first.Credential.ID + first.Release() + if sizes := limiter.BatchSizes(); fmt.Sprint(sizes) != "[8]" { + t.Fatalf("initial sticky selection did not use bounded window: %v", sizes) + } + + second, err := selector.Acquire(context.Background(), account.ProviderBuild, 0, "model", "", "sticky-session", nil, false) + if err != nil { + t.Fatal(err) + } + defer second.Release() + if second.Credential.ID != selectedID { + t.Fatalf("sticky account = %d, want %d", second.Credential.ID, selectedID) + } + if sizes := limiter.BatchSizes(); fmt.Sprint(sizes) != "[8]" { + t.Fatalf("sticky reuse rebuilt concurrency plan: %v", sizes) + } +} + func TestSegmentedActiveWaitsAndRescansAfterCapacityReturns(t *testing.T) { limiter := newSegmentedSelectiveLimiter() for id := uint64(1); id <= 100; id++ { @@ -406,17 +456,15 @@ func TestSegmentedActiveUsesFullPlannerAfterExhaustingSmallPool(t *testing.T) { } } -func TestSegmentedActiveSkipsStickyPinnedAndSmallPools(t *testing.T) { +func TestSegmentedActiveSkipsPinnedAndSmallPools(t *testing.T) { tests := []struct { - name string - count int - affinity string - pinned bool - enabled bool + name string + count int + pinned bool + enabled bool }{ {name: "disabled", count: 100}, {name: "small pool", count: 99, enabled: true}, - {name: "sticky", count: 100, affinity: "session", enabled: true}, {name: "pinned", count: 100, pinned: true, enabled: true}, } for _, test := range tests { @@ -429,7 +477,7 @@ func TestSegmentedActiveSkipsStickyPinnedAndSmallPools(t *testing.T) { if test.pinned { lease, err = selector.AcquirePinned(context.Background(), account.ProviderBuild, 1, 0, "model", "", true) } else { - lease, err = selector.Acquire(context.Background(), account.ProviderBuild, 0, "model", "", test.affinity, nil, false) + lease, err = selector.Acquire(context.Background(), account.ProviderBuild, 0, "model", "", "", nil, false) } if err != nil { t.Fatal(err) diff --git a/backend/internal/application/gateway/selector_session.go b/backend/internal/application/gateway/selector_session.go index 352261a3..47211257 100644 --- a/backend/internal/application/gateway/selector_session.go +++ b/backend/internal/application/gateway/selector_session.go @@ -46,6 +46,7 @@ func (s *Selector) beginSelectionSessionForKey(ctx context.Context, provider acc return nil, err } quotaConsumed := s.quotaConsumptionSnapshot(provider) + healthOverrides := s.routingHealthSnapshot(provider, now) session = &selectionSession{ selector: s, @@ -66,7 +67,7 @@ func (s *Selector) beginSelectionSessionForKey(ctx context.Context, provider acc var earliestRetry time.Time for index, candidate := range values { - value := candidate.Credential + value := applyHealthSnapshot(candidate.Credential, healthOverrides) if !accountScopeAllowsCandidate(provider, accountScope, candidate) { continue } @@ -252,12 +253,18 @@ func (session *selectionSession) acquireNormal(ctx context.Context, excluded map } } } - if session.stickyKey == "" { - indexes := session.unexcludedNormalIndexes(excluded) - activeRequest := session.selector.nextSegmentedActiveRequest(session.provider, session.upstreamModel, session.quotaMode, len(indexes)) - if activeRequest != nil { - return session.selector.acquireSegmentedCandidates(ctx, session.values, indexes, session.quotaMode, session.selector.resolveTierOrder(session.provider, session.upstreamModel), *activeRequest) + indexes := session.unexcludedNormalIndexes(excluded) + activeRequest := session.selector.nextSegmentedActiveRequest(session.provider, session.upstreamModel, session.quotaMode, len(indexes)) + if activeRequest != nil { + lease, err := session.selector.acquireSegmentedCandidates(ctx, session.values, indexes, session.quotaMode, session.selector.resolveTierOrder(session.provider, session.upstreamModel), *activeRequest) + if err != nil || lease == nil || session.stickyKey == "" { + return lease, err } + if lease.routingCandidate == nil { + lease.Release() + return nil, errors.New("分段选号缺少候选上下文") + } + return session.completeNormalLease(ctx, lease, *lease.routingCandidate, excluded) } deadline := time.Now().Add(capacityWait) @@ -353,6 +360,9 @@ func (session *selectionSession) hasUnexcludedNormal(excluded map[uint64]bool) b } func (session *selectionSession) unexcludedNormalIndexes(excluded map[uint64]bool) []int { + if len(excluded) == 0 && len(session.staleCandidates) == 0 { + return session.normalCandidates + } indexes := make([]int, 0, len(session.normalCandidates)) for _, index := range session.normalCandidates { if !session.candidateExcluded(excluded, session.values[index].Credential.ID) { diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index ff5862a1..6afc8c9f 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -362,7 +362,7 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) { adapter.resetAttempts() expiredCooldown := time.Now().UTC().Add(-time.Minute) for _, accountID := range []uint64{first.ID, second.ID} { - if err := accountRepo.UpdateHealth(ctx, accountID, 3, &expiredCooldown, "previous upstream failures", false); err != nil { + if err := accountRepo.UpdateHealth(ctx, accountID, account.ProviderBuild, 3, &expiredCooldown, "previous upstream failures", false); err != nil { t.Fatal(err) } } @@ -473,7 +473,7 @@ type blockingHealthAccountRepository struct { once sync.Once } -func (r *blockingHealthAccountRepository) UpdateHealth(ctx context.Context, id uint64, failureCount int, cooldownUntil *time.Time, lastError string, success bool) error { +func (r *blockingHealthAccountRepository) UpdateHealth(ctx context.Context, id uint64, provider account.Provider, failureCount int, cooldownUntil *time.Time, lastError string, success bool) error { if !success { r.once.Do(func() { close(r.started) }) select { @@ -482,7 +482,7 @@ func (r *blockingHealthAccountRepository) UpdateHealth(ctx context.Context, id u return ctx.Err() } } - return r.AccountRepository.UpdateHealth(ctx, id, failureCount, cooldownUntil, lastError, success) + return r.AccountRepository.UpdateHealth(ctx, id, provider, failureCount, cooldownUntil, lastError, success) } func TestRoutingAttemptPolicy(t *testing.T) { diff --git a/backend/internal/application/invalidation/service.go b/backend/internal/application/invalidation/service.go index e711ce69..b35167b2 100644 --- a/backend/internal/application/invalidation/service.go +++ b/backend/internal/application/invalidation/service.go @@ -101,6 +101,7 @@ func (s *Service) RunPublisher(ctx context.Context) error { type invalidationKey struct { layer repository.InvalidationLayer provider string + accountID uint64 clientKeyID uint64 } @@ -108,6 +109,10 @@ func eventKey(event repository.InvalidationEvent) invalidationKey { key := invalidationKey{layer: event.Layer(), provider: string(event.Provider)} if key.layer == repository.InvalidationLayerClientKey { key.clientKeyID = event.ClientKeyID + } else if event.Kind == repository.InvalidationAccountHealthChanged { + // Health events are intentionally account-scoped. Coalescing different + // accounts would silently drop cooldown updates on multi-replica setups. + key.accountID = event.AccountID } return key } diff --git a/backend/internal/application/invalidation/service_test.go b/backend/internal/application/invalidation/service_test.go index 861dbd99..85d25876 100644 --- a/backend/internal/application/invalidation/service_test.go +++ b/backend/internal/application/invalidation/service_test.go @@ -106,3 +106,11 @@ func TestEventKeyKeepsClientKeyInvalidationsDistinct(t *testing.T) { t.Fatalf("client-key invalidation keys were coalesced: first=%#v second=%#v global=%#v", first, second, global) } } + +func TestEventKeyKeepsAccountHealthInvalidationsDistinct(t *testing.T) { + first := eventKey(repository.InvalidationEvent{Kind: repository.InvalidationAccountHealthChanged, Provider: account.ProviderBuild, AccountID: 1}) + second := eventKey(repository.InvalidationEvent{Kind: repository.InvalidationAccountHealthChanged, Provider: account.ProviderBuild, AccountID: 2}) + if first == second { + t.Fatalf("account health invalidations were coalesced: first=%#v second=%#v", first, second) + } +} diff --git a/backend/internal/infra/config/config.go b/backend/internal/infra/config/config.go index a2efc88b..d7613841 100644 --- a/backend/internal/infra/config/config.go +++ b/backend/internal/infra/config/config.go @@ -831,7 +831,7 @@ func defaultConfig() Config { MarkBuildChatDeniedAsReauth: false, PreferFreeBuild: false, AccountIsolatedConnections: false, - SegmentedSelectorEnabled: false, + SegmentedSelectorEnabled: true, SegmentedMinCandidates: 3000, SegmentedWindowSize: 64, ReasoningReplayEnabled: true, diff --git a/backend/internal/infra/config/config_test.go b/backend/internal/infra/config/config_test.go index f1c3b56b..9e2b2fa1 100644 --- a/backend/internal/infra/config/config_test.go +++ b/backend/internal/infra/config/config_test.go @@ -151,7 +151,7 @@ bootstrapAdmin: if cfg.Routing.PreferFreeBuild { t.Fatal("preferFreeBuild should retain its false default when omitted from YAML") } - if cfg.Routing.SegmentedSelectorEnabled || cfg.Routing.SegmentedMinCandidates != 3000 || cfg.Routing.SegmentedWindowSize != 64 { + if !cfg.Routing.SegmentedSelectorEnabled || cfg.Routing.SegmentedMinCandidates != 3000 || cfg.Routing.SegmentedWindowSize != 64 { t.Fatalf("segmented selector defaults = %#v", cfg.Routing) } if cfg.Accounts.AutoCleanReauthEnabled || cfg.Accounts.AutoCleanIncludeDisabled { diff --git a/backend/internal/infra/persistence/relational/account_repository.go b/backend/internal/infra/persistence/relational/account_repository.go index 81491d6c..ff4aa29f 100644 --- a/backend/internal/infra/persistence/relational/account_repository.go +++ b/backend/internal/infra/persistence/relational/account_repository.go @@ -685,7 +685,7 @@ func (r *AccountRepository) ListRoutingAccountOverlays(ctx context.Context, prov var states []accountModelSyncStateModel if err := r.db.db.WithContext(ctx). Table("account_model_sync_states AS state"). - Select("state.*"). + Select("state.account_id"). Joins("JOIN provider_accounts AS account ON account.id = state.account_id"). Where("account.provider = ? AND account.enabled = TRUE AND state.last_success_at IS NOT NULL", provider). Find(&states).Error; err != nil { @@ -700,7 +700,7 @@ func (r *AccountRepository) ListRoutingAccountOverlays(ctx context.Context, prov var capabilities []accountModelCapabilityModel if err := r.db.db.WithContext(ctx). Table("account_model_capabilities AS capability"). - Select("capability.*"). + Select("capability.account_id"). Joins("JOIN provider_accounts AS account ON account.id = capability.account_id"). Where("account.provider = ? AND account.enabled = TRUE AND capability.upstream_model = ?", provider, upstreamModel). Find(&capabilities).Error; err != nil { @@ -715,7 +715,7 @@ func (r *AccountRepository) ListRoutingAccountOverlays(ctx context.Context, prov var blockRows []accountModelQuotaBlockModel if err := r.db.db.WithContext(ctx). Table("account_model_quota_blocks AS block"). - Select("block.*"). + Select("block.account_id", "block.upstream_model", "block.reason", "block.cooldown_until", "block.updated_at"). Joins("JOIN provider_accounts AS account ON account.id = block.account_id"). Where("account.provider = ? AND account.enabled = TRUE AND block.upstream_model = ? AND block.cooldown_until > ?", provider, upstreamModel, time.Now().UTC()). Find(&blockRows).Error; err != nil { @@ -2068,17 +2068,43 @@ func (r *AccountRepository) MarkBuildAPIFallback(ctx context.Context, id uint64, return nil } -func (r *AccountRepository) UpdateHealth(ctx context.Context, id uint64, failureCount int, cooldownUntil *time.Time, lastError string, success bool) error { - updates := map[string]any{"failure_count": failureCount, "cooldown_until": cooldownUntil, "last_error": truncate(lastError, 512)} +func (r *AccountRepository) UpdateHealth(ctx context.Context, id uint64, provider account.Provider, failureCount int, cooldownUntil *time.Time, lastError string, success bool) error { + if id == 0 || !provider.IsValid() { + return repository.ErrNotFound + } + failureCount = max(0, failureCount) + lastError = truncate(lastError, 512) + updates := map[string]any{"failure_count": failureCount, "cooldown_until": cooldownUntil, "last_error": lastError} if success { now := time.Now().UTC() updates["last_used_at"] = &now } - err := r.db.db.WithContext(ctx).Model(&accountModel{}).Where("id = ?", id).Updates(updates).Error - if err == nil && !success { - r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountStateChanged, AccountID: id}) + result := r.db.db.WithContext(ctx).Model(&accountModel{}).Where("id = ? AND provider = ?", id, provider).Updates(updates) + if result.Error != nil { + return mapError(result.Error) } - return err + if result.RowsAffected == 0 { + return repository.ErrNotFound + } + r.notifyInvalidation(ctx, repository.InvalidationEvent{ + Kind: repository.InvalidationAccountHealthChanged, Provider: provider, AccountID: id, + FailureCount: failureCount, CooldownUntil: cooldownUntil, + }) + return nil +} + +func (r *AccountRepository) TouchLastUsed(ctx context.Context, id uint64, usedAt time.Time) error { + if id == 0 || usedAt.IsZero() { + return repository.ErrNotFound + } + result := r.db.db.WithContext(ctx).Model(&accountModel{}).Where("id = ?", id).Update("last_used_at", usedAt.UTC()) + if result.Error != nil { + return mapError(result.Error) + } + if result.RowsAffected == 0 { + return repository.ErrNotFound + } + return nil } func (r *AccountRepository) UpsertModelQuotaBlock(ctx context.Context, value account.ModelQuotaBlock) error { @@ -2218,11 +2244,11 @@ func (r *AccountRepository) ClaimQuotaProbe(ctx context.Context, accountID uint6 } func (r *AccountRepository) ClearQuotaRecovery(ctx context.Context, accountID uint64) error { - err := r.db.db.WithContext(ctx).Delete("aRecoveryModel{}, "account_id = ?", accountID).Error - if err == nil { + result := r.db.db.WithContext(ctx).Delete("aRecoveryModel{}, "account_id = ?", accountID) + if result.Error == nil && result.RowsAffected > 0 { r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountRecoveryChanged, AccountID: accountID}) } - return err + return result.Error } func (r *AccountRepository) ResetQuotaState(ctx context.Context, provider account.Provider, accountIDs []uint64) error { diff --git a/backend/internal/infra/persistence/relational/invalidation_test.go b/backend/internal/infra/persistence/relational/invalidation_test.go index a04d3ccb..6083c954 100644 --- a/backend/internal/infra/persistence/relational/invalidation_test.go +++ b/backend/internal/infra/persistence/relational/invalidation_test.go @@ -89,6 +89,53 @@ func TestRoutingMutationsNotifyAfterCommit(t *testing.T) { } } +func TestAccountHealthMutationPublishesPreciseInvalidation(t *testing.T) { + ctx := context.Background() + database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "health-invalidation.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accounts := NewAccountRepository(database) + credential, _, err := accounts.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, Name: "health", SourceKey: "health", EncryptedAccessToken: "encrypted", + Enabled: true, AuthStatus: account.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + var events []repository.InvalidationEvent + accounts.SetInvalidationObserver(func(_ context.Context, event repository.InvalidationEvent) { + events = append(events, event) + }) + cooldownUntil := time.Now().UTC().Add(time.Minute) + if err := accounts.UpdateHealth(ctx, credential.ID, account.ProviderWeb, 2, &cooldownUntil, "wrong provider", false); err != repository.ErrNotFound { + t.Fatalf("mismatched provider error = %v, want not found", err) + } + if len(events) != 0 { + t.Fatalf("mismatched provider emitted invalidation: %#v", events) + } + if err := accounts.UpdateHealth(ctx, credential.ID, credential.Provider, 2, &cooldownUntil, "upstream status 429", false); err != nil { + t.Fatal(err) + } + if len(events) != 1 { + t.Fatalf("health events = %#v", events) + } + event := events[0] + if event.Kind != repository.InvalidationAccountHealthChanged || event.Provider != account.ProviderBuild || event.AccountID != credential.ID || event.FailureCount != 2 || event.CooldownUntil == nil || !event.CooldownUntil.Equal(cooldownUntil) { + t.Fatalf("health event = %#v", event) + } + if err := accounts.TouchLastUsed(ctx, credential.ID, time.Now().UTC()); err != nil { + t.Fatal(err) + } + if len(events) != 1 { + t.Fatalf("last-used touch emitted routing invalidation: %#v", events[1:]) + } +} + func TestClientKeyMutationsNotifyAfterCommit(t *testing.T) { ctx := context.Background() database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "client-key-invalidation.db")) diff --git a/backend/internal/infra/persistence/relational/repository_test.go b/backend/internal/infra/persistence/relational/repository_test.go index 532ce331..42dfb1e2 100644 --- a/backend/internal/infra/persistence/relational/repository_test.go +++ b/backend/internal/infra/persistence/relational/repository_test.go @@ -41,7 +41,7 @@ func TestSchemaAndRepositoryConstraints(t *testing.T) { if err := accountRepo.UpdateObservedModel(context.Background(), created.ID, "grok-observed", observedAt); err != nil { t.Fatal(err) } - if err := accountRepo.UpdateHealth(context.Background(), created.ID, 0, nil, "", true); err != nil { + if err := accountRepo.UpdateHealth(context.Background(), created.ID, created.Provider, 0, nil, "", true); err != nil { t.Fatal(err) } value.Name = "updated" @@ -314,7 +314,7 @@ func TestAccountRepositorySummarizesOperationalStates(t *testing.T) { create(account.ProviderBuild, "build-active") cooldown := create(account.ProviderBuild, "build-cooldown") cooldownUntil := now.Add(time.Hour) - if err := repo.UpdateHealth(ctx, cooldown.ID, 1, &cooldownUntil, "cooldown", false); err != nil { + if err := repo.UpdateHealth(ctx, cooldown.ID, cooldown.Provider, 1, &cooldownUntil, "cooldown", false); err != nil { t.Fatal(err) } disabled := create(account.ProviderBuild, "build-disabled") diff --git a/backend/internal/infra/runtime/memory/store.go b/backend/internal/infra/runtime/memory/store.go index 29f05c9b..de227aad 100644 --- a/backend/internal/infra/runtime/memory/store.go +++ b/backend/internal/infra/runtime/memory/store.go @@ -136,7 +136,9 @@ func (l *ConcurrencyLimiter) Current(_ context.Context, key string) (int, error) } func (l *ConcurrencyLimiter) CurrentMany(_ context.Context, keys []string) (map[string]int, error) { - values := make(map[string]int, len(keys)) + // Most accounts have no active lease. Keep the sparse result contract used + // by the planner instead of allocating one map entry for every candidate. + values := make(map[string]int) if len(keys) == 0 { return values, nil } @@ -177,7 +179,9 @@ func (l *ConcurrencyLimiter) CurrentMany(_ context.Context, keys []string) (map[ shard.mu.Lock() for _, keyIndex := range grouped[offsets[shardIndex]:offsets[shardIndex+1]] { key := keys[keyIndex] - values[key] = shard.counts[key] + if count := shard.counts[key]; count > 0 { + values[key] = count + } } shard.mu.Unlock() } diff --git a/backend/internal/infra/runtime/redis/store.go b/backend/internal/infra/runtime/redis/store.go index 7af0ad51..2ce44b49 100644 --- a/backend/internal/infra/runtime/redis/store.go +++ b/backend/internal/infra/runtime/redis/store.go @@ -586,22 +586,24 @@ func (s *Store) Current(ctx context.Context, key string) (int, error) { } func (s *Store) CurrentMany(ctx context.Context, keys []string) (map[string]int, error) { - values := make(map[string]int, len(keys)) + values := make(map[string]int) if len(keys) == 0 { return values, nil } now := "(" + strconv.FormatInt(time.Now().UTC().UnixMilli(), 10) pipe := s.client.Pipeline() - counts := make(map[string]*redisclient.IntCmd, len(keys)) - for _, key := range keys { + counts := make([]*redisclient.IntCmd, len(keys)) + for index, key := range keys { redisKey := s.key("concurrency", key) - counts[key] = pipe.ZCount(ctx, redisKey, now, "+inf") + counts[index] = pipe.ZCount(ctx, redisKey, now, "+inf") } if _, err := pipe.Exec(ctx); err != nil { return nil, err } - for key, count := range counts { - values[key] = int(count.Val()) + for index, count := range counts { + if value := int(count.Val()); value > 0 { + values[keys[index]] = value + } } return values, nil } diff --git a/backend/internal/repository/account.go b/backend/internal/repository/account.go index bd07fd88..707c7425 100644 --- a/backend/internal/repository/account.go +++ b/backend/internal/repository/account.go @@ -147,7 +147,10 @@ type AccountRepository interface { NextCredentialRefreshDueAt(ctx context.Context) (*time.Time, error) UpdateCredentialRefreshFailure(ctx context.Context, id uint64, failure CredentialRefreshFailure) error UpdateObservedModel(ctx context.Context, id uint64, model string, observedAt time.Time) error - UpdateHealth(ctx context.Context, id uint64, failureCount int, cooldownUntil *time.Time, lastError string, success bool) error + UpdateHealth(ctx context.Context, id uint64, provider account.Provider, failureCount int, cooldownUntil *time.Time, lastError string, success bool) error + // TouchLastUsed persists request activity without changing routing health or + // invalidating candidate snapshots. + TouchLastUsed(ctx context.Context, id uint64, usedAt time.Time) error // MarkBuildAPIFallback 幂等写入 Build 账号的 XAI 推理回退标记;非 Build 账号返回错误。 MarkBuildAPIFallback(ctx context.Context, id uint64, enabled bool) error // MarkWebNSFWEnabled 幂等记录 Web 账号首次确认 NSFW 已开启的时间。 diff --git a/backend/internal/repository/runtime.go b/backend/internal/repository/runtime.go index bf3217c6..429342f7 100644 --- a/backend/internal/repository/runtime.go +++ b/backend/internal/repository/runtime.go @@ -26,6 +26,7 @@ type ConcurrencyLimiter interface { } // ConcurrencySnapshotReader 批量读取并发租约快照;调度器会优先使用它减少远程运行态往返。 +// 返回值允许省略计数为零的键,读取方必须将缺失项视为零。 type ConcurrencySnapshotReader interface { CurrentMany(ctx context.Context, keys []string) (map[string]int, error) } @@ -89,9 +90,13 @@ type SettingsChangeBus interface { type InvalidationKind string const ( - InvalidationRouteChanged InvalidationKind = "route_changed" - InvalidationModelBindingChanged InvalidationKind = "model_binding_changed" - InvalidationAccountStateChanged InvalidationKind = "account_state_changed" + InvalidationRouteChanged InvalidationKind = "route_changed" + InvalidationModelBindingChanged InvalidationKind = "model_binding_changed" + InvalidationAccountStateChanged InvalidationKind = "account_state_changed" + // InvalidationAccountHealthChanged carries the exact request-path health + // mutation for one account. Unlike an arbitrary account state change, it can + // be applied as a small runtime overlay without rebuilding the provider pool. + InvalidationAccountHealthChanged InvalidationKind = "account_health_changed" InvalidationAccountCredentialChanged InvalidationKind = "account_credential_changed" InvalidationAccountCapabilityChanged InvalidationKind = "account_capability_changed" InvalidationAccountBillingChanged InvalidationKind = "account_billing_changed" @@ -116,6 +121,8 @@ type InvalidationEvent struct { AccountID uint64 `json:"accountId,omitempty"` ClientKeyID uint64 `json:"clientKeyId,omitempty"` UpstreamModel string `json:"upstreamModel,omitempty"` + FailureCount int `json:"failureCount,omitempty"` + CooldownUntil *time.Time `json:"cooldownUntil,omitempty"` Revision uint64 `json:"revision,omitempty"` SourceInstance string `json:"sourceInstance,omitempty"` PublishedAt time.Time `json:"publishedAt,omitempty"` @@ -127,7 +134,7 @@ func (e InvalidationEvent) Layer() InvalidationLayer { return InvalidationLayerRoute case InvalidationModelBindingChanged, InvalidationAccountCapabilityChanged, InvalidationAccountModelQuotaChanged: return InvalidationLayerOverlay - case InvalidationAccountStateChanged, InvalidationAccountCredentialChanged, InvalidationAccountBillingChanged, InvalidationAccountQuotaChanged, InvalidationAccountRecoveryChanged: + case InvalidationAccountStateChanged, InvalidationAccountHealthChanged, InvalidationAccountCredentialChanged, InvalidationAccountBillingChanged, InvalidationAccountQuotaChanged, InvalidationAccountRecoveryChanged: return InvalidationLayerBase case InvalidationClientKeyChanged: return InvalidationLayerClientKey @@ -144,6 +151,9 @@ func (e InvalidationEvent) Valid() bool { if layer == InvalidationLayerClientKey { return e.Provider == "" && e.AccountID == 0 && e.UpstreamModel == "" } + if e.Kind == InvalidationAccountHealthChanged { + return e.AccountID != 0 && (e.Provider == account.ProviderBuild || e.Provider == account.ProviderWeb || e.Provider == account.ProviderConsole) + } switch e.Provider { case "", account.ProviderBuild, account.ProviderWeb, account.ProviderConsole: return true diff --git a/config.example.yaml b/config.example.yaml index d6e8c5f0..d4f1da5e 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -91,8 +91,8 @@ routing: reasoningReplayMaxEntries: 10240 # [按需修改] 按账号隔离上游连接池,适合外部 L4/连接哈希负载均衡;会增加连接数、TLS 握手和文件描述符占用。 accountIsolatedConnections: false - # [通常不要修改] 大账号池分段选号默认关闭;启用后仍保留完整池回退和原子并发门禁。 - segmentedSelectorEnabled: false + # [通常不要修改] 大账号池默认使用有界分段选号;保留完整池回退、额度优先级和原子并发门禁。 + segmentedSelectorEnabled: true segmentedSelectorMinCandidates: 3000 segmentedSelectorWindowSize: 64 diff --git a/frontend/src/features/settings/settings-api.ts b/frontend/src/features/settings/settings-api.ts index c09a3d4d..46592637 100644 --- a/frontend/src/features/settings/settings-api.ts +++ b/frontend/src/features/settings/settings-api.ts @@ -142,7 +142,7 @@ const defaultAccountsConfig = (): SettingsConfigDTO["accounts"] => ({ }); function withSettingsDefaults(snapshot: SettingsSnapshotDTO): SettingsSnapshotDTO { const accounts = snapshot.config.accounts ?? defaultAccountsConfig(); - const segmentedSelector = snapshot.config.routing.segmentedSelector ?? { enabled: false, minCandidates: 3000, windowSize: 64 }; + const segmentedSelector = snapshot.config.routing.segmentedSelector ?? { enabled: true, minCandidates: 3000, windowSize: 64 }; return { ...snapshot, config: { @@ -164,7 +164,7 @@ function withSettingsDefaults(snapshot: SettingsSnapshotDTO): SettingsSnapshotDT markBuildChatDeniedAsReauth: snapshot.config.routing.markBuildChatDeniedAsReauth ?? false, accountIsolatedConnections: snapshot.config.routing.accountIsolatedConnections ?? false, segmentedSelector: { - enabled: segmentedSelector.enabled ?? false, + enabled: segmentedSelector.enabled ?? true, minCandidates: segmentedSelector.minCandidates || 3000, windowSize: segmentedSelector.windowSize || 64, }, diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index 28fb1258..4120cd1f 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -995,7 +995,7 @@ const resources = { codesInvalid: "请填写 1–32 个有效错误码,仅支持字母、数字、点、下划线、冒号和连字符。", codesPlaceholder: "permission-denied", }, - settingsRoutingSegmented: { enabled: "启用分段选号", enabledHelp: "仅对达到阈值且没有会话粘性的账号池生效;连续四个窗口满载后自动回退完整池选号。", minCandidates: "启用账号数阈值", minCandidatesHelp: "可用候选账号达到该数量后启用分段选号。", windowSize: "选号窗口大小", windowSizeHelp: "每个分段窗口检查的候选账号数量。" }, + settingsRoutingSegmented: { enabled: "启用分段选号", enabledHelp: "对达到阈值的账号池生效,兼容会话粘性;连续四个窗口满载后自动回退完整池选号。", minCandidates: "启用账号数阈值", minCandidatesHelp: "可用候选账号达到该数量后启用分段选号。", windowSize: "选号窗口大小", windowSizeHelp: "每个分段窗口检查的候选账号数量。" }, settingsRoutingAttempts: { help: "有限模式控制单次请求的路由尝试轮次:初次选择计 1 次,切号或出口重试各增加 1 次,范围为 1–65535;无限制模式会在账号级可切换失败时遍历当前可用账号。", unlimited: "无限制", @@ -1643,7 +1643,7 @@ const resources = { settingsBuildTransport: { responseHeaderTimeout: "Response header timeout", responseHeaderTimeoutHelp: "Maximum time to wait for the first Grok Build response headers after the request body is sent.", streamIdleTimeout: "Stream idle timeout", streamIdleTimeoutHelp: "Maximum wait for new data on an open streaming response before aborting. Covers upstream connections that succeed but go silent mid-stream." }, settingsBuildForbidden: { markInvalid: "Invalidate matching error codes", markInvalidHelp: "When enabled, a Grok Build 403 with a matching error code marks the account invalid and removes it from scheduling.", codes: "Invalidation error codes", codesHelp: "Enter one code per line. Codes match the complete code or error.code value case-insensitively, up to 32 entries.", codesInvalid: "Enter 1–32 valid codes using letters, numbers, dots, underscores, colons, or hyphens.", codesPlaceholder: "permission-denied" }, - settingsRoutingSegmented: { enabled: "Enable segmented selection", enabledHelp: "Applies only above the threshold without session affinity and falls back to full-pool selection after four saturated windows.", minCandidates: "Account threshold", minCandidatesHelp: "Enables segmented selection when the eligible account pool reaches this size.", windowSize: "Selection window", windowSizeHelp: "Number of candidate accounts inspected in each segmented window." }, + settingsRoutingSegmented: { enabled: "Enable segmented selection", enabledHelp: "Applies above the threshold, supports session affinity, and falls back to full-pool selection after four saturated windows.", minCandidates: "Account threshold", minCandidatesHelp: "Enables segmented selection when the eligible account pool reaches this size.", windowSize: "Selection window", windowSizeHelp: "Number of candidate accounts inspected in each segmented window." }, settingsRoutingAttempts: { help: "A finite value limits routing-attempt rounds: initial selection counts as one, and account failover or egress retry adds another. Range: 1–65535. Unlimited mode can traverse all currently eligible accounts after account-scoped failures.", unlimited: "Unlimited", From 543fb5786e9d875736c86effd2710357afc54a68 Mon Sep 17 00:00:00 2001 From: WuxiVIP Date: Fri, 14 Aug 2026 13:11:03 +0800 Subject: [PATCH 37/48] feat(proxy): support VLESS Reality Vision Encode the Vision flow addon and honor Reality ClientHello fingerprints. Reject presets without X25519 TLS 1.3 key shares and preserve explicit ALPN. --- backend/go.mod | 5 + backend/go.sum | 10 + backend/internal/pkg/tunnelproxy/reality.go | 234 ++++++++++++++++++ .../internal/pkg/tunnelproxy/tunnelproxy.go | 131 ++++++++-- .../pkg/tunnelproxy/tunnelproxy_test.go | 138 ++++++++++- 5 files changed, 502 insertions(+), 16 deletions(-) create mode 100644 backend/internal/pkg/tunnelproxy/reality.go diff --git a/backend/go.mod b/backend/go.mod index ea822164..764639ad 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -14,7 +14,10 @@ require ( 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/metacubex/sing v0.5.7 + github.com/metacubex/sing-vmess v0.2.5 github.com/redis/go-redis/v9 v9.21.0 + github.com/refraction-networking/utls v1.6.7 github.com/shadowsocks/go-shadowsocks2 v0.1.5 github.com/swaggo/files v1.0.1 github.com/swaggo/gin-swagger v1.6.1 @@ -41,6 +44,7 @@ require ( github.com/bytedance/sonic v1.15.0 // indirect github.com/bytedance/sonic/loader v0.5.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/cloudflare/circl v1.3.7 // indirect github.com/cloudwego/base64x v0.1.6 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/gabriel-vasile/mimetype v1.4.12 // indirect @@ -55,6 +59,7 @@ require ( github.com/go-playground/validator/v10 v10.30.1 // indirect github.com/goccy/go-json v0.10.5 // indirect github.com/goccy/go-yaml v1.19.2 // indirect + github.com/gofrs/uuid/v5 v5.3.2 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/pgx/v5 v5.6.0 // indirect diff --git a/backend/go.sum b/backend/go.sum index c4c442f6..066a5245 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -36,6 +36,8 @@ github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiD github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cloudflare/circl v1.3.7 h1:qlCDlTPz2n9fu58M0Nh1J/JzcFpfgkFHHX3O35r5vcU= +github.com/cloudflare/circl v1.3.7/go.mod h1:sRTcRWXGLrKw6yIGJ+l7amYJFfAXbZG0kBSc8r4zxgA= 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= @@ -80,6 +82,8 @@ github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +github.com/gofrs/uuid/v5 v5.3.2 h1:2jfO8j3XgSwlz/wHqemAEugfnTlikAYHhnqQ8Xh4fE0= +github.com/gofrs/uuid/v5 v5.3.2/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8= github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= @@ -128,6 +132,10 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= +github.com/metacubex/sing v0.5.7 h1:8OC+fhKFSv/l9ehEhJRaZZAOuthfZo68SteBVLe8QqM= +github.com/metacubex/sing v0.5.7/go.mod h1:ypf0mjwlZm0sKdQSY+yQvmsbWa0hNPtkeqyRMGgoN+w= +github.com/metacubex/sing-vmess v0.2.5 h1:m9Zt5I27lB9fmLMZfism9sH2LcnAfShZfwSkf6/KJoE= +github.com/metacubex/sing-vmess v0.2.5/go.mod h1:AwtlzUgf8COe9tRYAKqWZ+leDH7p5U98a0ZUpYehl8Q= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -154,6 +162,8 @@ github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SA github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU= github.com/redis/go-redis/v9 v9.21.0 h1:FPBE4hhbAke+TLmcY3WkpbDffJEomdqPn3HYiqAtL9E= github.com/redis/go-redis/v9 v9.21.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA= +github.com/refraction-networking/utls v1.6.7 h1:zVJ7sP1dJx/WtVuITug3qYUq034cDq9B2MR1K67ULZM= +github.com/refraction-networking/utls v1.6.7/go.mod h1:BC3O4vQzye5hqpmDTWUqi4P5DDhzJfkV1tdqtawQIH0= 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= diff --git a/backend/internal/pkg/tunnelproxy/reality.go b/backend/internal/pkg/tunnelproxy/reality.go new file mode 100644 index 00000000..e2358ae7 --- /dev/null +++ b/backend/internal/pkg/tunnelproxy/reality.go @@ -0,0 +1,234 @@ +package tunnelproxy + +import ( + "bytes" + "context" + "crypto/aes" + "crypto/cipher" + "crypto/ecdh" + "crypto/ed25519" + "crypto/hmac" + "crypto/sha256" + "crypto/sha512" + "crypto/x509" + "encoding/base64" + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "net" + "time" + + "github.com/Asutorufa/yuhaiin/pkg/net/netapi" + utls "github.com/refraction-networking/utls" + "golang.org/x/crypto/chacha20poly1305" + "golang.org/x/crypto/hkdf" +) + +// realityProxy follows the Xray Reality client handshake used by yuhaiin, but +// keeps the ClientHello selectable so Clash client-fingerprint values are not +// silently replaced with Chrome. +type realityProxy struct { + netapi.EmptyDispatch + dialer netapi.Proxy + serverName string + publicKey *ecdh.PublicKey + shortID [8]byte + helloID utls.ClientHelloID + alpn []string +} + +func newRealityProxy(config Config, dialer netapi.Proxy) (netapi.Proxy, error) { + publicKeyBytes, err := base64.RawURLEncoding.DecodeString(config.RealityPublicKey) + if err != nil { + return nil, fmt.Errorf("解析 Reality public key: %w", err) + } + publicKey, err := ecdh.X25519().NewPublicKey(publicKeyBytes) + if err != nil { + return nil, errors.New("Reality public key 无效") + } + var shortID [8]byte + decodedLength, err := hex.Decode(shortID[:], []byte(config.RealityShortID)) + if err != nil || decodedLength > len(shortID) { + return nil, errors.New("Reality short ID 无效") + } + helloID, ok := realityClientHelloID(config.ClientFingerprint) + if !ok { + return nil, fmt.Errorf("VLESS Reality 暂不支持客户端指纹 %q", config.ClientFingerprint) + } + return &realityProxy{ + dialer: dialer, serverName: config.ServerName, publicKey: publicKey, + shortID: shortID, helloID: helloID, alpn: append([]string(nil), config.ALPN...), + }, nil +} + +func realityClientHelloID(fingerprint string) (utls.ClientHelloID, bool) { + switch fingerprint { + case "chrome": + return utls.HelloChrome_Auto, true + case "firefox": + return utls.HelloFirefox_Auto, true + case "safari": + return utls.HelloSafari_Auto, true + case "ios": + return utls.HelloIOS_Auto, true + case "edge": + return utls.HelloEdge_Auto, true + case "qq": + return utls.HelloQQ_Auto, true + default: + return utls.ClientHelloID{}, false + } +} + +func (p *realityProxy) Conn(ctx context.Context, address netapi.Address) (net.Conn, error) { + connection, err := p.dialer.Conn(ctx, address) + if err != nil { + return nil, err + } + secure, err := p.handshake(ctx, connection) + if err != nil { + _ = connection.Close() + return nil, fmt.Errorf("Reality 握手: %w", err) + } + return secure, nil +} + +func (p *realityProxy) PacketConn(context.Context, netapi.Address) (net.PacketConn, error) { + return nil, errors.New("Reality 隧道不支持 UDP") +} + +func (p *realityProxy) handshake(ctx context.Context, connection net.Conn) (net.Conn, error) { + verifier := &realityVerifier{serverName: p.serverName} + secure, err := buildRealityClientHello(connection, p.serverName, p.alpn, p.helloID, verifier.verifyPeerCertificate) + if err != nil { + return nil, err + } + hello := secure.HandshakeState.Hello + privateKey := secure.HandshakeState.State13.EcdheKey + + hello.SessionId = make([]byte, 32) + copy(hello.Raw[39:], hello.SessionId) + binary.BigEndian.PutUint64(hello.SessionId, uint64(time.Now().Unix())) + hello.SessionId[0] = 1 + hello.SessionId[1] = 8 + hello.SessionId[2] = 1 + copy(hello.SessionId[8:], p.shortID[:]) + + peerKey, err := privateKey.ECDH(p.publicKey) + if err != nil { + return nil, fmt.Errorf("Reality ECDH: %w", err) + } + verifier.authKey = peerKey + if _, err := hkdf.New(sha256.New, peerKey, hello.Random[:20], []byte("REALITY")).Read(peerKey); err != nil { + return nil, err + } + var aead cipher.AEAD + if realityPrefersAESGCM(hello.CipherSuites) { + block, cipherErr := aes.NewCipher(peerKey) + if cipherErr != nil { + return nil, cipherErr + } + aead, err = cipher.NewGCM(block) + } else { + aead, err = chacha20poly1305.New(peerKey) + } + if err != nil { + return nil, err + } + aead.Seal(hello.SessionId[:0], hello.Random[20:], hello.SessionId[:16], hello.Raw) + copy(hello.Raw[39:], hello.SessionId) + + if err := secure.HandshakeContext(ctx); err != nil { + return nil, err + } + if !verifier.verified { + return nil, errors.New("Reality 身份验证失败") + } + return secure, nil +} + +func buildRealityClientHello(connection net.Conn, serverName string, alpn []string, helloID utls.ClientHelloID, verify func([][]byte, [][]*x509.Certificate) error) (*utls.UConn, error) { + config := &utls.Config{ + ServerName: serverName, InsecureSkipVerify: true, SessionTicketsDisabled: true, + NextProtos: append([]string(nil), alpn...), VerifyPeerCertificate: verify, + } + secure := utls.UClient(connection, config, helloID) + if err := secure.BuildHandshakeState(); err != nil { + return nil, err + } + if secure.HandshakeState.Hello == nil || len(secure.HandshakeState.Hello.Raw) < 71 { + return nil, errors.New("Reality ClientHello 无效") + } + if len(alpn) != 0 { + patched := false + for _, extension := range secure.Extensions { + if alpnExtension, ok := extension.(*utls.ALPNExtension); ok { + alpnExtension.AlpnProtocols = append([]string(nil), alpn...) + patched = true + break + } + } + if !patched { + secure.Extensions = append(secure.Extensions, &utls.ALPNExtension{AlpnProtocols: append([]string(nil), alpn...)}) + } + config.NextProtos = append([]string(nil), alpn...) + secure.HandshakeState.Hello.AlpnProtocols = append([]string(nil), alpn...) + } + privateKey := secure.HandshakeState.State13.EcdheKey + if privateKey == nil || privateKey.Curve() != ecdh.X25519() { + return nil, fmt.Errorf("Reality 客户端指纹 %q 未提供 X25519 TLS 1.3 key share", helloID.Client) + } + return secure, nil +} + +func realityPrefersAESGCM(cipherSuites []uint16) bool { + for _, cipherSuite := range cipherSuites { + switch cipherSuite { + case utls.TLS_AES_128_GCM_SHA256, utls.TLS_AES_256_GCM_SHA384, + utls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, utls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, + utls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, utls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: + return true + case utls.TLS_CHACHA20_POLY1305_SHA256, utls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, + utls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: + return false + } + } + return false +} + +type realityVerifier struct { + serverName string + authKey []byte + verified bool +} + +func (v *realityVerifier) verifyPeerCertificate(rawCertificates [][]byte, _ [][]*x509.Certificate) error { + certificates := make([]*x509.Certificate, 0, len(rawCertificates)) + for _, rawCertificate := range rawCertificates { + certificate, err := x509.ParseCertificate(rawCertificate) + if err != nil { + return err + } + certificates = append(certificates, certificate) + } + if len(certificates) == 0 { + return errors.New("Reality 服务端未返回证书") + } + if publicKey, ok := certificates[0].PublicKey.(ed25519.PublicKey); ok { + digest := hmac.New(sha512.New, v.authKey) + _, _ = digest.Write(publicKey) + if bytes.Equal(digest.Sum(nil), certificates[0].Signature) { + v.verified = true + return nil + } + } + options := x509.VerifyOptions{ + DNSName: v.serverName, Intermediates: x509.NewCertPool(), CurrentTime: time.Now(), + } + for _, certificate := range certificates[1:] { + options.Intermediates.AddCert(certificate) + } + _, err := certificates[0].Verify(options) + return err +} diff --git a/backend/internal/pkg/tunnelproxy/tunnelproxy.go b/backend/internal/pkg/tunnelproxy/tunnelproxy.go index c6314036..de0ac340 100644 --- a/backend/internal/pkg/tunnelproxy/tunnelproxy.go +++ b/backend/internal/pkg/tunnelproxy/tunnelproxy.go @@ -16,11 +16,15 @@ import ( "github.com/Asutorufa/yuhaiin/pkg/net/netapi" "github.com/Asutorufa/yuhaiin/pkg/net/proxy/trojan" - "github.com/Asutorufa/yuhaiin/pkg/net/proxy/vless" + visionproxy "github.com/Asutorufa/yuhaiin/pkg/net/proxy/vision" + yuhaiinvless "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" + singvmess "github.com/metacubex/sing-vmess" + singvless "github.com/metacubex/sing-vmess/vless" + singmetadata "github.com/metacubex/sing/common/metadata" sscore "github.com/shadowsocks/go-shadowsocks2/core" "github.com/shadowsocks/go-shadowsocks2/socks" ) @@ -34,9 +38,15 @@ type Config struct { Cipher string Transport string TLS bool + Security string + Flow string ServerName string Insecure bool ALPN []string + RealityPublicKey string + RealityShortID string + ClientFingerprint string + SpiderX string WebSocketHost string WebSocketPath string CanonicalProxyURL string @@ -111,9 +121,7 @@ func parseUserInfoProxy(value string) (Config, error) { 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) - } + flow := strings.ToLower(strings.TrimSpace(query.Get("flow"))) if scheme == "vless" { parsedUUID, err := uuid.Parse(credential) if err != nil { @@ -126,16 +134,39 @@ func parseUserInfoProxy(value string) (Config, error) { } security := strings.ToLower(strings.TrimSpace(query.Get("security"))) tlsEnabled := scheme == "trojan" + securityMode := "none" + if tlsEnabled { + securityMode = "tls" + } switch security { case "", "tls": if security == "tls" { tlsEnabled = true + securityMode = "tls" } case "none": tlsEnabled = false + securityMode = "none" + case "reality": + if scheme != "vless" { + return Config{}, errors.New("Reality security 当前仅支持 VLESS") + } + if transport != "tcp" { + return Config{}, errors.New("VLESS Reality 当前仅支持 TCP 传输") + } + tlsEnabled = true + securityMode = "reality" default: return Config{}, fmt.Errorf("暂不支持 %s security %q", strings.ToUpper(scheme), security) } + if flow != "" { + if scheme != "vless" || flow != "xtls-rprx-vision" { + return Config{}, fmt.Errorf("暂不支持 VLESS flow %q", flow) + } + if transport != "tcp" || (securityMode != "tls" && securityMode != "reality") { + return Config{}, errors.New("VLESS Vision 需要 TCP 和 TLS 或 Reality security") + } + } if headerType := strings.ToLower(strings.TrimSpace(query.Get("headerType"))); headerType != "" && headerType != "none" { return Config{}, fmt.Errorf("暂不支持 %s headerType %q", strings.ToUpper(scheme), headerType) } @@ -144,6 +175,23 @@ func parseUserInfoProxy(value string) (Config, error) { return Config{}, err } serverName := firstNonEmpty(query.Get("sni"), query.Get("peer"), parsed.Hostname()) + realityPublicKey := firstNonEmpty(query.Get("pbk"), query.Get("public-key"), query.Get("publicKey")) + realityShortID := firstNonEmpty(query.Get("sid"), query.Get("short-id"), query.Get("shortId")) + fingerprint := strings.ToLower(firstNonEmpty(query.Get("fp"), query.Get("fingerprint"), query.Get("client-fingerprint"))) + spiderX := firstNonEmpty(query.Get("spx"), query.Get("spider-x"), query.Get("spiderX")) + if securityMode == "reality" { + if realityPublicKey == "" { + return Config{}, errors.New("VLESS Reality public key 不能为空") + } + if fingerprint == "" { + fingerprint = "chrome" + } + if _, supported := realityClientHelloID(fingerprint); !supported { + return Config{}, fmt.Errorf("VLESS Reality 暂不支持客户端指纹 %q", fingerprint) + } + } else if realityPublicKey != "" || realityShortID != "" || fingerprint != "" || spiderX != "" { + return Config{}, errors.New("Reality 参数只能用于 Reality security") + } wsHost := firstNonEmpty(query.Get("host"), serverName) if err := validateWebSocketHost(wsHost); transport == "ws" && err != nil { return Config{}, err @@ -159,8 +207,9 @@ func parseUserInfoProxy(value string) (Config, error) { } 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, + TLS: tlsEnabled, Security: securityMode, Flow: flow, ServerName: serverName, Insecure: insecure, + ALPN: splitList(query.Get("alpn")), RealityPublicKey: realityPublicKey, RealityShortID: realityShortID, + ClientFingerprint: fingerprint, SpiderX: spiderX, WebSocketHost: wsHost, WebSocketPath: wsPath, } config.CanonicalProxyURL = canonicalUserInfoProxyURL(config) if err := validateConfig(config); err != nil { @@ -172,15 +221,29 @@ func parseUserInfoProxy(value string) (Config, error) { 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") + security := config.Security + if security == "" { + security = "none" + if config.TLS { + security = "tls" + } } + query.Set("security", security) if config.Scheme == "vless" { query.Set("encryption", "none") } + if config.Flow != "" { + query.Set("flow", config.Flow) + } query.Set("sni", config.ServerName) + if security == "reality" { + query.Set("pbk", config.RealityPublicKey) + query.Set("sid", config.RealityShortID) + query.Set("fp", config.ClientFingerprint) + if config.SpiderX != "" { + query.Set("spx", config.SpiderX) + } + } if config.Insecure { query.Set("allowInsecure", "1") } @@ -456,6 +519,12 @@ 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.Security == "reality" { + var err error + current, err = newRealityProxy(config, current) + if err != nil { + return nil, fmt.Errorf("创建 Reality 客户端: %w", err) + } } else if config.TLS { current = &tlsProxy{config: config, dialer: current} } @@ -467,7 +536,7 @@ func buildProxy(config Config) (netapi.Proxy, error) { case "vless": protocolConfig := &protocol.Vless{} protocolConfig.SetUuid(config.Credential) - return newOwnedVLESSProxy(protocolConfig, current) + return newOwnedVLESSProxy(protocolConfig, current, config.Flow) case "vmess": protocolConfig := &protocol.Vmess{} protocolConfig.SetUuid(config.Credential) @@ -487,13 +556,23 @@ type ownedVLESSProxy struct { netapi.EmptyDispatch config *protocol.Vless dialer netapi.Proxy + flow string + uuid [16]byte } -func newOwnedVLESSProxy(config *protocol.Vless, dialer netapi.Proxy) (netapi.Proxy, error) { - if _, err := vless.NewClient(config, dialer); err != nil { +func newOwnedVLESSProxy(config *protocol.Vless, dialer netapi.Proxy, flow string) (netapi.Proxy, error) { + if _, err := yuhaiinvless.NewClient(config, dialer); err != nil { return nil, err } - return &ownedVLESSProxy{config: config, dialer: dialer}, nil + proxy := &ownedVLESSProxy{config: config, dialer: dialer, flow: flow} + if flow == "xtls-rprx-vision" { + userID, err := uuid.Parse(config.GetUuid()) + if err != nil { + return nil, errors.New("VLESS Vision UUID 无效") + } + copy(proxy.uuid[:], userID[:]) + } + return proxy, nil } func (p *ownedVLESSProxy) Conn(ctx context.Context, address netapi.Address) (net.Conn, error) { @@ -501,7 +580,20 @@ func (p *ownedVLESSProxy) Conn(ctx context.Context, address netapi.Address) (net if err != nil { return nil, err } - client, err := vless.NewClient(p.config, &singleConnectionProxy{connection: connection}) + if p.flow == "xtls-rprx-vision" { + result, requestErr := newVisionVLESSConn(connection, address, p.uuid, p.flow) + if requestErr != nil { + _ = connection.Close() + return nil, fmt.Errorf("发送 VLESS Vision 请求: %w", requestErr) + } + visionConnection, visionErr := visionproxy.NewVisionConn(result, connection, p.uuid) + if visionErr != nil { + _ = result.Close() + return nil, fmt.Errorf("创建 VLESS Vision 连接: %w", visionErr) + } + return visionConnection, nil + } + client, err := yuhaiinvless.NewClient(p.config, &singleConnectionProxy{connection: connection}) if err != nil { _ = connection.Close() return nil, err @@ -514,6 +606,15 @@ func (p *ownedVLESSProxy) Conn(ctx context.Context, address netapi.Address) (net return result, nil } +func newVisionVLESSConn(connection net.Conn, address netapi.Address, userID [16]byte, flow string) (net.Conn, error) { + destination := singmetadata.ParseSocksaddrHostPort(address.Hostname(), address.Port()) + result := singvless.NewConn(connection, userID, singvmess.CommandTCP, destination, flow) + if _, err := result.Write(nil); err != nil { + 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") } diff --git a/backend/internal/pkg/tunnelproxy/tunnelproxy_test.go b/backend/internal/pkg/tunnelproxy/tunnelproxy_test.go index a34f86a8..c5755fd8 100644 --- a/backend/internal/pkg/tunnelproxy/tunnelproxy_test.go +++ b/backend/internal/pkg/tunnelproxy/tunnelproxy_test.go @@ -16,6 +16,9 @@ import ( "github.com/Asutorufa/yuhaiin/pkg/net/netapi" "github.com/Asutorufa/yuhaiin/pkg/protos/node/protocol" "github.com/coder/websocket" + "github.com/google/uuid" + singvless "github.com/metacubex/sing-vmess/vless" + utls "github.com/refraction-networking/utls" ) const testUUID = "123e4567-e89b-12d3-a456-426614174000" @@ -63,6 +66,100 @@ func TestNormalizeRemarksDoNotChangeIdentity(t *testing.T) { } } +func TestNormalizeRealityVisionBuildsDialer(t *testing.T) { + raw := "vless://" + testUUID + "@proxy.example:443?encryption=none&security=reality&sni=edge.example&type=tcp&flow=xtls-rprx-vision&fp=chrome&pbk=SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8&sid=0123456789abcdef&spx=%2F" + normalized, err := Normalize(raw) + if err != nil { + t.Fatal(err) + } + config, err := Parse(normalized) + if err != nil { + t.Fatal(err) + } + if config.Security != "reality" || config.Flow != "xtls-rprx-vision" || config.RealityPublicKey == "" || config.RealityShortID != "0123456789abcdef" || config.ClientFingerprint != "chrome" || config.SpiderX != "/" { + t.Fatalf("Reality Vision config = %#v", config) + } + if _, err := NewDialer(normalized); err != nil { + t.Fatalf("construct Reality Vision dialer: %v", err) + } + for _, field := range []string{"security=reality", "flow=xtls-rprx-vision", "fp=chrome", "pbk=", "sid=0123456789abcdef", "spx=%2F"} { + if !strings.Contains(normalized, field) { + t.Fatalf("normalized Reality URL missing %q: %s", field, normalized) + } + } +} + +func TestNormalizeRealitySupportsStandardClientFingerprints(t *testing.T) { + for _, fingerprint := range []string{"chrome", "edge", "safari", "firefox", "ios", "qq"} { + t.Run(fingerprint, func(t *testing.T) { + raw := "vless://" + testUUID + "@proxy.example:443?encryption=none&security=reality&sni=edge.example&type=tcp&flow=xtls-rprx-vision&pbk=SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8&sid=0123456789abcdef&fp=" + fingerprint + normalized, err := Normalize(raw) + if err != nil { + t.Fatal(err) + } + config, err := Parse(normalized) + if err != nil { + t.Fatal(err) + } + if config.ClientFingerprint != fingerprint { + t.Fatalf("client fingerprint = %q", config.ClientFingerprint) + } + }) + } +} + +func TestRealityAcceptedFingerprintsProvideX25519AndPreserveALPN(t *testing.T) { + wantedALPN := []string{"h2", "http/1.1"} + for _, fingerprint := range []string{"chrome", "edge", "safari", "firefox", "ios", "qq"} { + t.Run(fingerprint, func(t *testing.T) { + helloID, supported := realityClientHelloID(fingerprint) + if !supported { + t.Fatalf("fingerprint %q unexpectedly unsupported", fingerprint) + } + client, server := net.Pipe() + defer client.Close() + defer server.Close() + secure, err := buildRealityClientHello(client, "edge.example", wantedALPN, helloID, nil) + if err != nil { + t.Fatal(err) + } + if strings.Join(secure.HandshakeState.Hello.AlpnProtocols, ",") != strings.Join(wantedALPN, ",") { + t.Fatalf("ClientHello ALPN = %v", secure.HandshakeState.Hello.AlpnProtocols) + } + foundALPN := false + for _, extension := range secure.Extensions { + alpnExtension, ok := extension.(*utls.ALPNExtension) + if !ok { + continue + } + foundALPN = true + if strings.Join(alpnExtension.AlpnProtocols, ",") != strings.Join(wantedALPN, ",") { + t.Fatalf("ALPN extension = %v", alpnExtension.AlpnProtocols) + } + } + if !foundALPN { + t.Fatal("ClientHello has no ALPN extension") + } + }) + } +} + +func TestRealityClientHelloWithoutTLS13KeyShareReturnsError(t *testing.T) { + for name, helloID := range map[string]utls.ClientHelloID{ + "android": utls.HelloAndroid_11_OkHttp, + "360": utls.Hello360_Auto, + } { + t.Run(name, func(t *testing.T) { + client, server := net.Pipe() + defer client.Close() + defer server.Close() + if _, err := buildRealityClientHello(client, "edge.example", nil, helloID, nil); err == nil { + t.Fatalf("fingerprint %q unexpectedly produced a Reality key share", name) + } + }) + } +} + 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 { @@ -107,7 +204,7 @@ func TestOwnedVLESSProxyClosesConnectionWhenInitialWriteFails(t *testing.T) { tracked := &closeTrackingConn{Conn: client} config := &protocol.Vless{} config.SetUuid(testUUID) - proxy, err := newOwnedVLESSProxy(config, &singleConnectionProxy{connection: tracked}) + proxy, err := newOwnedVLESSProxy(config, &singleConnectionProxy{connection: tracked}, "") if err != nil { t.Fatal(err) } @@ -119,6 +216,41 @@ func TestOwnedVLESSProxyClosesConnectionWhenInitialWriteFails(t *testing.T) { } } +func TestVisionVLESSRequestIncludesFlowAddon(t *testing.T) { + client, server := net.Pipe() + defer server.Close() + + var userID [16]byte + parsedUUID, err := uuid.Parse(testUUID) + if err != nil { + t.Fatal(err) + } + copy(userID[:], parsedUUID[:]) + + result := make(chan error, 1) + go func() { + connection, requestErr := newVisionVLESSConn(client, netapi.ParseDomainPort("tcp", "target.example", 443), userID, "xtls-rprx-vision") + if connection != nil { + _ = connection.Close() + } + result <- requestErr + }() + + request, err := singvless.ReadRequest(server) + if err != nil { + t.Fatal(err) + } + if request.Flow != "xtls-rprx-vision" { + t.Fatalf("VLESS flow addon = %q", request.Flow) + } + if request.Destination.Fqdn != "target.example" || request.Destination.Port != 443 { + t.Fatalf("VLESS destination = %v", request.Destination) + } + if err := <-result; err != nil { + t.Fatal(err) + } +} + func TestTunnelHandshakeContextHasIndependentDeadline(t *testing.T) { ctx, cancel := newTunnelHandshakeContext(context.Background()) defer cancel() @@ -149,6 +281,10 @@ func TestParseRejectsUnsupportedOrMalformedLinks(t *testing.T) { "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", + "vless://" + testUUID + "@proxy.example:443?encryption=none&security=reality&sni=edge.example&pbk=invalid&sid=01", + "vless://" + testUUID + "@proxy.example:443?encryption=none&security=reality&sni=edge.example&pbk=SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8&sid=01&fp=opera", + "vless://" + testUUID + "@proxy.example:443?encryption=none&security=reality&sni=edge.example&pbk=SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8&sid=01&fp=android", + "vless://" + testUUID + "@proxy.example:443?encryption=none&security=reality&sni=edge.example&pbk=SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8&sid=01&fp=360", "trojan://secret@proxy.example:443?type=grpc", "trojan://secret@proxy.example:443/unexpected", "ss://" + base64.RawURLEncoding.EncodeToString([]byte("rc4-md5:secret")) + "@proxy.example:8388", From 5a84f88d1cba2a72bd27ed4c4077a3438fc0d486 Mon Sep 17 00:00:00 2001 From: WuxiVIP Date: Fri, 14 Aug 2026 13:11:21 +0800 Subject: [PATCH 38/48] feat(egress): parse Clash subscriptions Convert HTTP, SOCKS5, Trojan, VLESS, SS, and VMess entries from Clash YAML. Hysteria and TUIC remain unsupported and are skipped. --- .../application/egress/subscription.go | 5 +- .../application/egress/subscription_clash.go | 231 ++++++++++++++++++ .../application/egress/subscription_test.go | 160 ++++++++++++ 3 files changed, 395 insertions(+), 1 deletion(-) create mode 100644 backend/internal/application/egress/subscription_clash.go diff --git a/backend/internal/application/egress/subscription.go b/backend/internal/application/egress/subscription.go index 42ddff98..329c4cde 100644 --- a/backend/internal/application/egress/subscription.go +++ b/backend/internal/application/egress/subscription.go @@ -104,7 +104,7 @@ func fetchProxySubscription(ctx context.Context, value string, viaProxy string) } } request.Header.Set("Accept", "text/plain, text/*;q=0.9, */*;q=0.1") - request.Header.Set("User-Agent", "grok2api-egress-subscription/1") + request.Header.Set("User-Agent", "Clash.Meta") response, err := client.Do(request) if err != nil { return nil, err @@ -368,6 +368,9 @@ func parseProxySubscription(value string) ([]subscriptionEntry, int, error) { return entries, decodedSkipped, nil } } + if entries, clashSkipped, matched := parseClashSubscription(value); matched && len(entries) > 0 { + return entries, clashSkipped, nil + } return nil, skipped, errors.New("订阅中没有可用的代理节点") } diff --git a/backend/internal/application/egress/subscription_clash.go b/backend/internal/application/egress/subscription_clash.go new file mode 100644 index 00000000..62d902f6 --- /dev/null +++ b/backend/internal/application/egress/subscription_clash.go @@ -0,0 +1,231 @@ +package egress + +import ( + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net" + "net/url" + "strconv" + "strings" + + "gopkg.in/yaml.v3" +) + +type clashSubscription struct { + Proxies []clashProxy `yaml:"proxies"` +} + +type clashProxy struct { + Type string `yaml:"type"` + Server string `yaml:"server"` + Port int `yaml:"port"` + Username string `yaml:"username"` + Password string `yaml:"password"` + Cipher string `yaml:"cipher"` + UUID string `yaml:"uuid"` + AlterID int `yaml:"alterId"` + Network string `yaml:"network"` + TLS bool `yaml:"tls"` + ServerName string `yaml:"servername"` + SNI string `yaml:"sni"` + Flow string `yaml:"flow"` + SkipCertVerify bool `yaml:"skip-cert-verify"` + ClientFingerprint string `yaml:"client-fingerprint"` + Plugin string `yaml:"plugin"` + WSOptions clashWebSocketOption `yaml:"ws-opts"` + RealityOptions clashRealityOptions `yaml:"reality-opts"` +} + +type clashWebSocketOption struct { + Path string `yaml:"path"` + Headers map[string]string `yaml:"headers"` +} + +type clashRealityOptions struct { + PublicKey string `yaml:"public-key"` + ShortID string `yaml:"short-id"` +} + +type clashVMessShare struct { + Version string `json:"v"` + Address string `json:"add"` + Port string `json:"port"` + UUID string `json:"id"` + AlterID string `json:"aid"` + Cipher string `json:"scy"` + 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 parseClashSubscription(value string) ([]subscriptionEntry, int, bool) { + var document clashSubscription + if err := yaml.Unmarshal([]byte(strings.TrimPrefix(value, "\ufeff")), &document); err != nil || document.Proxies == nil { + return nil, 0, false + } + if len(document.Proxies) > maxSubscriptionEntries { + return nil, len(document.Proxies), true + } + lines := make([]string, 0, len(document.Proxies)) + skipped := 0 + for _, proxy := range document.Proxies { + line, err := clashProxyURL(proxy) + if err != nil { + skipped++ + continue + } + lines = append(lines, line) + } + entries, lineSkipped := parseProxyLines(strings.Join(lines, "\n")) + return entries, skipped + lineSkipped, true +} + +func clashProxyURL(proxy clashProxy) (string, error) { + server, err := clashProxyServer(proxy.Server, proxy.Port) + if err != nil { + return "", err + } + proxyType := strings.ToLower(strings.TrimSpace(proxy.Type)) + switch proxyType { + case "http": + scheme := "http" + if proxy.TLS { + scheme = "https" + } + return clashStandardProxyURL(scheme, server, proxy.Username, proxy.Password), nil + case "socks5": + if proxy.TLS { + return "", errors.New("暂不支持 TLS SOCKS5") + } + return clashStandardProxyURL("socks5", server, proxy.Username, proxy.Password), nil + case "ss": + if strings.TrimSpace(proxy.Plugin) != "" { + return "", errors.New("暂不支持 Shadowsocks plugin") + } + method := strings.ToLower(strings.TrimSpace(proxy.Cipher)) + if method == "" || proxy.Password == "" { + return "", errors.New("Shadowsocks cipher/password 不能为空") + } + credential := base64.RawURLEncoding.EncodeToString([]byte(method + ":" + proxy.Password)) + return "ss://" + credential + "@" + server, nil + case "trojan": + if proxy.Password == "" { + return "", errors.New("Trojan password 不能为空") + } + query, err := clashTunnelQuery(proxy, "tls") + if err != nil { + return "", err + } + return (&url.URL{Scheme: "trojan", User: url.User(proxy.Password), Host: server, RawQuery: query.Encode()}).String(), nil + case "vless": + if proxy.UUID == "" { + return "", errors.New("VLESS UUID 不能为空") + } + security := "none" + if proxy.RealityOptions.PublicKey != "" || proxy.RealityOptions.ShortID != "" { + security = "reality" + } else if proxy.TLS { + security = "tls" + } + query, err := clashTunnelQuery(proxy, security) + if err != nil { + return "", err + } + query.Set("encryption", "none") + if flow := strings.TrimSpace(proxy.Flow); flow != "" { + query.Set("flow", flow) + } + if security == "reality" { + query.Set("pbk", proxy.RealityOptions.PublicKey) + query.Set("sid", proxy.RealityOptions.ShortID) + query.Set("fp", firstNonEmptySubscription(proxy.ClientFingerprint, "chrome")) + } + return (&url.URL{Scheme: "vless", User: url.User(proxy.UUID), Host: server, RawQuery: query.Encode()}).String(), nil + case "vmess": + return clashVMessURL(proxy) + default: + return "", fmt.Errorf("暂不支持 Clash 代理类型 %q", proxyType) + } +} + +func clashProxyServer(host string, port int) (string, error) { + host = strings.Trim(strings.TrimSpace(host), "[]") + if host == "" || port < 1 || port > 65535 { + return "", errors.New("Clash 代理服务器地址无效") + } + return net.JoinHostPort(host, strconv.Itoa(port)), nil +} + +func clashStandardProxyURL(scheme, server, username, password string) string { + value := &url.URL{Scheme: scheme, Host: server} + if username != "" || password != "" { + value.User = url.UserPassword(username, password) + } + return value.String() +} + +func clashTunnelQuery(proxy clashProxy, security string) (url.Values, error) { + transport := strings.ToLower(strings.TrimSpace(proxy.Network)) + if transport == "" { + transport = "tcp" + } + if transport == "websocket" { + transport = "ws" + } + query := make(url.Values) + query.Set("type", transport) + query.Set("security", security) + query.Set("sni", firstNonEmptySubscription(proxy.ServerName, proxy.SNI, proxy.Server)) + if proxy.SkipCertVerify { + query.Set("allowInsecure", "1") + } + if transport == "ws" { + query.Set("path", firstNonEmptySubscription(proxy.WSOptions.Path, "/")) + query.Set("host", firstNonEmptySubscription(proxy.WSOptions.Headers["Host"], proxy.WSOptions.Headers["host"], proxy.ServerName, proxy.SNI, proxy.Server)) + } + return query, nil +} + +func clashVMessURL(proxy clashProxy) (string, error) { + if proxy.UUID == "" { + return "", errors.New("VMess UUID 不能为空") + } + network := strings.ToLower(strings.TrimSpace(proxy.Network)) + if network == "" { + network = "tcp" + } + if network == "websocket" { + network = "ws" + } + share := clashVMessShare{ + Version: "2", Address: proxy.Server, Port: strconv.Itoa(proxy.Port), UUID: proxy.UUID, + AlterID: strconv.Itoa(proxy.AlterID), Cipher: firstNonEmptySubscription(proxy.Cipher, "auto"), Network: network, + ServerName: firstNonEmptySubscription(proxy.ServerName, proxy.SNI, proxy.Server), AllowInsecure: proxy.SkipCertVerify, + } + if proxy.TLS { + share.TLS = "tls" + } + if network == "ws" { + share.Path = firstNonEmptySubscription(proxy.WSOptions.Path, "/") + share.Host = firstNonEmptySubscription(proxy.WSOptions.Headers["Host"], proxy.WSOptions.Headers["host"], proxy.ServerName, proxy.SNI, proxy.Server) + } + encoded, err := json.Marshal(share) + if err != nil { + return "", err + } + return "vmess://" + base64.RawStdEncoding.EncodeToString(encoded), nil +} + +func firstNonEmptySubscription(values ...string) string { + for _, value := range values { + if value = strings.TrimSpace(value); value != "" { + return value + } + } + return "" +} diff --git a/backend/internal/application/egress/subscription_test.go b/backend/internal/application/egress/subscription_test.go index d7bb2cb4..5986f5d9 100644 --- a/backend/internal/application/egress/subscription_test.go +++ b/backend/internal/application/egress/subscription_test.go @@ -15,6 +15,7 @@ import ( 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" ) type subscriptionSyncRepositoryStub struct { @@ -100,6 +101,165 @@ func TestParseProxySubscriptionImportsSupportedTunnelSchemes(t *testing.T) { } } +func TestParseProxySubscriptionAcceptsClashYAML(t *testing.T) { + content := ` +proxies: + - name: http + type: http + server: http.example + port: 8080 + username: user + password: pass + - name: socks + type: socks5 + server: socks.example + port: 1080 + - name: trojan + type: trojan + server: trojan.example + port: 443 + password: secret + network: ws + sni: edge.example + ws-opts: + path: /ws + headers: + Host: edge.example + - name: reality + type: vless + server: reality.example + port: 443 + uuid: 123e4567-e89b-12d3-a456-426614174000 + network: tcp + tls: true + servername: edge.example + flow: xtls-rprx-vision + client-fingerprint: chrome + reality-opts: + public-key: SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8 + short-id: 0123456789abcdef + - name: shadowsocks + type: ss + server: ss.example + port: 8388 + cipher: aes-128-gcm + password: secret + - name: vmess + type: vmess + server: vmess.example + port: 443 + uuid: 123e4567-e89b-12d3-a456-426614174000 + alterId: 0 + cipher: auto + network: ws + tls: true + servername: edge.example + ws-opts: + path: /vmess + headers: + Host: edge.example + - name: ignored-hysteria + type: hysteria2 + server: hy.example + port: 443 + password: secret + - name: ignored-tuic + type: tuic + server: tuic.example + port: 443 + password: secret +proxy-groups: + - name: auto + type: select + proxies: [http, socks] +` + entries, skipped, err := parseProxySubscription(content) + if err != nil { + t.Fatal(err) + } + if len(entries) != 6 || skipped != 2 { + t.Fatalf("Clash entries=%d skipped=%d values=%#v", len(entries), skipped, entries) + } + var realityConfig tunnelproxy.Config + for _, entry := range entries { + if strings.HasPrefix(entry.ProxyURL, "vless://") { + realityConfig, err = tunnelproxy.Parse(entry.ProxyURL) + if err != nil { + t.Fatal(err) + } + } + } + if realityConfig.Security != "reality" || realityConfig.Flow != "xtls-rprx-vision" || realityConfig.RealityPublicKey == "" || realityConfig.RealityShortID != "0123456789abcdef" { + t.Fatalf("Clash Reality config = %#v", realityConfig) + } +} + +func TestFetchProxySubscriptionUsesClashUserAgent(t *testing.T) { + var userAgent string + proxy := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + userAgent = request.Header.Get("User-Agent") + _, _ = writer.Write([]byte("http://proxy.example:8080\n")) + })) + defer proxy.Close() + + body, err := fetchProxySubscription(context.Background(), "http://1.1.1.1/subscription", proxy.URL) + if err != nil { + t.Fatal(err) + } + if userAgent != "Clash.Meta" || !strings.Contains(string(body), "proxy.example") { + t.Fatalf("User-Agent=%q body=%q", userAgent, body) + } +} + +func TestClashRealityPreservesSupportedClientFingerprints(t *testing.T) { + content := ` +proxies: + - type: vless + server: chrome.example + port: 443 + uuid: 123e4567-e89b-12d3-a456-426614174000 + flow: xtls-rprx-vision + client-fingerprint: chrome + reality-opts: &reality + public-key: SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8 + short-id: 0123456789abcdef + - type: vless + server: edge.example + port: 443 + uuid: 123e4567-e89b-12d3-a456-426614174000 + flow: xtls-rprx-vision + client-fingerprint: edge + reality-opts: *reality + - type: vless + server: safari.example + port: 443 + uuid: 123e4567-e89b-12d3-a456-426614174000 + flow: xtls-rprx-vision + client-fingerprint: safari + reality-opts: *reality +` + entries, skipped, err := parseProxySubscription(content) + if err != nil { + t.Fatal(err) + } + if len(entries) != 3 || skipped != 0 { + t.Fatalf("entries=%d skipped=%d", len(entries), skipped) + } + fingerprints := make(map[string]bool) + for _, entry := range entries { + config, parseErr := tunnelproxy.Parse(entry.ProxyURL) + if parseErr != nil { + t.Fatal(parseErr) + } + fingerprints[config.ClientFingerprint] = true + } + for _, fingerprint := range []string{"chrome", "edge", "safari"} { + if !fingerprints[fingerprint] { + t.Fatalf("missing client fingerprint %q", fingerprint) + } + } +} + 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", From ecf070ba42cd0c969bca74443d2da30d11472c08 Mon Sep 17 00:00:00 2001 From: heshangcode <39662806+heshangcode@users.noreply.github.com> Date: Fri, 14 Aug 2026 16:28:35 +0800 Subject: [PATCH 39/48] fix: keep web-to-build SSO device flow off Cloudflare-strict accounts.x.ai accounts.x.ai rejects non-browser clients (including the managed tls-client) with HTTP 403 even when a valid cf_clearance is presented, while auth.x.ai accepts them. Move the device flow onto auth.x.ai: - Solve an ad-hoc clearance for accounts.x.ai through the same egress exit (new Manager.SolveClearance, never persisted into the node cache) and attach it to the flow, falling back gracefully when solving fails. - Degrade the SSO precheck and the verification-page warmup to warnings when Cloudflare blocks them; credential validity is now judged by the verify step, which still maps dead SSO cookies to ErrUnauthorized (preserving the credential-rejected marker) via the sign-in redirect. - Stop following redirects on verify/approve POSTs and read the 302 Location directly for the consent/done markers, so the flow never visits accounts.x.ai. Verified with go test ./... and a live conversion (created 1, failed 0). Co-Authored-By: Claude --- backend/internal/infra/egress/manager.go | 25 ++++ .../internal/infra/provider/web/sso_build.go | 81 ++++++++++- .../infra/provider/web/sso_build_test.go | 129 ++++++++++++++++++ 3 files changed, 229 insertions(+), 6 deletions(-) diff --git a/backend/internal/infra/egress/manager.go b/backend/internal/infra/egress/manager.go index e3c99930..36f6504b 100644 --- a/backend/internal/infra/egress/manager.go +++ b/backend/internal/infra/egress/manager.go @@ -435,6 +435,31 @@ func (m *Manager) UpdateClearanceConfig(value ClearanceConfig) { m.clearanceMu.Unlock() } +// SolveClearance 通过已配置的 FlareSolverr 为指定目标 URL 现解 Cloudflare Clearance。 +// 结果不写节点缓存也不持久化,避免与节点既有 Clearance(如 grok.com)互相覆盖; +// 调用方必须通过同一 proxyURL 出口发送后续请求,保证 Clearance 与出口 IP 一致。 +func (m *Manager) SolveClearance(ctx context.Context, proxyURL, targetURL string) (string, string, error) { + m.clearanceMu.Lock() + cfg := m.clearanceConfig + solver := m.solver + m.clearanceMu.Unlock() + if cfg.Mode != "flaresolverr" && cfg.Mode != "on_demand" { + return "", "", errors.New("FlareSolverr Clearance 未启用") + } + cfg.TargetURL = strings.TrimRight(strings.TrimSpace(targetURL), "/") + if cfg.TargetURL == "" { + cfg.TargetURL = "https://grok.com" + } + if cfg.Timeout <= 0 { + cfg.Timeout = time.Minute + } + solution, err := solver.Solve(ctx, cfg, proxyURL) + if err != nil { + return "", "", err + } + return solution.Cookies, solution.UserAgent, nil +} + func (m *Manager) Acquire(ctx context.Context, scope domain.Scope, affinity string) (*Lease, error) { lease, _, err := m.acquire(ctx, scope, affinity, true, "", egressNodeFromContext(ctx)) return lease, err diff --git a/backend/internal/infra/provider/web/sso_build.go b/backend/internal/infra/provider/web/sso_build.go index b46ffc68..84e91bb4 100644 --- a/backend/internal/infra/provider/web/sso_build.go +++ b/backend/internal/infra/provider/web/sso_build.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "io" + "log/slog" "net/http" "net/url" "sort" @@ -36,10 +37,16 @@ type ssoBuildHTTPClient interface { Do(*http.Request) (*http.Response, error) } +// ssoClearanceResolver 为 SSO 转换目标(accounts.x.ai)现解 Cloudflare Clearance。 +// 求解失败时返回 error,调用方降级为无 Clearance 的现有行为。 +type ssoClearanceResolver func(ctx context.Context) (cookies, userAgent string, err error) + type ssoBuildFlow struct { client ssoBuildHTTPClient userAgent string cookies map[string]string + clearance ssoClearanceResolver // 可选 + logger *slog.Logger // 可选,用于降级告警 } func (a *Adapter) ConvertToBuild(ctx context.Context, credential accountdomain.Credential) (provider.CredentialSeed, error) { @@ -62,8 +69,17 @@ func (a *Adapter) ConvertToBuild(ctx context.Context, credential accountdomain.C requestCtx, cancel := context.WithTimeout(ctx, 90*time.Second) defer cancel() flow := &ssoBuildFlow{ - client: lease, userAgent: lease.UserAgent, + client: lease, userAgent: lease.UserAgent, logger: a.logger, cookies: map[string]string{"sso": token, "sso-rw": token}, + // 节点缓存的 Clearance 是 grok.com 域,对 accounts.x.ai 无效; + // 转换流程通过同一出口现解目标域的 Clearance。 + clearance: func(solveCtx context.Context) (string, string, error) { + cookies, userAgent, err := a.egress.SolveClearance(solveCtx, lease.ProxyURL, ssoAccountsURL) + if err != nil { + a.logger.Warn("web_sso_build_clearance_failed", "account_id", credential.ID, "error", err) + } + return cookies, userAgent, err + }, } seed, err := flow.convert(requestCtx, credential) if err != nil { @@ -75,6 +91,14 @@ func (a *Adapter) ConvertToBuild(ctx context.Context, credential accountdomain.C } func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Credential) (provider.CredentialSeed, error) { + if f.clearance != nil { + if cookies, userAgent, err := f.clearance(ctx); err == nil { + mergeCookieHeader(f.cookies, cookies) + if ua := strings.TrimSpace(userAgent); ua != "" { + f.userAgent = ua + } + } + } status, finalURL, _, err := f.do(ctx, http.MethodGet, ssoAccountsURL, nil) if err != nil { return provider.CredentialSeed{}, err @@ -83,7 +107,10 @@ func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Cre return provider.CredentialSeed{}, provider.ErrUnauthorized } if status < 200 || status >= 400 { - return provider.CredentialSeed{}, fmt.Errorf("校验 Grok Web SSO 失败: %w", conversionHTTPError{status: status}) + // accounts.x.ai 对非浏览器客户端启用严格 Cloudflare 拦截(HTTP 403), + // 该预检仅用于提前识别失效 SSO,并非 Device Flow 必需步骤; + // 被拦截时降级跳过,凭据有效性交给 verify 步判断。 + f.warn("web_sso_build_precheck_blocked", "status", status) } form := url.Values{"client_id": {ssoBuildClientID}, "scope": {ssoBuildScope}} @@ -119,21 +146,31 @@ func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Cre return provider.CredentialSeed{}, err } if status < 200 || status >= 400 { - return provider.CredentialSeed{}, fmt.Errorf("打开 Device Flow 验证页失败: %w", conversionHTTPError{status: status}) + // 打开验证页只是模拟浏览器预热,xAI 不要求必须先访问该页; + // 与预检一致,被 Cloudflare 拦截时降级跳过。 + f.warn("web_sso_build_verify_page_blocked", "status", status) } - status, finalURL, _, err = f.do(ctx, http.MethodPost, ssoVerifyURL, url.Values{"user_code": {device.UserCode}}) + // verify/approve 的重定向目标是 accounts.x.ai,该域对非浏览器客户端严格拦截; + // 不跟随重定向,直接读 Location 判定结果,整个流程保持在 auth.x.ai 上完成。 + status, finalURL, _, err = f.doWithFollow(ctx, http.MethodPost, ssoVerifyURL, url.Values{"user_code": {device.UserCode}}, false) if err != nil { return provider.CredentialSeed{}, err } + if status == http.StatusUnauthorized { + return provider.CredentialSeed{}, provider.ErrUnauthorized + } if status < 200 || status >= 400 { return provider.CredentialSeed{}, fmt.Errorf("SSO 自动验证 Device Flow 失败: %w", conversionHTTPError{status: status}) } if !strings.Contains(finalURL, "consent") { + if strings.Contains(finalURL, "sign-in") || strings.Contains(finalURL, "sign-up") { + return provider.CredentialSeed{}, provider.ErrUnauthorized + } return provider.CredentialSeed{}, fmt.Errorf("SSO 自动验证 Device Flow 失败") } - status, finalURL, _, err = f.do(ctx, http.MethodPost, ssoApproveURL, url.Values{ + status, finalURL, _, err = f.doWithFollow(ctx, http.MethodPost, ssoApproveURL, url.Values{ "user_code": {device.UserCode}, "action": {"allow"}, "principal_type": {"User"}, "principal_id": {""}, - }) + }, false) if err != nil { return provider.CredentialSeed{}, err } @@ -226,6 +263,12 @@ func (f *ssoBuildFlow) pollToken(ctx context.Context, deviceCode string, interva } func (f *ssoBuildFlow) do(ctx context.Context, method, endpoint string, form url.Values) (int, string, []byte, error) { + return f.doWithFollow(ctx, method, endpoint, form, true) +} + +// doWithFollow 在 follow=false 时遇到 3xx 直接返回状态码与解析后的 Location 作为 finalURL, +// 用于重定向目标域会被 Cloudflare 拦截(accounts.x.ai)的请求。 +func (f *ssoBuildFlow) doWithFollow(ctx context.Context, method, endpoint string, form url.Values, follow bool) (int, string, []byte, error) { if !safeXAIURL(endpoint) { return 0, "", nil, fmt.Errorf("xAI OAuth URL 不安全") } @@ -277,6 +320,9 @@ func (f *ssoBuildFlow) do(ctx context.Context, method, endpoint string, form url if !safeXAIURL(currentURL) { return response.StatusCode, currentURL, data, fmt.Errorf("xAI OAuth 重定向到非受信域名") } + if !follow { + return response.StatusCode, currentURL, nil, nil + } if response.StatusCode == http.StatusSeeOther || ((response.StatusCode == http.StatusMovedPermanently || response.StatusCode == http.StatusFound) && currentMethod != http.MethodGet && currentMethod != http.MethodHead) { currentMethod = http.MethodGet currentForm = nil @@ -285,6 +331,29 @@ func (f *ssoBuildFlow) do(ctx context.Context, method, endpoint string, form url return 0, currentURL, nil, fmt.Errorf("xAI OAuth 重定向次数过多") } +// warn 记录降级告警;logger 未注入时静默。 +func (f *ssoBuildFlow) warn(message string, args ...any) { + if f.logger != nil { + f.logger.Warn(message, args...) + } +} + +// mergeCookieHeader 将 Clearance 求解返回的 Cookie 串合并进 cookie 集合, +// 校验规则与 captureCookies 一致,避免注入非法 Cookie 头。 +func mergeCookieHeader(cookies map[string]string, header string) { + for _, part := range strings.Split(header, ";") { + name, value, found := strings.Cut(part, "=") + if !found { + continue + } + name, value = strings.TrimSpace(name), strings.TrimSpace(value) + if name == "" || len(name) > 128 || len(value) > 16384 || strings.ContainsAny(name+value, "\r\n\x00") { + continue + } + cookies[name] = value + } +} + func (f *ssoBuildFlow) captureCookies(response *http.Response) { for _, cookie := range response.Cookies() { name := strings.TrimSpace(cookie.Name) diff --git a/backend/internal/infra/provider/web/sso_build_test.go b/backend/internal/infra/provider/web/sso_build_test.go index 0e4e54f4..8f51f622 100644 --- a/backend/internal/infra/provider/web/sso_build_test.go +++ b/backend/internal/infra/provider/web/sso_build_test.go @@ -2,10 +2,15 @@ package web import ( "context" + "errors" "io" "net/http" + "net/url" "strings" "testing" + + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/infra/provider" ) type scriptedSSOClient struct { @@ -48,6 +53,130 @@ func TestSSOBuildFlowFollowsOnlyTrustedXAIHTTPSRedirects(t *testing.T) { } } +func TestMergeCookieHeader(t *testing.T) { + cookies := map[string]string{"sso": "secret"} + mergeCookieHeader(cookies, "cf_clearance=abc.123; __cuid=id=with-equals; bad\x00name=x; =novalue; long="+strings.Repeat("a", 16385)+"; sso=hijack") + if cookies["cf_clearance"] != "abc.123" { + t.Fatalf("cf_clearance = %q", cookies["cf_clearance"]) + } + if cookies["__cuid"] != "id=with-equals" { + t.Fatalf("__cuid = %q", cookies["__cuid"]) + } + if _, ok := cookies["bad\x00name"]; ok { + t.Fatal("cookie with NUL in name was accepted") + } + if _, ok := cookies[""]; ok { + t.Fatal("cookie with empty name was accepted") + } + if _, ok := cookies["long"]; ok { + t.Fatal("oversized cookie value was accepted") + } + if cookies["sso"] != "hijack" { + t.Fatalf("existing cookie should be overridden, got %q", cookies["sso"]) + } +} + +// blockedPrecheckScript 模拟 accounts.x.ai 预检被 Cloudflare 403 拦截, +// 随后 Device Flow 启动返回 500 使流程在第 2 步终止。 +func blockedPrecheckScript() *scriptedSSOClient { + return &scriptedSSOClient{responses: []*http.Response{ + {StatusCode: http.StatusForbidden, Header: http.Header{}, Body: io.NopCloser(strings.NewReader("challenge"))}, + {StatusCode: http.StatusInternalServerError, Header: http.Header{}, Body: io.NopCloser(strings.NewReader("boom"))}, + }} +} + +func TestSSOBuildFlowAttachesClearanceToFirstRequest(t *testing.T) { + client := blockedPrecheckScript() + flow := &ssoBuildFlow{ + client: client, userAgent: "lease-agent", + cookies: map[string]string{"sso": "secret"}, + clearance: func(context.Context) (string, string, error) { + return "cf_clearance=abc.123; __cf_bm=xyz", "solver-agent", nil + }, + } + _, err := flow.convert(context.Background(), fakeCredential()) + if err == nil { + t.Fatal("expected conversion to fail after scripted 500") + } + if len(client.requests) == 0 { + t.Fatal("no request was issued") + } + first := client.requests[0] + if ua := first.Header.Get("User-Agent"); ua != "solver-agent" { + t.Fatalf("User-Agent = %q, want solver-agent", ua) + } + cookie := first.Header.Get("Cookie") + if !strings.Contains(cookie, "sso=secret") || !strings.Contains(cookie, "cf_clearance=abc.123") || !strings.Contains(cookie, "__cf_bm=xyz") { + t.Fatalf("Cookie = %q", cookie) + } + if len(client.requests) != 2 { + t.Fatalf("blocked precheck must be degraded, requests = %d", len(client.requests)) + } +} + +func TestSSOBuildFlowClearanceFailureFallsBack(t *testing.T) { + client := blockedPrecheckScript() + flow := &ssoBuildFlow{ + client: client, userAgent: "lease-agent", + cookies: map[string]string{"sso": "secret"}, + clearance: func(context.Context) (string, string, error) { + return "", "", io.ErrUnexpectedEOF + }, + } + _, _ = flow.convert(context.Background(), fakeCredential()) + if len(client.requests) == 0 { + t.Fatal("no request was issued") + } + first := client.requests[0] + if ua := first.Header.Get("User-Agent"); ua != "lease-agent" { + t.Fatalf("User-Agent = %q, want lease-agent", ua) + } + cookie := first.Header.Get("Cookie") + if strings.Contains(cookie, "cf_clearance") || !strings.Contains(cookie, "sso=secret") { + t.Fatalf("Cookie = %q", cookie) + } +} + +func TestSSOBuildFlowMapsDeadSSOToUnauthorized(t *testing.T) { + client := &scriptedSSOClient{responses: []*http.Response{ + {StatusCode: http.StatusForbidden, Header: http.Header{}, Body: io.NopCloser(strings.NewReader("challenge"))}, + {StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader( + `{"device_code":"dc","user_code":"uc","verification_uri_complete":"https://accounts.x.ai/oauth2/device?code=abc","interval":1,"expires_in":1800}`))}, + {StatusCode: http.StatusForbidden, Header: http.Header{}, Body: io.NopCloser(strings.NewReader("challenge"))}, + {StatusCode: http.StatusFound, Header: http.Header{"Location": []string{"https://accounts.x.ai/sign-in"}}, Body: io.NopCloser(strings.NewReader(""))}, + }} + flow := &ssoBuildFlow{client: client, userAgent: "lease-agent", cookies: map[string]string{"sso": "dead"}} + _, err := flow.convert(context.Background(), fakeCredential()) + if !errors.Is(err, provider.ErrUnauthorized) { + t.Fatalf("err = %v, want ErrUnauthorized", err) + } + if len(client.requests) != 4 { + t.Fatalf("requests = %d, want 4 (precheck, device, verify page, verify 不跟随重定向)", len(client.requests)) + } +} + +func TestSSOBuildFlowVerifyDoesNotFollowRedirect(t *testing.T) { + client := &scriptedSSOClient{responses: []*http.Response{ + {StatusCode: http.StatusFound, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device?code=abc&consent=1"}}, Body: io.NopCloser(strings.NewReader(""))}, + }} + flow := &ssoBuildFlow{client: client, userAgent: "lease-agent", cookies: map[string]string{"sso": "live"}} + status, finalURL, _, err := flow.doWithFollow(context.Background(), http.MethodPost, ssoVerifyURL, url.Values{"user_code": {"uc"}}, false) + if err != nil { + t.Fatal(err) + } + if status != http.StatusFound { + t.Fatalf("status = %d, want 302", status) + } + if finalURL != "https://accounts.x.ai/oauth2/device?code=abc&consent=1" { + t.Fatalf("finalURL = %q", finalURL) + } + if len(client.requests) != 1 { + t.Fatalf("redirect must not be followed, requests = %d", len(client.requests)) + } +} + +func fakeCredential() accountdomain.Credential { return accountdomain.Credential{} } + func TestSSOBuildConversionSanitizesTokenAndURLs(t *testing.T) { if token := normalizeSSOToken("sso=token-value; x-userid=drop"); token != "token-value" { t.Fatalf("token = %q", token) From 71517cc609ac24daeae4e8a9ce00b7afdc5753bb Mon Sep 17 00:00:00 2001 From: lij768423-svg Date: Fri, 14 Aug 2026 19:59:28 +0800 Subject: [PATCH 40/48] feat: add probe profiles, dual-probe recovery, and thinking guard Add a configurable quality-guard probe catalog (last-line / contains / regex markers). User-traffic degrade isolates immediately; restore only after a QUALITY_OK probe is healthy and includes thinking tokens. Missing thinking is a hard isolate even at normal TPS. --- .../application/egress/probe_match.go | 62 +++ .../application/egress/probe_match_test.go | 28 ++ .../internal/application/egress/service.go | 5 +- .../application/gateway/quality_probe.go | 2 +- .../internal/transport/http/egress/handler.go | 25 +- .../transport/http/egress/handler_test.go | 31 ++ .../transport/http/egress/profiles.go | 414 ++++++++++++++++++ .../quality-guard/probe-profiles-panel.tsx | 186 ++++++++ .../quality-guard/quality-guard-api.ts | 60 ++- .../quality-guard/quality-guard-page.tsx | 5 + frontend/src/shared/i18n/index.ts | 46 +- tools/egress-quality-guard/quality_guard.py | 182 ++++++-- .../quality_guard_test.py | 227 ++++++++-- 13 files changed, 1189 insertions(+), 84 deletions(-) create mode 100644 backend/internal/application/egress/probe_match.go create mode 100644 backend/internal/application/egress/probe_match_test.go create mode 100644 backend/internal/transport/http/egress/profiles.go create mode 100644 frontend/src/features/quality-guard/probe-profiles-panel.tsx diff --git a/backend/internal/application/egress/probe_match.go b/backend/internal/application/egress/probe_match.go new file mode 100644 index 00000000..89ac2874 --- /dev/null +++ b/backend/internal/application/egress/probe_match.go @@ -0,0 +1,62 @@ +package egress + +import ( + "regexp" + "strings" + "unicode" +) + +const ( + MatchContains = "contains" + MatchLastLine = "last_line" + MatchRegex = "regex" +) + +func NormalizeMatchMode(mode string) string { + switch strings.ToLower(strings.TrimSpace(mode)) { + case MatchLastLine, "last-line", "lastline": + return MatchLastLine + case MatchRegex, "regexp": + return MatchRegex + default: + return MatchContains + } +} + +func lastNonEmptyLine(text string) string { + lines := strings.Split(text, "\n") + for i := len(lines) - 1; i >= 0; i-- { + line := strings.TrimSpace(lines[i]) + if line != "" { + return line + } + } + return "" +} + +// MatchExpected reports whether the probe body satisfies the expected marker. +// An empty expected string always matches so throughput-only profiles can skip +// content checks. +func MatchExpected(text, expected, mode string) bool { + expected = strings.TrimSpace(expected) + if expected == "" { + return true + } + text = strings.TrimRightFunc(text, unicode.IsSpace) + switch NormalizeMatchMode(mode) { + case MatchLastLine: + line := lastNonEmptyLine(text) + if line == "" { + return false + } + return strings.EqualFold(line, expected) || strings.Contains(line, expected) + case MatchRegex: + re, err := regexp.Compile(expected) + if err != nil { + return false + } + return re.MatchString(text) + default: + return strings.Contains(text, expected) + } +} diff --git a/backend/internal/application/egress/probe_match_test.go b/backend/internal/application/egress/probe_match_test.go new file mode 100644 index 00000000..d19e30c3 --- /dev/null +++ b/backend/internal/application/egress/probe_match_test.go @@ -0,0 +1,28 @@ +package egress + +import "testing" + +func TestMatchExpectedModes(t *testing.T) { + text := "天空是蓝的,因为瑞利散射。\nQUALITY_OK\n" + if !MatchExpected(text, "QUALITY_OK", MatchLastLine) { + t.Fatal("last line QUALITY_OK should match") + } + if MatchExpected("hello\nNOT_OK", "QUALITY_OK", MatchLastLine) { + t.Fatal("wrong last line must not match") + } + if !MatchExpected("prefix QUALITY_OK suffix", "QUALITY_OK", MatchContains) { + t.Fatal("contains should match") + } + if !MatchExpected("done\nstatus=QUALITY_OK", "QUALITY_OK", MatchLastLine) { + t.Fatal("last line containing the marker should match") + } + if !MatchExpected("alpha\nbeta QUALITY_OK", `QUALITY_OK$`, MatchRegex) { + t.Fatal("regex should match") + } + if MatchExpected("nope", "[", MatchRegex) { + t.Fatal("invalid regex must not match") + } + if !MatchExpected("anything", "", MatchContains) { + t.Fatal("empty expected is always a match") + } +} diff --git a/backend/internal/application/egress/service.go b/backend/internal/application/egress/service.go index 7bdefb59..4a45045f 100644 --- a/backend/internal/application/egress/service.go +++ b/backend/internal/application/egress/service.go @@ -41,6 +41,7 @@ type QualityProbeInput struct { Model string Prompt string Expected string + MatchMode string MaxOutputTokens int } @@ -128,13 +129,15 @@ func (s *Service) ProbeQuality(ctx context.Context, nodeID uint64, input Quality input.Model = strings.TrimSpace(input.Model) input.Prompt = strings.TrimSpace(input.Prompt) input.Expected = strings.TrimSpace(input.Expected) + rawMatchMode := strings.TrimSpace(input.MatchMode) + input.MatchMode = NormalizeMatchMode(input.MatchMode) if input.Model == "" { return QualityProbeResult{}, fmt.Errorf("%w: model 必填", ErrInvalidInput) } if input.Prompt == "" { input.Prompt = DefaultQualityProbePrompt } - if input.Expected == "" { + if input.Expected == "" && rawMatchMode == "" { input.Expected = DefaultQualityProbeExpected } if len(input.Prompt) > MaxQualityProbePromptBytes || len(input.Expected) > MaxQualityProbeExpectedBytes { diff --git a/backend/internal/application/gateway/quality_probe.go b/backend/internal/application/gateway/quality_probe.go index 689685a7..7fb3ef93 100644 --- a/backend/internal/application/gateway/quality_probe.go +++ b/backend/internal/application/gateway/quality_probe.go @@ -184,7 +184,7 @@ func (s *Service) ProbeEgressQuality(ctx context.Context, nodeID uint64, input e FirstTokenMS: firstTokenMS, DurationMS: durationMS, GenerationMS: generationMS, ChunkCount: chunkCount, OutputTokens: usage.OutputTokens, ReasoningTokens: usage.ReasoningTokens, VisibleTokens: visibleTokens, VisibleCharacters: visibleCharacters, OutputTokensPerSecond: outputTokensPerSecond, - ExpectedMatched: strings.Contains(text, input.Expected), ResponseSHA256: hex.EncodeToString(digest[:]), + ExpectedMatched: egressapp.MatchExpected(text, input.Expected, input.MatchMode), ResponseSHA256: hex.EncodeToString(digest[:]), }, nil } diff --git a/backend/internal/transport/http/egress/handler.go b/backend/internal/transport/http/egress/handler.go index 52f73f07..45c62fd6 100644 --- a/backend/internal/transport/http/egress/handler.go +++ b/backend/internal/transport/http/egress/handler.go @@ -59,6 +59,10 @@ func (h *Handler) Register(router *gin.RouterGroup) { router.POST("/egress-nodes/:id/quality-test", h.testQuality) router.GET("/egress-quality-guard", h.qualityGuardStatus) router.PUT("/egress-quality-guard/config", h.updateQualityGuardConfig) + router.GET("/egress-quality-guard/profiles", h.listQualityGuardProfiles) + router.POST("/egress-quality-guard/profiles", h.createQualityGuardProfile) + router.PUT("/egress-quality-guard/profiles/:id", h.updateQualityGuardProfile) + router.DELETE("/egress-quality-guard/profiles/:id", h.deleteQualityGuardProfile) router.POST("/egress-quality-guard/nodes/:id/test", h.testQualityGuardNode) router.POST("/egress-nodes/:id/accounts", h.assignAccounts) router.DELETE("/egress-nodes/accounts", h.unassignAccounts) @@ -203,6 +207,10 @@ func (h *Handler) qualityGuardStatus(c *gin.Context) { if state.Statistics.StartedAt > 0 { payload["statistics"] = state.Statistics } + if profiles, err := loadProbeProfileFile(h.profilesPath()); err == nil { + payload["activeProfileId"] = profiles.ActiveProfileID + payload["profiles"] = profiles.summaries() + } response.Success(c, http.StatusOK, payload) } @@ -361,11 +369,24 @@ func (h *Handler) testQualityGuardNode(c *gin.Context) { if !ok { return } - if h.guardProbe.ClientKeyID == 0 || strings.TrimSpace(h.guardProbe.Model) == "" || h.guardProbe.Prompt == "" || h.guardProbe.Expected == "" { + if h.guardProbe.ClientKeyID == 0 || strings.TrimSpace(h.guardProbe.Model) == "" { response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "质量守护配置暂不可用") return } - value, err := h.service.ProbeQuality(c.Request.Context(), nodeID, h.guardProbe) + var request struct { + ProfileID string `json:"profileId"` + } + _ = c.ShouldBindJSON(&request) + input, err := h.resolveProbeInput(strings.TrimSpace(request.ProfileID)) + if err != nil { + response.Error(c, http.StatusBadRequest, "invalidRequest", err.Error()) + return + } + if strings.TrimSpace(input.Prompt) == "" { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "质量守护配置暂不可用") + return + } + value, err := h.service.ProbeQuality(c.Request.Context(), nodeID, input) if err != nil { h.writeQualityProbeError(c, err) return diff --git a/backend/internal/transport/http/egress/handler_test.go b/backend/internal/transport/http/egress/handler_test.go index 2b664174..d3d62c5d 100644 --- a/backend/internal/transport/http/egress/handler_test.go +++ b/backend/internal/transport/http/egress/handler_test.go @@ -94,6 +94,37 @@ func TestWriteQualityProbeErrorIdentifiesMissingProbeAccount(t *testing.T) { } } +func TestQualityGuardProfilesCRUDAndStatusOmitsPrompt(t *testing.T) { + directory := t.TempDir() + statePath := directory + "/state.json" + configPath := directory + "/runtime-config.json" + if err := os.WriteFile(statePath, []byte(`{"version":1,"guard":{"mode":"hybrid","model":"grok-4.5","node_ids":["8"]},"nodes":{}}`), 0o600); err != nil { + t.Fatal(err) + } + handler := NewHandler(nil, statePath, configPath) + + createRecorder := httptest.NewRecorder() + createContext, _ := gin.CreateTestContext(createRecorder) + createContext.Request = httptest.NewRequest("POST", "/egress-quality-guard/profiles", bytes.NewBufferString(`{"name":"自定义标记","prompt":"只输出 FLAG_OK","expectedText":"FLAG_OK","matchMode":"last_line","active":true}`)) + createContext.Request.Header.Set("Content-Type", "application/json") + handler.createQualityGuardProfile(createContext) + if createRecorder.Code != 200 || !strings.Contains(createRecorder.Body.String(), `"FLAG_OK"`) { + t.Fatalf("create status=%d body=%s", createRecorder.Code, createRecorder.Body.String()) + } + + statusRecorder := httptest.NewRecorder() + statusContext, _ := gin.CreateTestContext(statusRecorder) + statusContext.Request = httptest.NewRequest("GET", "/egress-quality-guard", nil) + handler.qualityGuardStatus(statusContext) + body := statusRecorder.Body.String() + if statusRecorder.Code != 200 || !strings.Contains(body, `"activeProfileId":"p-2"`) || !strings.Contains(body, `"has_expected":true`) { + t.Fatalf("status=%d body=%s", statusRecorder.Code, body) + } + if strings.Contains(body, "只输出 FLAG_OK") || strings.Contains(body, "FLAG_OK") { + t.Fatalf("status leaked probe prompt or marker: %s", body) + } +} + func TestUpdateQualityGuardConfigWritesPrivateAtomicFile(t *testing.T) { directory := t.TempDir() statePath := directory + "/state.json" diff --git a/backend/internal/transport/http/egress/profiles.go b/backend/internal/transport/http/egress/profiles.go new file mode 100644 index 00000000..0f59599c --- /dev/null +++ b/backend/internal/transport/http/egress/profiles.go @@ -0,0 +1,414 @@ +package egress + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "time" + + egressapp "github.com/chenyme/grok2api/backend/internal/application/egress" + "github.com/chenyme/grok2api/backend/internal/shared/response" + "github.com/gin-gonic/gin" +) + +const ( + profileThroughput = "throughput" + profileQualityMarker = "quality-marker" + maxCustomProfiles = 32 +) + +type probeProfile struct { + ID string `json:"id"` + Name string `json:"name"` + BuiltIn bool `json:"built_in"` + Prompt string `json:"prompt"` + ExpectedText string `json:"expected_text,omitempty"` + MatchMode string `json:"match_mode"` + MaxOutputTokens int `json:"max_output_tokens,omitempty"` + UpdatedAt float64 `json:"updated_at,omitempty"` +} + +type probeProfileFile struct { + Version int `json:"version"` + ActiveProfileID string `json:"active_profile_id"` + NextID int `json:"next_id"` + Profiles map[string]probeProfile `json:"profiles"` +} + +func builtinProbeProfiles() []probeProfile { + return []probeProfile{ + { + ID: profileQualityMarker, + Name: "预期标记", + BuiltIn: true, + Prompt: "先用三点总结为什么天空呈蓝色,最后一行只输出 QUALITY_OK。", + ExpectedText: "QUALITY_OK", + MatchMode: egressapp.MatchLastLine, + }, + { + ID: profileThroughput, + Name: "吞吐基线", + BuiltIn: true, + Prompt: "Write a detailed technical explanation of how TCP slow start works, at least 12 sentences, plain text only.", + MatchMode: egressapp.MatchContains, + }, + } +} + +func (h *Handler) profilesPath() string { + if h.guardConfigPath == "" { + return "" + } + return filepath.Join(filepath.Dir(h.guardConfigPath), "profiles.json") +} + +func seedProbeProfileFile(data *probeProfileFile) { + if data.Profiles == nil { + data.Profiles = map[string]probeProfile{} + } + if data.Version == 0 { + data.Version = 1 + } + now := float64(time.Now().Unix()) + for _, builtin := range builtinProbeProfiles() { + existing, ok := data.Profiles[builtin.ID] + if !ok { + builtin.UpdatedAt = now + data.Profiles[builtin.ID] = builtin + continue + } + if existing.BuiltIn { + existing.Name = builtin.Name + existing.Prompt = builtin.Prompt + existing.ExpectedText = builtin.ExpectedText + existing.MatchMode = builtin.MatchMode + data.Profiles[builtin.ID] = existing + } + } + if data.ActiveProfileID == "" { + data.ActiveProfileID = profileQualityMarker + } + if _, ok := data.Profiles[data.ActiveProfileID]; !ok { + data.ActiveProfileID = profileQualityMarker + } + if data.NextID < 1 { + data.NextID = 1 + } +} + +func loadProbeProfileFile(path string) (probeProfileFile, error) { + data := probeProfileFile{Version: 1, Profiles: map[string]probeProfile{}} + if path == "" { + seedProbeProfileFile(&data) + return data, nil + } + raw, err := os.ReadFile(path) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + seedProbeProfileFile(&data) + return data, nil + } + return probeProfileFile{}, err + } + if err := json.Unmarshal(raw, &data); err != nil { + return probeProfileFile{}, err + } + seedProbeProfileFile(&data) + return data, nil +} + +func saveProbeProfileFile(path string, data probeProfileFile) error { + if path == "" { + return errors.New("profiles path is empty") + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + raw, err := json.Marshal(data) + if err != nil { + return err + } + temporary, err := os.CreateTemp(filepath.Dir(path), ".profiles-") + if err != nil { + return err + } + temporaryPath := temporary.Name() + defer os.Remove(temporaryPath) + if err := temporary.Chmod(0o600); err != nil { + _ = temporary.Close() + return err + } + if _, err := temporary.Write(raw); err != nil { + _ = temporary.Close() + return err + } + if err := temporary.Close(); err != nil { + return err + } + return os.Rename(temporaryPath, path) +} + +func (data probeProfileFile) resolve(id string) (probeProfile, bool) { + if id == "" { + id = data.ActiveProfileID + } + profile, ok := data.Profiles[id] + return profile, ok +} + +func (data probeProfileFile) summaries() []map[string]any { + out := make([]map[string]any, 0, len(data.Profiles)) + for _, profile := range data.Profiles { + out = append(out, map[string]any{ + "id": profile.ID, + "name": profile.Name, + "built_in": profile.BuiltIn, + "match_mode": profile.MatchMode, + "has_expected": strings.TrimSpace(profile.ExpectedText) != "", + }) + } + sort.Slice(out, func(i, j int) bool { + leftBuiltIn, _ := out[i]["built_in"].(bool) + rightBuiltIn, _ := out[j]["built_in"].(bool) + if leftBuiltIn != rightBuiltIn { + return leftBuiltIn + } + leftID, _ := out[i]["id"].(string) + rightID, _ := out[j]["id"].(string) + return leftID < rightID + }) + return out +} + +func validateProbeProfile(profile *probeProfile, creating bool) error { + profile.Name = strings.TrimSpace(profile.Name) + profile.Prompt = strings.TrimSpace(profile.Prompt) + profile.ExpectedText = strings.TrimSpace(profile.ExpectedText) + profile.MatchMode = egressapp.NormalizeMatchMode(profile.MatchMode) + if profile.Name == "" { + return errors.New("方案名称不能为空") + } + if len(profile.Name) > 80 { + return errors.New("方案名称不能超过 80 个字符") + } + if profile.Prompt == "" { + return errors.New("探测 Prompt 不能为空") + } + if len(profile.Prompt) > egressapp.MaxQualityProbePromptBytes { + return errors.New("探测 Prompt 过长") + } + if len(profile.ExpectedText) > egressapp.MaxQualityProbeExpectedBytes { + return errors.New("预期标记过长") + } + if profile.MatchMode == egressapp.MatchRegex && profile.ExpectedText != "" { + if _, err := regexp.Compile(profile.ExpectedText); err != nil { + return fmt.Errorf("正则预期标记无效") + } + } + if profile.MaxOutputTokens < 0 || profile.MaxOutputTokens > egressapp.MaxQualityProbeOutputTokens { + return fmt.Errorf("方案最大输出需在 0 到 %d Token 之间", egressapp.MaxQualityProbeOutputTokens) + } + if creating && profile.BuiltIn { + return errors.New("不能新建内置方案") + } + return nil +} + +func applyProfile(base egressapp.QualityProbeInput, profile probeProfile) egressapp.QualityProbeInput { + base.Prompt = profile.Prompt + base.Expected = profile.ExpectedText + base.MatchMode = egressapp.NormalizeMatchMode(profile.MatchMode) + if profile.MaxOutputTokens > 0 { + base.MaxOutputTokens = profile.MaxOutputTokens + } + return base +} + +func (h *Handler) listQualityGuardProfiles(c *gin.Context) { + data, err := loadProbeProfileFile(h.profilesPath()) + if err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用") + return + } + items := make([]probeProfile, 0, len(data.Profiles)) + for _, profile := range data.Profiles { + items = append(items, profile) + } + sort.Slice(items, func(i, j int) bool { + if items[i].BuiltIn != items[j].BuiltIn { + return items[i].BuiltIn + } + return items[i].ID < items[j].ID + }) + response.Success(c, http.StatusOK, gin.H{ + "activeProfileId": data.ActiveProfileID, + "items": items, + }) +} + +type probeProfileWriteRequest struct { + Name string `json:"name"` + Prompt string `json:"prompt"` + ExpectedText string `json:"expectedText"` + MatchMode string `json:"matchMode"` + MaxOutputTokens int `json:"maxOutputTokens"` + Active bool `json:"active"` +} + +func (h *Handler) createQualityGuardProfile(c *gin.Context) { + path := h.profilesPath() + if path == "" { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardReadOnly", "探针方案当前只读") + return + } + var request probeProfileWriteRequest + if c.ShouldBindJSON(&request) != nil { + response.Error(c, http.StatusBadRequest, "invalidRequest", "请求参数无效") + return + } + data, err := loadProbeProfileFile(path) + if err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用") + return + } + custom := 0 + for _, profile := range data.Profiles { + if !profile.BuiltIn { + custom++ + } + } + if custom >= maxCustomProfiles { + response.Error(c, http.StatusBadRequest, "invalidRequest", fmt.Sprintf("自定义方案最多 %d 个", maxCustomProfiles)) + return + } + profile := probeProfile{ + Name: request.Name, Prompt: request.Prompt, ExpectedText: request.ExpectedText, + MatchMode: request.MatchMode, MaxOutputTokens: request.MaxOutputTokens, + } + if err := validateProbeProfile(&profile, true); err != nil { + response.Error(c, http.StatusBadRequest, "invalidRequest", err.Error()) + return + } + data.NextID++ + profile.ID = fmt.Sprintf("p-%d", data.NextID) + profile.UpdatedAt = float64(time.Now().Unix()) + data.Profiles[profile.ID] = profile + if request.Active { + data.ActiveProfileID = profile.ID + } + if err := saveProbeProfileFile(path, data); err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败") + return + } + response.Success(c, http.StatusOK, profile) +} + +func (h *Handler) updateQualityGuardProfile(c *gin.Context) { + path := h.profilesPath() + if path == "" { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardReadOnly", "探针方案当前只读") + return + } + id := strings.TrimSpace(c.Param("id")) + var request probeProfileWriteRequest + if c.ShouldBindJSON(&request) != nil { + response.Error(c, http.StatusBadRequest, "invalidRequest", "请求参数无效") + return + } + data, err := loadProbeProfileFile(path) + if err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用") + return + } + existing, ok := data.Profiles[id] + if !ok { + response.Error(c, http.StatusNotFound, "notFound", "方案不存在") + return + } + if existing.BuiltIn { + if request.Active { + data.ActiveProfileID = existing.ID + if err := saveProbeProfileFile(path, data); err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败") + return + } + response.Success(c, http.StatusOK, existing) + return + } + response.Error(c, http.StatusBadRequest, "invalidRequest", "内置方案不能修改,请复制后另存") + return + } + existing.Name = request.Name + existing.Prompt = request.Prompt + existing.ExpectedText = request.ExpectedText + existing.MatchMode = request.MatchMode + existing.MaxOutputTokens = request.MaxOutputTokens + if err := validateProbeProfile(&existing, false); err != nil { + response.Error(c, http.StatusBadRequest, "invalidRequest", err.Error()) + return + } + existing.UpdatedAt = float64(time.Now().Unix()) + data.Profiles[id] = existing + if request.Active { + data.ActiveProfileID = id + } + if err := saveProbeProfileFile(path, data); err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败") + return + } + response.Success(c, http.StatusOK, existing) +} + +func (h *Handler) deleteQualityGuardProfile(c *gin.Context) { + path := h.profilesPath() + if path == "" { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardReadOnly", "探针方案当前只读") + return + } + id := strings.TrimSpace(c.Param("id")) + data, err := loadProbeProfileFile(path) + if err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用") + return + } + existing, ok := data.Profiles[id] + if !ok { + response.Error(c, http.StatusNotFound, "notFound", "方案不存在") + return + } + if existing.BuiltIn { + response.Error(c, http.StatusBadRequest, "invalidRequest", "内置方案不能删除") + return + } + delete(data.Profiles, id) + if data.ActiveProfileID == id { + data.ActiveProfileID = profileQualityMarker + } + if err := saveProbeProfileFile(path, data); err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败") + return + } + response.Success(c, http.StatusOK, gin.H{"deleted": true}) +} + +func (h *Handler) resolveProbeInput(profileID string) (egressapp.QualityProbeInput, error) { + input := h.guardProbe + data, err := loadProbeProfileFile(h.profilesPath()) + if err != nil { + return input, err + } + profile, ok := data.resolve(profileID) + if !ok { + if profileID != "" { + return input, fmt.Errorf("方案不存在") + } + return input, nil + } + return applyProfile(input, profile), nil +} diff --git a/frontend/src/features/quality-guard/probe-profiles-panel.tsx b/frontend/src/features/quality-guard/probe-profiles-panel.tsx new file mode 100644 index 00000000..d013b78e --- /dev/null +++ b/frontend/src/features/quality-guard/probe-profiles-panel.tsx @@ -0,0 +1,186 @@ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { Pencil, Plus, Star, Trash2 } from "lucide-react"; +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { toast } from "sonner"; + +import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { Spinner } from "@/components/ui/spinner"; +import { Textarea } from "@/components/ui/textarea"; +import { createProbeProfile, deleteProbeProfile, listProbeProfiles, updateProbeProfile, type ProbeProfile } from "@/features/quality-guard/quality-guard-api"; + +type Draft = { + name: string; + prompt: string; + expectedText: string; + matchMode: string; +}; + +const emptyDraft = (): Draft => ({ name: "", prompt: "", expectedText: "", matchMode: "last_line" }); + +export function ProbeProfilesPanel() { + const { t } = useTranslation(); + const queryClient = useQueryClient(); + const [editing, setEditing] = useState(undefined); + const [draft, setDraft] = useState(emptyDraft()); + const [deleting, setDeleting] = useState(null); + const query = useQuery({ queryKey: ["quality-guard-profiles"], queryFn: listProbeProfiles }); + const invalidate = () => { + void queryClient.invalidateQueries({ queryKey: ["quality-guard-profiles"] }); + void queryClient.invalidateQueries({ queryKey: ["quality-guard"] }); + }; + const saveMutation = useMutation({ + mutationFn: async () => { + const payload = { + name: draft.name.trim(), + prompt: draft.prompt.trim(), + expectedText: draft.expectedText.trim(), + matchMode: draft.matchMode, + }; + if (editing && !editing.built_in) { + return updateProbeProfile(editing.id, payload); + } + return createProbeProfile(payload); + }, + onSuccess: () => { + toast.success(t("qualityGuard.profileSaved")); + setEditing(undefined); + invalidate(); + }, + onError: (error) => toast.error(error instanceof Error ? error.message : t("errors.generic")), + }); + const activateMutation = useMutation({ + mutationFn: (profile: ProbeProfile) => updateProbeProfile(profile.id, { + name: profile.name, + prompt: profile.prompt, + expectedText: profile.expected_text ?? "", + matchMode: profile.match_mode, + active: true, + }), + onSuccess: () => { + toast.success(t("qualityGuard.profileSaved")); + invalidate(); + }, + onError: (error) => toast.error(error instanceof Error ? error.message : t("errors.generic")), + }); + const deleteMutation = useMutation({ + mutationFn: (profile: ProbeProfile) => deleteProbeProfile(profile.id), + onSuccess: () => { + toast.success(t("qualityGuard.profileDeleted")); + setDeleting(null); + invalidate(); + }, + onError: (error) => toast.error(error instanceof Error ? error.message : t("errors.generic")), + }); + + const items = query.data?.items ?? []; + const activeId = query.data?.activeProfileId; + const readonly = Boolean(editing?.built_in); + const matchLabel = (mode: string) => { + if (mode === "last_line") return t("qualityGuard.profileMatchLastLine"); + if (mode === "regex") return t("qualityGuard.profileMatchRegex"); + return t("qualityGuard.profileMatchContains"); + }; + + return ( +
+
+
+

{t("qualityGuard.profilesTab")}

+

{t("qualityGuard.profilesHelp")}

+
+ +
+
+ {items.map((profile) => { + const active = profile.id === activeId; + const marker = profile.expected_text + ? `${t("qualityGuard.profileExpected")} ${profile.expected_text} · ${matchLabel(profile.match_mode)}` + : t("qualityGuard.profileNoExpected"); + return ( +
+
+
+ {profile.name} + {t(profile.built_in ? "qualityGuard.profileBuiltin" : "qualityGuard.profileCustom")} + {active ? {t("qualityGuard.profileActive")} : null} +
+

{marker}

+
+
+ {!active ? : null} + + {!profile.built_in ? : null} +
+
+ ); + })} +
+ + { if (!open && !saveMutation.isPending) setEditing(undefined); }}> + + + {editing ? t(readonly ? "qualityGuard.profileView" : "qualityGuard.profileEdit") : t("qualityGuard.profileCreate")} + {t("qualityGuard.profilesHelp")} + +
{ event.preventDefault(); if (!readonly) saveMutation.mutate(); }}> +
+ + setDraft({ ...draft, name: event.target.value })} /> +
+
+ + +
+
+ + setDraft({ ...draft, expectedText: event.target.value })} /> +

{t("qualityGuard.profileExpectedHelp")}

+
+
+ +