diff --git a/.dockerignore b/.dockerignore index 3cbe7a87..40deb96a 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,5 +1,7 @@ ** +!VERSION + !backend/ !backend/go.mod !backend/go.sum diff --git a/Dockerfile b/Dockerfile index c6899db6..14e3ea41 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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 diff --git a/VERSION b/VERSION index 1c5ae582..5e008de3 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -v3.0.0 \ No newline at end of file +v3.0.1 \ No newline at end of file diff --git a/backend/internal/app/application.go b/backend/internal/app/application.go index 70787d94..935c8885 100644 --- a/backend/internal/app/application.go +++ b/backend/internal/app/application.go @@ -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) diff --git a/backend/internal/application/updatecheck/service.go b/backend/internal/application/updatecheck/service.go new file mode 100644 index 00000000..20eb899a --- /dev/null +++ b/backend/internal/application/updatecheck/service.go @@ -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 +} diff --git a/backend/internal/application/updatecheck/service_test.go b/backend/internal/application/updatecheck/service_test.go new file mode 100644 index 00000000..353cdc4f --- /dev/null +++ b/backend/internal/application/updatecheck/service_test.go @@ -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") + } +} diff --git a/backend/internal/buildinfo/version.go b/backend/internal/buildinfo/version.go new file mode 100644 index 00000000..36543956 --- /dev/null +++ b/backend/internal/buildinfo/version.go @@ -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 +} diff --git a/backend/internal/transport/http/server.go b/backend/internal/transport/http/server.go index 9d831e76..1a1d7570 100644 --- a/backend/internal/transport/http/server.go +++ b/backend/internal/transport/http/server.go @@ -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()) diff --git a/backend/internal/transport/http/server_test.go b/backend/internal/transport/http/server_test.go index 5922dea0..6a08e105 100644 --- a/backend/internal/transport/http/server_test.go +++ b/backend/internal/transport/http/server_test.go @@ -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) + } } } diff --git a/backend/internal/transport/http/system/handler.go b/backend/internal/transport/http/system/handler.go index ca59c133..c2a58c6e 100644 --- a/backend/internal/transport/http/system/handler.go +++ b/backend/internal/transport/http/system/handler.go @@ -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) { diff --git a/backend/internal/transport/http/system/handler_test.go b/backend/internal/transport/http/system/handler_test.go index 25dfd4b9..9ab0bf45 100644 --- a/backend/internal/transport/http/system/handler_test.go +++ b/backend/internal/transport/http/system/handler_test.go @@ -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) + } + } +} diff --git a/frontend/src/app/app-shell.tsx b/frontend/src/app/app-shell.tsx index 7cc442a1..d30d9cac 100644 --- a/frontend/src/app/app-shell.tsx +++ b/frontend/src/app/app-shell.tsx @@ -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() {
+ + + + ) : null} diff --git a/frontend/src/features/system/version-update.tsx b/frontend/src/features/system/version-update.tsx new file mode 100644 index 00000000..1f6e39a3 --- /dev/null +++ b/frontend/src/features/system/version-update.tsx @@ -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 {version}; +} + +export function VersionUpdateBanner() { + const { t } = useTranslation(); + const versionQuery = useVersionInfo(); + const checkMutation = useCheckForUpdates(); + const version = versionQuery.data; + if (!version?.updateAvailable) return null; + + return ( +
+
+

{t("updates.available", { version: version.latestVersion })}

+

{t("updates.currentSummary", { version: version.currentVersion })}

+
+
+ {version.releaseUrl ? ( + + ) : null} + {version.releaseUrl ? : null} + +
+
+ ); +} + +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 ( +
+
+

{t("updates.title")}

+ +
+ +
+ + + + +
+ + {error ?

{error}

: null} + + {version?.releaseNotes || version?.releaseUrl ? ( +
+
+

{t("updates.releaseNotes")}

+ {version.releaseUrl ? ( + + ) : null} +
+

+ {version.releaseNotes || t("updates.noReleaseNotes")} +

+
+ ) : null} + +

{t("updates.manualOnly")}

+
+ ); +} + +function VersionField({ label, value, status }: { label: string; value: string; status?: UpdateStatus }) { + return ( +
+

{label}

+
+ {status ? : null} + {value} +
+
+ ); +} diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index fbf065cc..fe71befb 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -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.",