feat: add version check and update functionality

This commit is contained in:
Chenyme committed 2026-07-16 20:13:31 +08:00
1 parent 4b02f7da8d
commit 57e7e4ba8a
17 files changed
+667 -43

No files matched your search

+2
View File
@@ -1,5 +1,7 @@
**
!VERSION
!backend/
!backend/go.mod
!backend/go.sum
+1
View File
@@ -59,6 +59,7 @@ WORKDIR /app
COPY --from=backend-builder --chmod=0755 /out/grok2api /app/grok2api
COPY --from=frontend-builder /src/frontend/dist /app/frontend/dist
COPY VERSION /app/VERSION
COPY --chmod=0755 docker/entrypoint.sh /usr/local/bin/grok2api-entrypoint
EXPOSE 8000
+1 -1
View File
@@ -1 +1 @@
v3.0.0
v3.0.1
+14 -2
View File
@@ -22,6 +22,8 @@ import (
modelapp "github.com/chenyme/grok2api/backend/internal/application/model"
quotarecoveryapp "github.com/chenyme/grok2api/backend/internal/application/quotarecovery"
settingsapp "github.com/chenyme/grok2api/backend/internal/application/settings"
updatecheckapp "github.com/chenyme/grok2api/backend/internal/application/updatecheck"
"github.com/chenyme/grok2api/backend/internal/buildinfo"
"github.com/chenyme/grok2api/backend/internal/domain/account"
"github.com/chenyme/grok2api/backend/internal/infra/config"
infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress"
@@ -56,6 +58,7 @@ type Application struct {
accounts *accountapp.Service
models *modelapp.Service
clientKeys *clientkeyapp.Service
updates *updatecheckapp.Service
accountRepo repository.AccountRepository
modelRepo repository.ModelRepository
providers *provider.Registry
@@ -275,17 +278,18 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat
auditService.UpdateConfig(next.Audit.BatchSize, next.Audit.FlushInterval.Value())
clientKeyService.UpdateDefaults(next.ClientKeyDefaults.RPMLimit, next.ClientKeyDefaults.MaxConcurrent)
})
updateService := updatecheckapp.NewService(buildinfo.CurrentVersion(), nil)
startup := newStartupState(len(windows))
readiness := func(readyCtx context.Context) httpserver.ReadinessSnapshot {
return readinessSnapshot(readyCtx, startup, runtimeHealth, modelRepo, accountRepo, providers)
}
router := httpserver.New(httpserver.Dependencies{Logger: logger, RequestTimeout: cfg.Server.RequestTimeout.Value(), MaxBodyBytes: cfg.Server.MaxBodyBytes, ConcurrencyGate: inferenceConcurrency, SecureCookies: cfg.Auth.SecureCookies, SwaggerEnabled: cfg.Server.SwaggerEnabled, PublicAPIBaseURL: cfg.Frontend.EffectivePublicAPIBaseURL(), FrontendStaticPath: cfg.Frontend.StaticPath, Readiness: readiness, TrafficReady: startup.acceptsTraffic, AdminAuth: adminService, Accounts: accountService, AccountSync: accountSyncService, Models: modelService, ClientKeys: clientKeyService, Audits: auditService, Dashboard: dashboardService, Gateway: gatewayService, Media: mediaService, Settings: settingsService, Egress: egressService})
router := httpserver.New(httpserver.Dependencies{Logger: logger, RequestTimeout: cfg.Server.RequestTimeout.Value(), MaxBodyBytes: cfg.Server.MaxBodyBytes, ConcurrencyGate: inferenceConcurrency, SecureCookies: cfg.Auth.SecureCookies, SwaggerEnabled: cfg.Server.SwaggerEnabled, PublicAPIBaseURL: cfg.Frontend.EffectivePublicAPIBaseURL(), FrontendStaticPath: cfg.Frontend.StaticPath, Readiness: readiness, TrafficReady: startup.acceptsTraffic, AdminAuth: adminService, Accounts: accountService, AccountSync: accountSyncService, Models: modelService, ClientKeys: clientKeyService, Audits: auditService, Dashboard: dashboardService, Gateway: gatewayService, Media: mediaService, Settings: settingsService, Egress: egressService, Updates: updateService})
server := &http.Server{Addr: cfg.Server.Listen, Handler: router, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: cfg.Server.ReadTimeout.Value(), IdleTimeout: 2 * time.Minute, MaxHeaderBytes: 64 << 10}
return &Application{
logger: logger, database: database, server: server,
audits: auditService, responses: responseRepo, runtime: runtimeStore,
settingsBus: settingsBus, settings: settingsService, gateway: gatewayService, media: mediaService, quotaRecovery: quotaRecoveryService, accounts: accountService, models: modelService, clientKeys: clientKeyService,
settingsBus: settingsBus, settings: settingsService, gateway: gatewayService, media: mediaService, quotaRecovery: quotaRecoveryService, accounts: accountService, models: modelService, clientKeys: clientKeyService, updates: updateService,
accountRepo: accountRepo, modelRepo: modelRepo, providers: providers, web: webAdapter, startup: startup,
}, nil
}
@@ -355,6 +359,14 @@ func (a *Application) Run(ctx context.Context) error {
})
return nil
})
startBackground("release_check", func(taskCtx context.Context) error {
a.updates.Check(taskCtx)
a.runPeriodicTask(taskCtx, 24*time.Hour, "release_check", func(checkCtx context.Context) error {
a.updates.Check(checkCtx)
return nil
})
return nil
})
startBackground("billing_reservation_cleanup", func(taskCtx context.Context) error {
a.runPeriodicTask(taskCtx, 10*time.Minute, "billing_reservation_cleanup", func(runCtx context.Context) error {
_, err := a.clientKeys.CleanupExpiredBilling(runCtx, 1000)
@@ -0,0 +1,230 @@
package updatecheck
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/sync/singleflight"
)
const (
latestReleaseAPI = "https://api.github.com/repos/chenyme/grok2api/releases/latest"
maxReleaseBytes = 1 << 20
maxNotesRunes = 4096
)
type Status string
const (
StatusUnchecked Status = "unchecked"
StatusUpToDate Status = "up_to_date"
StatusUpdateAvailable Status = "update_available"
StatusCheckFailed Status = "check_failed"
)
type Snapshot struct {
CurrentVersion string `json:"currentVersion"`
LatestVersion string `json:"latestVersion"`
UpdateAvailable bool `json:"updateAvailable"`
Status Status `json:"status"`
CheckedAt *time.Time `json:"checkedAt"`
ReleaseURL string `json:"releaseUrl"`
ReleaseNotes string `json:"releaseNotes"`
Error string `json:"error"`
}
type Service struct {
current string
client *http.Client
now func() time.Time
mu sync.RWMutex
snapshot Snapshot
checks singleflight.Group
}
func NewService(currentVersion string, client *http.Client) *Service {
currentVersion = strings.TrimSpace(currentVersion)
if currentVersion == "" {
currentVersion = "dev"
}
if client == nil {
client = &http.Client{Timeout: 10 * time.Second}
}
return &Service{
current: currentVersion,
client: client,
now: time.Now,
snapshot: Snapshot{
CurrentVersion: currentVersion,
Status: StatusUnchecked,
},
}
}
func (s *Service) Snapshot() Snapshot {
s.mu.RLock()
defer s.mu.RUnlock()
return cloneSnapshot(s.snapshot)
}
func (s *Service) Check(ctx context.Context) Snapshot {
result, err, _ := s.checks.Do("latest", func() (any, error) {
return s.fetchLatest(ctx)
})
s.mu.Lock()
defer s.mu.Unlock()
if err != nil {
s.snapshot.Status = StatusCheckFailed
s.snapshot.Error = err.Error()
return cloneSnapshot(s.snapshot)
}
release := result.(latestRelease)
checkedAt := s.now().UTC()
current, currentOK := parseSemanticVersion(s.current)
latest, latestOK := parseSemanticVersion(release.Tag)
if !currentOK || !latestOK {
s.snapshot.LatestVersion = release.Tag
s.snapshot.ReleaseURL = release.URL
s.snapshot.ReleaseNotes = release.Notes
s.snapshot.Status = StatusCheckFailed
s.snapshot.Error = "当前版本或最新版本不是有效的语义化版本,无法比较"
return cloneSnapshot(s.snapshot)
}
available := compareSemanticVersion(latest, current) > 0
s.snapshot = Snapshot{
CurrentVersion: s.current, LatestVersion: release.Tag,
UpdateAvailable: available, CheckedAt: &checkedAt,
ReleaseURL: release.URL, ReleaseNotes: release.Notes,
Status: StatusUpToDate,
}
if available {
s.snapshot.Status = StatusUpdateAvailable
}
return cloneSnapshot(s.snapshot)
}
type latestRelease struct {
Tag string
URL string
Notes string
}
func (s *Service) fetchLatest(ctx context.Context) (latestRelease, error) {
request, err := http.NewRequestWithContext(ctx, http.MethodGet, latestReleaseAPI, nil)
if err != nil {
return latestRelease{}, err
}
request.Header.Set("Accept", "application/vnd.github+json")
request.Header.Set("User-Agent", "grok2api/"+s.current)
request.Header.Set("X-GitHub-Api-Version", "2022-11-28")
response, err := s.client.Do(request)
if err != nil {
return latestRelease{}, fmt.Errorf("检查 GitHub Release 失败: %w", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return latestRelease{}, fmt.Errorf("GitHub Release 检查失败(HTTP %d)", response.StatusCode)
}
data, err := io.ReadAll(io.LimitReader(response.Body, maxReleaseBytes+1))
if err != nil {
return latestRelease{}, fmt.Errorf("读取 GitHub Release 响应: %w", err)
}
if len(data) > maxReleaseBytes {
return latestRelease{}, errors.New("GitHub Release 响应超过安全上限")
}
var payload struct {
Tag string `json:"tag_name"`
Body string `json:"body"`
}
if err := json.Unmarshal(data, &payload); err != nil {
return latestRelease{}, fmt.Errorf("解析 GitHub Release 响应: %w", err)
}
payload.Tag = strings.TrimSpace(payload.Tag)
if payload.Tag == "" {
return latestRelease{}, errors.New("GitHub Release 未返回版本号")
}
return latestRelease{
Tag: payload.Tag,
URL: "https://github.com/chenyme/grok2api/releases/tag/" + url.PathEscape(payload.Tag),
Notes: truncateRunes(strings.TrimSpace(payload.Body), maxNotesRunes),
}, nil
}
type semanticVersion struct {
major, minor, patch uint64
prerelease string
}
func parseSemanticVersion(value string) (semanticVersion, bool) {
value = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(value), "v"))
if before, _, ok := strings.Cut(value, "+"); ok {
value = before
}
prerelease := ""
if before, after, ok := strings.Cut(value, "-"); ok {
value, prerelease = before, after
}
parts := strings.Split(value, ".")
if len(parts) != 3 {
return semanticVersion{}, false
}
numbers := make([]uint64, 3)
for index, part := range parts {
if part == "" || (len(part) > 1 && part[0] == '0') {
return semanticVersion{}, false
}
value, err := strconv.ParseUint(part, 10, 64)
if err != nil {
return semanticVersion{}, false
}
numbers[index] = value
}
return semanticVersion{major: numbers[0], minor: numbers[1], patch: numbers[2], prerelease: prerelease}, true
}
func compareSemanticVersion(left, right semanticVersion) int {
for _, pair := range [][2]uint64{{left.major, right.major}, {left.minor, right.minor}, {left.patch, right.patch}} {
if pair[0] < pair[1] {
return -1
}
if pair[0] > pair[1] {
return 1
}
}
if left.prerelease == right.prerelease {
return 0
}
if left.prerelease == "" {
return 1
}
if right.prerelease == "" {
return -1
}
return strings.Compare(left.prerelease, right.prerelease)
}
func truncateRunes(value string, limit int) string {
runes := []rune(value)
if len(runes) <= limit {
return value
}
return string(runes[:limit])
}
func cloneSnapshot(value Snapshot) Snapshot {
if value.CheckedAt != nil {
checkedAt := *value.CheckedAt
value.CheckedAt = &checkedAt
}
return value
}
@@ -0,0 +1,68 @@
package updatecheck
import (
"context"
"errors"
"io"
"net/http"
"strings"
"testing"
"time"
)
type roundTripFunc func(*http.Request) (*http.Response, error)
func (function roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) {
return function(request)
}
func TestCheckFindsLatestRelease(t *testing.T) {
client := &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) {
if request.URL.String() != latestReleaseAPI || request.Header.Get("User-Agent") != "grok2api/v3.0.0" {
t.Fatalf("request = %#v", request)
}
return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(`{"tag_name":"v3.0.1","body":"Release notes"}`)), Header: make(http.Header)}, nil
})}
service := NewService("v3.0.0", client)
now := time.Date(2026, 7, 16, 12, 0, 0, 0, time.UTC)
service.now = func() time.Time { return now }
snapshot := service.Check(context.Background())
if snapshot.Status != StatusUpdateAvailable || !snapshot.UpdateAvailable || snapshot.LatestVersion != "v3.0.1" || snapshot.CheckedAt == nil || !snapshot.CheckedAt.Equal(now) {
t.Fatalf("snapshot = %#v", snapshot)
}
if snapshot.ReleaseURL != "https://github.com/chenyme/grok2api/releases/tag/v3.0.1" || snapshot.ReleaseNotes != "Release notes" {
t.Fatalf("release = %#v", snapshot)
}
}
func TestCheckFailureKeepsLastSuccessfulRelease(t *testing.T) {
fail := false
client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
if fail {
return nil, errors.New("network down")
}
return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(`{"tag_name":"v3.0.0","body":"Stable"}`)), Header: make(http.Header)}, nil
})}
service := NewService("v3.0.0", client)
first := service.Check(context.Background())
fail = true
second := service.Check(context.Background())
if first.Status != StatusUpToDate || second.Status != StatusCheckFailed || second.LatestVersion != "v3.0.0" || second.CheckedAt == nil || second.Error == "" {
t.Fatalf("first=%#v second=%#v", first, second)
}
}
func TestSemanticVersionComparison(t *testing.T) {
stable, ok := parseSemanticVersion("v3.0.1")
if !ok {
t.Fatal("stable version was rejected")
}
older, _ := parseSemanticVersion("3.0.0")
prerelease, _ := parseSemanticVersion("v3.0.1-rc.1")
if compareSemanticVersion(stable, older) <= 0 || compareSemanticVersion(prerelease, stable) >= 0 {
t.Fatal("semantic version ordering is invalid")
}
if _, ok := parseSemanticVersion("dev"); ok {
t.Fatal("development version was accepted as semver")
}
}
+45
View File
@@ -0,0 +1,45 @@
package buildinfo
import (
"os"
"path/filepath"
"runtime/debug"
"strings"
)
// Version 可在发布构建时通过 -ldflags -X 注入。
var Version string
// CurrentVersion 返回当前运行实例的版本。源码运行优先读取仓库 VERSION,
// 容器和发行包可将 VERSION 放在可执行文件同目录。
func CurrentVersion() string {
if value := cleanVersion(Version); value != "" {
return value
}
if value := cleanVersion(os.Getenv("GROK2API_VERSION")); value != "" {
return value
}
candidates := []string{"VERSION", filepath.Join("..", "VERSION")}
if executable, err := os.Executable(); err == nil {
candidates = append(candidates, filepath.Join(filepath.Dir(executable), "VERSION"))
}
for _, candidate := range candidates {
if data, err := os.ReadFile(candidate); err == nil {
if value := cleanVersion(string(data)); value != "" {
return value
}
}
}
if info, ok := debug.ReadBuildInfo(); ok && info.Main.Version != "" && info.Main.Version != "(devel)" {
return info.Main.Version
}
return "dev"
}
func cleanVersion(value string) string {
value = strings.TrimSpace(value)
if len(value) > 128 || strings.IndexFunc(value, func(r rune) bool { return r < 0x20 || r == 0x7f }) >= 0 {
return ""
}
return value
}
+3 -1
View File
@@ -18,6 +18,7 @@ import (
mediaapp "github.com/chenyme/grok2api/backend/internal/application/media"
modelapp "github.com/chenyme/grok2api/backend/internal/application/model"
settingsapp "github.com/chenyme/grok2api/backend/internal/application/settings"
updatecheckapp "github.com/chenyme/grok2api/backend/internal/application/updatecheck"
accounthttp "github.com/chenyme/grok2api/backend/internal/transport/http/account"
adminauthhttp "github.com/chenyme/grok2api/backend/internal/transport/http/adminauth"
audithttp "github.com/chenyme/grok2api/backend/internal/transport/http/audit"
@@ -59,6 +60,7 @@ type Dependencies struct {
Media *mediaapp.Service
Settings *settingsapp.Service
Egress *egressapp.Service
Updates *updatecheckapp.Service
}
type ReadinessComponent struct {
@@ -152,7 +154,7 @@ func New(deps Dependencies) *gin.Engine {
return deps.Settings.PublicAPIBaseURL()
}
return deps.PublicAPIBaseURL
}).Register(adminProtected)
}, deps.Updates).Register(adminProtected)
v1 := router.Group("/v1")
v1.Use(deps.ConcurrencyGate.Middleware())
+15 -6
View File
@@ -72,15 +72,24 @@ func TestInferenceTrafficIsRejectedWhileReconciling(t *testing.T) {
}
}
func TestSystemInfoRequiresAdminAuthentication(t *testing.T) {
func TestSystemEndpointsRequireAdminAuthentication(t *testing.T) {
deps := testDependencies()
deps.PublicAPIBaseURL = "https://api.example.com"
router := New(deps)
request := httptest.NewRequest(http.MethodGet, "/api/admin/v1/system", nil)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, request)
if recorder.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusUnauthorized)
for _, route := range []struct {
method string
path string
}{
{method: http.MethodGet, path: "/api/admin/v1/system"},
{method: http.MethodGet, path: "/api/admin/v1/system/version"},
{method: http.MethodPost, path: "/api/admin/v1/system/update/check"},
} {
request := httptest.NewRequest(route.method, route.path, nil)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, request)
if recorder.Code != http.StatusUnauthorized {
t.Fatalf("%s %s status = %d, want %d", route.method, route.path, recorder.Code, http.StatusUnauthorized)
}
}
}
@@ -4,23 +4,38 @@ import (
"net/http"
"strings"
updatecheckapp "github.com/chenyme/grok2api/backend/internal/application/updatecheck"
"github.com/chenyme/grok2api/backend/internal/shared/response"
"github.com/gin-gonic/gin"
)
type Handler struct {
publicAPIBaseURL func() string
updates *updatecheckapp.Service
}
func NewHandler(publicAPIBaseURL func() string) *Handler {
func NewHandler(publicAPIBaseURL func() string, updates *updatecheckapp.Service) *Handler {
if publicAPIBaseURL == nil {
publicAPIBaseURL = func() string { return "" }
}
return &Handler{publicAPIBaseURL: publicAPIBaseURL}
if updates == nil {
updates = updatecheckapp.NewService("dev", nil)
}
return &Handler{publicAPIBaseURL: publicAPIBaseURL, updates: updates}
}
func (h *Handler) Register(router *gin.RouterGroup) {
router.GET("/system", h.get)
router.GET("/system/version", h.version)
router.POST("/system/update/check", h.checkUpdate)
}
func (h *Handler) version(c *gin.Context) {
response.Success(c, http.StatusOK, h.updates.Snapshot())
}
func (h *Handler) checkUpdate(c *gin.Context) {
response.Success(c, http.StatusOK, h.updates.Check(c.Request.Context()))
}
func (h *Handler) get(c *gin.Context) {
@@ -2,17 +2,26 @@ package system
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
updatecheckapp "github.com/chenyme/grok2api/backend/internal/application/updatecheck"
"github.com/gin-gonic/gin"
)
type roundTripFunc func(*http.Request) (*http.Response, error)
func (function roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) {
return function(request)
}
func TestHandlerReturnsOnlyPublicFrontendConfig(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
NewHandler(func() string { return "https://api.example.com/" }).Register(router.Group("/api/admin/v1"))
NewHandler(func() string { return "https://api.example.com/" }, updatecheckapp.NewService("v3.0.0", nil)).Register(router.Group("/api/admin/v1"))
request := httptest.NewRequest(http.MethodGet, "/api/admin/v1/system", nil)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, request)
@@ -29,3 +38,41 @@ func TestHandlerReturnsOnlyPublicFrontendConfig(t *testing.T) {
t.Fatalf("data = %#v", payload.Data)
}
}
func TestHandlerReturnsAndChecksVersion(t *testing.T) {
gin.SetMode(gin.TestMode)
client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"tag_name":"v3.0.1","body":"Notes"}`))}, nil
})}
router := gin.New()
updates := updatecheckapp.NewService("v3.0.0", client)
NewHandler(nil, updates).Register(router.Group("/api/admin/v1"))
for _, test := range []struct {
method string
path string
status string
}{
{method: http.MethodGet, path: "/api/admin/v1/system/version", status: "unchecked"},
{method: http.MethodPost, path: "/api/admin/v1/system/update/check", status: "update_available"},
} {
request := httptest.NewRequest(test.method, test.path, nil)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, request)
if recorder.Code != http.StatusOK {
t.Fatalf("%s %s status = %d", test.method, test.path, recorder.Code)
}
var payload struct {
Data struct {
CurrentVersion string `json:"currentVersion"`
Status string `json:"status"`
} `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatal(err)
}
if payload.Data.CurrentVersion != "v3.0.0" || payload.Data.Status != test.status {
t.Fatalf("%s %s data = %#v", test.method, test.path, payload.Data)
}
}
}
+5 -3
View File
@@ -18,6 +18,7 @@ import { useAuth } from "@/shared/auth/use-auth";
import { GitHubMark } from "@/shared/components/github-mark";
import { SiteFooter } from "@/shared/components/site-footer";
import { cn } from "@/shared/lib/cn";
import { CurrentVersionLabel } from "@/features/system/version-update";
const navigation = [
{ href: "/dashboard", label: "nav.dashboard", icon: LayoutDashboard },
@@ -217,8 +218,9 @@ export function AppShell() {
<div className="min-h-screen bg-background">
<aside className="fixed inset-y-0 left-0 z-30 hidden h-screen w-[288px] flex-col overflow-hidden bg-sidebar px-4 py-6 lg:flex">
<div className="flex h-7 shrink-0 items-center justify-between px-2.5">
<Link to="/dashboard" className="flex h-7 items-center text-base font-semibold text-foreground">
{t("appName")}
<Link to="/dashboard" className="flex h-7 items-baseline gap-2 text-base font-semibold text-foreground">
<span>{t("appName")}</span>
<CurrentVersionLabel />
</Link>
<Button variant="ghost" size="icon" className="size-7 text-muted-foreground [&_svg]:size-[15px]" asChild>
<a href="https://github.com/chenyme/grok2api" target="_blank" rel="noreferrer" aria-label="GitHub">
@@ -243,7 +245,7 @@ export function AppShell() {
<div className="relative z-10 mt-3 shrink-0 bg-sidebar pt-3">{accountControl}</div>
</SheetContent>
</Sheet>
<span className="text-sm font-semibold">{t("appName")}</span>
<span className="flex items-baseline gap-2 text-sm font-semibold"><span>{t("appName")}</span><CurrentVersionLabel /></span>
<Button variant="ghost" size="icon" className="size-8 text-muted-foreground hover:text-foreground" asChild>
<a href="https://github.com/chenyme/grok2api" target="_blank" rel="noreferrer" aria-label="GitHub">
<GitHubMark />
+34 -1
View File
@@ -1,5 +1,5 @@
import { apiRequest } from "@/shared/api/client";
import { createObjectDecoder, isString } from "@/shared/api/decoder";
import { createObjectDecoder, isBoolean, isOneOf, isString, type ValueValidator } from "@/shared/api/decoder";
export type SystemInfoDTO = {
publicApiBaseURL: string;
@@ -10,3 +10,36 @@ const decodeSystemInfo = createObjectDecoder<SystemInfoDTO>("system info", { pub
export function getSystemInfo(): Promise<SystemInfoDTO> {
return apiRequest("/api/admin/v1/system", {}, decodeSystemInfo);
}
export type UpdateStatus = "unchecked" | "up_to_date" | "update_available" | "check_failed";
export type VersionInfoDTO = {
currentVersion: string;
latestVersion: string;
updateAvailable: boolean;
status: UpdateStatus;
checkedAt: string | null;
releaseUrl: string;
releaseNotes: string;
error: string;
};
const isNullableString: ValueValidator = (value) => value === null || isString(value);
const decodeVersionInfo = createObjectDecoder<VersionInfoDTO>("version info", {
currentVersion: isString,
latestVersion: isString,
updateAvailable: isBoolean,
status: isOneOf("unchecked", "up_to_date", "update_available", "check_failed"),
checkedAt: isNullableString,
releaseUrl: isString,
releaseNotes: isString,
error: isString,
});
export function getVersionInfo(): Promise<VersionInfoDTO> {
return apiRequest("/api/admin/v1/system/version", {}, decodeVersionInfo);
}
export function checkForUpdates(): Promise<VersionInfoDTO> {
return apiRequest("/api/admin/v1/system/update/check", { method: "POST" }, decodeVersionInfo);
}
@@ -8,6 +8,7 @@ import { Button } from "@/components/ui/button";
import { ChartContainer, ChartLegend, ChartLegendContent, ChartTooltip, ChartTooltipContent, type ChartConfig } from "@/components/ui/chart";
import { Spinner } from "@/components/ui/spinner";
import { getDashboard, type DashboardPeriod, type DashboardDTO } from "@/features/dashboard/dashboard-api";
import { VersionUpdateBanner } from "@/features/system/version-update";
import { useAuth } from "@/shared/auth/use-auth";
import { ErrorState } from "@/shared/components/data-state";
import { PeriodSelector } from "@/shared/components/period-selector";
@@ -81,32 +82,36 @@ export function DashboardPage() {
return (
<div className="space-y-8">
<header>
<div>
<h1 className="text-xl font-medium">{t("dashboard.title")}</h1>
<p className="mt-1 text-xs text-muted-foreground">
{t("dashboard.subtitle", { name: displayName })}
{dashboard?.generatedAt ? <span> · {t("dashboard.lastUpdated", { time: formatDateTime(dashboard.generatedAt, i18n.language) })}</span> : null}
</p>
</div>
</header>
<section className="space-y-4">
<div className="flex items-center justify-between gap-3">
<h2 className="shrink-0 text-sm font-medium">{t("dashboard.usage")}</h2>
<div className="flex min-w-0 shrink-0 items-center gap-2">
<Button variant="ghost" size="icon" className="size-8 text-muted-foreground" onClick={refreshAll} disabled={dashboardQuery.isFetching || manualRefreshing} aria-label={t("common.refresh")}><RefreshCw className={manualRefreshing ? "animate-spin" : undefined} /></Button>
<PeriodSelector value={periodDays} onChange={(value) => setPreferences((current) => ({ ...current, periodDays: value }))} ariaLabel={t("dashboard.usage")} />
<div className="space-y-5">
<header>
<div>
<h1 className="text-xl font-medium">{t("dashboard.title")}</h1>
<p className="mt-1 text-xs text-muted-foreground">
{t("dashboard.subtitle", { name: displayName })}
{dashboard?.generatedAt ? <span> · {t("dashboard.lastUpdated", { time: formatDateTime(dashboard.generatedAt, i18n.language) })}</span> : null}
</p>
</div>
</div>
</header>
<div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-4">
<MetricCard icon={<Users />} label={t("dashboard.activeAccounts")} value={formatNumber(activeAccounts, i18n.language)} detail={t("dashboard.availableSummary", { active: activeAccounts, total: resources?.totalAccounts ?? 0 })} loading={loading} />
<MetricCard icon={<Activity />} label={t("dashboard.requests")} value={formatNumber(usage?.requests ?? 0, i18n.language)} detail={t("dashboard.requestQualitySummary", { success: formatNumber(usage?.successRate ?? 0, i18n.language, 1), failed: usage?.failedRequests ?? 0 })} loading={loading} />
<MetricCard icon={<Box />} label={t("dashboard.tokens")} value={formatNumber(usage?.tokens ?? 0, i18n.language)} detail={t("dashboard.tokenEfficiency", { rate: formatNumber(cacheHitRate, i18n.language, 1) })} loading={loading} />
<MetricCard icon={<CircleDollarSign />} label={t("dashboard.billing")} value={formatUSD(usage?.billedCostUsdTicks ?? 0, i18n.language)} detail={t("dashboard.billingSummary", { period })} loading={loading} />
</div>
</section>
<VersionUpdateBanner />
<section className="space-y-4">
<div className="flex items-center justify-between gap-3">
<h2 className="shrink-0 text-sm font-medium">{t("dashboard.usage")}</h2>
<div className="flex min-w-0 shrink-0 items-center gap-2">
<Button variant="ghost" size="icon" className="size-8 text-muted-foreground" onClick={refreshAll} disabled={dashboardQuery.isFetching || manualRefreshing} aria-label={t("common.refresh")}><RefreshCw className={manualRefreshing ? "animate-spin" : undefined} /></Button>
<PeriodSelector value={periodDays} onChange={(value) => setPreferences((current) => ({ ...current, periodDays: value }))} ariaLabel={t("dashboard.usage")} />
</div>
</div>
<div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-4">
<MetricCard icon={<Users />} label={t("dashboard.activeAccounts")} value={formatNumber(activeAccounts, i18n.language)} detail={t("dashboard.availableSummary", { active: activeAccounts, total: resources?.totalAccounts ?? 0 })} loading={loading} />
<MetricCard icon={<Activity />} label={t("dashboard.requests")} value={formatNumber(usage?.requests ?? 0, i18n.language)} detail={t("dashboard.requestQualitySummary", { success: formatNumber(usage?.successRate ?? 0, i18n.language, 1), failed: usage?.failedRequests ?? 0 })} loading={loading} />
<MetricCard icon={<Box />} label={t("dashboard.tokens")} value={formatNumber(usage?.tokens ?? 0, i18n.language)} detail={t("dashboard.tokenEfficiency", { rate: formatNumber(cacheHitRate, i18n.language, 1) })} loading={loading} />
<MetricCard icon={<CircleDollarSign />} label={t("dashboard.billing")} value={formatUSD(usage?.billedCostUsdTicks ?? 0, i18n.language)} detail={t("dashboard.billingSummary", { period })} loading={loading} />
</div>
</section>
</div>
<TrendPanel dashboard={dashboard} metric={trendMetric} onMetricChange={(value) => setPreferences((current) => ({ ...current, trendMetric: value }))} locale={i18n.language} loading={loading} />
@@ -11,6 +11,7 @@ import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { EgressNodes } from "@/features/settings/egress-nodes";
import { VersionUpdateSection } from "@/features/system/version-update";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { isByteSizeUnit, isDurationUnit, type ByteSizeValue, type DurationValue } from "@/features/settings/settings-model";
import { useSettings } from "@/features/settings/use-settings";
@@ -69,6 +70,7 @@ export function SettingsPage() {
<TabsTrigger value="providers">{t("settings.groups.providers")}</TabsTrigger>
<TabsTrigger value="delivery">{t("settings.groups.delivery")}</TabsTrigger>
<TabsTrigger value="policies">{t("settings.groups.policies")}</TabsTrigger>
<TabsTrigger value="about">{t("settings.groups.about")}</TabsTrigger>
</TabsList>
<SettingsPane value="providers">
@@ -207,6 +209,10 @@ export function SettingsPage() {
</div>
</SettingsSection>
</SettingsPane>
<SettingsPane value="about">
<VersionUpdateSection />
</SettingsPane>
</Tabs>
) : null}
</form>
@@ -0,0 +1,123 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { ArrowUpRight, RefreshCw } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { checkForUpdates, getVersionInfo, type UpdateStatus } from "@/entities/system/system-api";
import { cn } from "@/shared/lib/cn";
import { formatDateTime } from "@/shared/lib/format";
const versionQueryKey = ["system-version"] as const;
function useVersionInfo() {
return useQuery({
queryKey: versionQueryKey,
queryFn: getVersionInfo,
staleTime: 60_000,
retry: 1,
});
}
function useCheckForUpdates() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: checkForUpdates,
onSuccess: (value) => queryClient.setQueryData(versionQueryKey, value),
});
}
export function CurrentVersionLabel() {
const versionQuery = useVersionInfo();
const version = versionQuery.data?.currentVersion;
if (!version) return null;
return <span className="font-mono text-[10px] font-normal text-muted-foreground">{version}</span>;
}
export function VersionUpdateBanner() {
const { t } = useTranslation();
const versionQuery = useVersionInfo();
const checkMutation = useCheckForUpdates();
const version = versionQuery.data;
if (!version?.updateAvailable) return null;
return (
<section className="flex flex-col gap-3 rounded-lg bg-amber-500/10 px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0">
<p className="text-sm font-medium">{t("updates.available", { version: version.latestVersion })}</p>
<p className="mt-0.5 text-xs text-muted-foreground">{t("updates.currentSummary", { version: version.currentVersion })}</p>
</div>
<div className="flex shrink-0 items-center gap-0.5">
{version.releaseUrl ? (
<Button variant="ghost" size="sm" className="h-7 px-2.5 text-xs font-normal text-muted-foreground hover:text-foreground" asChild>
<a href={version.releaseUrl} target="_blank" rel="noreferrer">{t("updates.viewRelease")}<ArrowUpRight className="size-3.5" /></a>
</Button>
) : null}
{version.releaseUrl ? <span className="mx-1 h-3 w-px bg-border/70" /> : null}
<Button variant="ghost" size="sm" className="h-7 px-2.5 text-xs font-normal text-muted-foreground hover:text-foreground" disabled={checkMutation.isPending} onClick={() => checkMutation.mutate()}>
{checkMutation.isPending ? <Spinner /> : <RefreshCw className="size-3.5" />}{t("updates.checkNow")}
</Button>
</div>
</section>
);
}
export function VersionUpdateSection() {
const { t, i18n } = useTranslation();
const versionQuery = useVersionInfo();
const checkMutation = useCheckForUpdates();
const version = versionQuery.data;
const requestError = versionQuery.error instanceof Error ? versionQuery.error.message : "";
const checkError = checkMutation.error instanceof Error ? checkMutation.error.message : "";
const error = version?.error || checkError || requestError;
return (
<section className="space-y-4">
<div className="flex min-h-8 items-center justify-between gap-3">
<h2 className="text-sm font-medium">{t("updates.title")}</h2>
<Button type="button" variant="secondary" size="sm" disabled={versionQuery.isPending || checkMutation.isPending} onClick={() => checkMutation.mutate()}>
{versionQuery.isPending || checkMutation.isPending ? <Spinner /> : <RefreshCw />}{t("updates.checkNow")}
</Button>
</div>
<div className="grid max-w-[860px] gap-x-8 gap-y-5 sm:grid-cols-2">
<VersionField label={t("updates.currentVersion")} value={version?.currentVersion || "-"} />
<VersionField label={t("updates.latestVersion")} value={version?.latestVersion || t("updates.notChecked")} />
<VersionField label={t("updates.statusLabel")} value={version ? t(`updates.status.${version.status}`) : t("common.loading")} status={version?.status} />
<VersionField label={t("updates.checkedAt")} value={version?.checkedAt ? formatDateTime(version.checkedAt, i18n.language) : t("updates.neverChecked")} />
</div>
{error ? <p className="max-w-[860px] text-xs leading-5 text-destructive">{error}</p> : null}
{version?.releaseNotes || version?.releaseUrl ? (
<div className="max-w-[860px] rounded-lg bg-muted/40 p-4">
<div className="flex items-center justify-between gap-3">
<h3 className="text-xs font-medium">{t("updates.releaseNotes")}</h3>
{version.releaseUrl ? (
<Button type="button" variant="ghost" size="sm" className="h-7 px-2 text-xs" asChild>
<a href={version.releaseUrl} target="_blank" rel="noreferrer">{t("updates.openRelease")}<ArrowUpRight /></a>
</Button>
) : null}
</div>
<p className="mt-2 max-h-40 overflow-y-auto whitespace-pre-wrap break-words text-xs leading-5 text-muted-foreground">
{version.releaseNotes || t("updates.noReleaseNotes")}
</p>
</div>
) : null}
<p className="max-w-[860px] text-xs leading-5 text-muted-foreground">{t("updates.manualOnly")}</p>
</section>
);
}
function VersionField({ label, value, status }: { label: string; value: string; status?: UpdateStatus }) {
return (
<div>
<p className="text-xs text-muted-foreground">{label}</p>
<div className="mt-1.5 flex items-center gap-2 text-sm font-medium">
{status ? <span className={cn("size-1.5 rounded-full bg-muted-foreground", status === "up_to_date" && "bg-emerald-500", status === "update_available" && "bg-amber-500", status === "check_failed" && "bg-destructive")} /> : null}
<span className="break-all">{value}</span>
</div>
</div>
);
}
+26 -2
View File
@@ -97,6 +97,29 @@ const resources = {
sortAscending: "按{{column}}升序排列",
sortDescending: "按{{column}}降序排列",
},
updates: {
title: "关于与更新",
currentVersion: "当前版本",
latestVersion: "最新版本",
statusLabel: "更新状态",
checkedAt: "上次成功检查",
checkNow: "检查更新",
viewRelease: "查看更新",
openRelease: "打开 Release",
releaseNotes: "更新说明",
noReleaseNotes: "该版本没有更新说明。",
notChecked: "尚未获取",
neverChecked: "尚未成功检查",
available: "发现新版本 {{version}}",
currentSummary: "当前运行 {{version}}",
manualOnly: "当前仅提供版本检查与更新提示,不会自动下载、安装或重启服务。",
status: {
unchecked: "尚未检查",
up_to_date: "已是最新",
update_available: "发现新版本",
check_failed: "检查失败",
},
},
nav: {
dashboard: "仪表盘",
accounts: "账号",
@@ -598,7 +621,7 @@ const resources = {
restartRequired: "重启生效",
invalidValue: "请输入有效值",
durationUnit: "时长单位",
groups: { providers: "Provider 配置", delivery: "媒体与网络", policies: "运行策略" },
groups: { providers: "Provider 配置", delivery: "媒体与网络", policies: "运行策略", about: "关于" },
server: { title: "服务容量", maxConcurrentRequests: "API 请求并发上限", maxConcurrentRequestsHelp: "单实例同时处理的 /v1 请求数;调低不会中断进行中的请求。" },
provider: { title: "Grok Build", baseURL: "上游地址", clientVersion: "客户端版本", clientIdentifier: "客户端标识", tokenAuth: "Token Auth", userAgent: "User-Agent", recommendedVersion: "推荐 {{version}}", syncRecommendedVersion: "同步推荐版本", recommendedVersionApplied: "已是推荐版本", syncRecommendedVersionDescription: "填入后端当前已完成兼容回归的版本和 User-Agent,保存后生效。" },
web: { title: "Grok Web", baseURL: "上游地址", statsigMode: "x-statsig 获取方式", statsigManual: "手动填写", statsigURL: "URL 获取", statsigValue: "x-statsig-id", statsigConfigured: "已配置", statsigKeepConfigured: "留空保持当前配置", statsigValuePlaceholder: "粘贴 x-statsig-id", statsigSignerURL: "签名服务 URL", quotaTimeout: "额度请求超时", chatTimeout: "聊天超时", imageTimeout: "图片超时", videoTimeout: "视频超时", mediaConcurrency: "媒体任务并发", recoveryBackoffBase: "额度恢复退避", recoveryBackoffMax: "额度恢复最大退避", allowNSFW: "允许 NSFW 图片" },
@@ -870,6 +893,7 @@ const resources = {
expiryUnknown: "Credential expiry is unknown",
},
common: { actions: "Actions", cancel: "Cancel", close: "Close", copy: "Copy", copied: "Copied", copyFailed: "Copy failed", create: "Create", delete: "Delete", disabled: "Disabled", disable: "Disable", edit: "Edit", enabled: "Enabled", enable: "Enable", loading: "Loading", importingProgress: "Importing, completed {{completed}} / {{total}}", syncingProgress: "Syncing initial data, completed {{completed}} / {{total}}", noData: "No data", pageOf: "Page {{page}}/{{pages}}", perPage: "Per page", rows: "rows", firstPage: "First page", lastPage: "Last page", previousPage: "Previous page", nextPage: "Next page", selectedCount: "{{count}} selected", selectPage: "Select this page", selectItem: "Select {{name}}", refresh: "Refresh", retry: "Retry", filter: "Filters", all: "All", clearFilters: "Clear filters", save: "Save", reset: "Reset", sortAscending: "Sort {{column}} ascending", sortDescending: "Sort {{column}} descending" },
updates: { title: "About & updates", currentVersion: "Current version", latestVersion: "Latest version", statusLabel: "Update status", checkedAt: "Last successful check", checkNow: "Check for updates", viewRelease: "View update", openRelease: "Open Release", releaseNotes: "Release notes", noReleaseNotes: "No release notes are available for this version.", notChecked: "Not fetched", neverChecked: "No successful check yet", available: "New version {{version}} available", currentSummary: "Running {{version}}", manualOnly: "Only version checks and update notices are enabled. The service will not download, install, or restart automatically.", status: { unchecked: "Not checked", up_to_date: "Up to date", update_available: "Update available", check_failed: "Check failed" } },
nav: { dashboard: "Dashboard", accounts: "Accounts", models: "Models", clientKeys: "Client keys", creativeConsole: "Creative console", gallery: "Gallery", videoGallery: "Video Gallery", audits: "Request audits", docs: "Documentation", settings: "Settings" },
creativeConsole: {
title: "Creative console",
@@ -1020,7 +1044,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" }, 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", clientVersion: "Client version", clientIdentifier: "Client identifier", tokenAuth: "Token auth", userAgent: "User-Agent", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync recommended version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill in the backend version and User-Agent that passed compatibility regression; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", statsigMode: "x-statsig source", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", quotaTimeout: "Quota timeout", chatTimeout: "Chat timeout", imageTimeout: "Image timeout", videoTimeout: "Video timeout", mediaConcurrency: "Media job concurrency", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffMax: "Maximum recovery backoff", allowNSFW: "Allow NSFW images" }, batch: { title: "Batch tasks", importConcurrency: "Import sync concurrency", conversionConcurrency: "Account conversion concurrency", syncConcurrency: "Data sync concurrency", refreshConcurrency: "Credential refresh concurrency", randomDelay: "Maximum random delay (ms)" }, media: { title: "Media storage", maxImageSize: "Maximum image size", maxTotalSize: "Media storage limit", cleanupThresholdPercent: "Automatic cleanup threshold", cleanupInterval: "Capacity check interval", 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 with optional username and password.", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "Configured; leave blank to keep unchanged", operationFailed: "Operation failed" }, routing: { title: "Routing policy", stickyTTL: "Sticky session TTL", cooldownBase: "Base cooldown", cooldownMax: "Maximum cooldown", maxAttempts: "Maximum attempts" }, audit: { title: "Request audit", bufferSize: "Queue capacity", batchSize: "Batch size", flushInterval: "Flush interval" }, clientKeys: { title: "Client key defaults", rpmLimit: "Default RPM", maxConcurrent: "Default concurrency" }, 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", clientVersion: "Client version", clientIdentifier: "Client identifier", tokenAuth: "Token auth", userAgent: "User-Agent", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync recommended version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill in the backend version and User-Agent that passed compatibility regression; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", statsigMode: "x-statsig source", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", quotaTimeout: "Quota timeout", chatTimeout: "Chat timeout", imageTimeout: "Image timeout", videoTimeout: "Video timeout", mediaConcurrency: "Media job concurrency", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffMax: "Maximum recovery backoff", allowNSFW: "Allow NSFW images" }, batch: { title: "Batch tasks", importConcurrency: "Import sync concurrency", conversionConcurrency: "Account conversion concurrency", syncConcurrency: "Data sync concurrency", refreshConcurrency: "Credential refresh concurrency", randomDelay: "Maximum random delay (ms)" }, media: { title: "Media storage", maxImageSize: "Maximum image size", maxTotalSize: "Media storage limit", cleanupThresholdPercent: "Automatic cleanup threshold", cleanupInterval: "Capacity check interval", 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 with optional username and password.", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "Configured; leave blank to keep unchanged", operationFailed: "Operation failed" }, routing: { title: "Routing policy", stickyTTL: "Sticky session TTL", cooldownBase: "Base cooldown", cooldownMax: "Maximum cooldown", maxAttempts: "Maximum attempts" }, audit: { title: "Request audit", bufferSize: "Queue capacity", batchSize: "Batch size", flushInterval: "Flush interval" }, clientKeys: { title: "Client key defaults", rpmLimit: "Default RPM", maxConcurrent: "Default concurrency" }, units: { seconds: "Seconds", minutes: "Minutes", hours: "Hours", days: "Days" } },
docs: {
title: "API documentation",
description: "OpenAI Responses compatibility, account routing, and conversation-state behavior for this gateway.",