From b08b702ed36e47f417bb7540c5414707988c19ec Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Tue, 10 Nov 2026 10:49:39 +0900 Subject: [PATCH 1/5] feat: add conservative AI Studio web profile Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- internal/aistudio/auth.go | 29 ++++++++++++ internal/aistudio/conservative_test.go | 30 +++++++++++++ internal/api/conservative_test.go | 26 +++++++++++ internal/api/pairing.go | 17 +++++++ internal/api/pairing_test.go | 2 + internal/app/admin.go | 13 ++++++ internal/app/admin_config_test.go | 9 +++- internal/app/app.go | 3 ++ internal/app/auth_retry.go | 7 ++- internal/app/auth_retry_test.go | 2 + internal/app/conservative_test.go | 17 +++++++ internal/app/lifecycle.go | 4 ++ internal/app/runtime.go | 18 +++++++- internal/app/update.go | 4 ++ internal/buildpolicy/conservative.go | 6 +++ internal/buildpolicy/default.go | 5 +++ internal/camoufoxnative/conservative_test.go | 16 +++++++ internal/camoufoxnative/login.go | 10 ++++- internal/chromeauth/abe_unsupported.go | 2 +- internal/chromeauth/abe_windows_amd64.go | 2 +- internal/chromeauth/cdp.go | 4 ++ internal/chromeauth/conservative_test.go | 29 ++++++++++++ internal/chromeauth/ncrypt_other.go | 2 +- internal/chromeauth/ncrypt_windows.go | 2 +- internal/chromeauth/platform_conservative.go | 18 ++++++++ internal/chromeauth/platform_other.go | 2 +- internal/chromeauth/platform_windows.go | 2 +- internal/chromeauth/platform_windows_test.go | 2 +- internal/config/config.go | 19 +++++++- internal/config/conservative.go | 43 ++++++++++++++++++ internal/config/conservative_test.go | 47 ++++++++++++++++++++ internal/config/env_test.go | 2 + internal/setup/setup.go | 4 ++ web/src/components/AccountsPanel.vue | 4 +- 34 files changed, 388 insertions(+), 14 deletions(-) create mode 100644 internal/aistudio/conservative_test.go create mode 100644 internal/api/conservative_test.go create mode 100644 internal/app/conservative_test.go create mode 100644 internal/buildpolicy/conservative.go create mode 100644 internal/buildpolicy/default.go create mode 100644 internal/camoufoxnative/conservative_test.go create mode 100644 internal/chromeauth/conservative_test.go create mode 100644 internal/chromeauth/platform_conservative.go create mode 100644 internal/config/conservative.go create mode 100644 internal/config/conservative_test.go diff --git a/internal/aistudio/auth.go b/internal/aistudio/auth.go index 2b10775d..8f7b1cde 100644 --- a/internal/aistudio/auth.go +++ b/internal/aistudio/auth.go @@ -13,6 +13,7 @@ import ( "strings" "time" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" "github.com/Mag1cFall/AIStudio2API/internal/camoufoxnative" ) @@ -198,6 +199,15 @@ func WriteStorageState(filePath string, state StorageState) error { // Validate 校验 storage state 的浏览器字段 func (s StorageState) Validate() error { + if buildpolicy.Conservative { + extension, exists, err := s.AuthExtension() + if err != nil { + return err + } + if exists && (extension.OAuth != nil || extension.Bound != nil) { + return fmt.Errorf("Chrome OAuth and device-bound renewal material are disabled in the conservative trial") + } + } for index, cookie := range s.Cookies { if strings.TrimSpace(cookie.Name) == "" || strings.TrimSpace(cookie.Domain) == "" { return fmt.Errorf("storage state Cookie %d 缺少名称或域", index) @@ -220,6 +230,25 @@ func (s StorageState) Validate() error { return nil } +// ValidateRuntimeState rejects copied states at the live service boundary while +// allowing generic parsers and fixtures to validate their storage shape. +func ValidateRuntimeState(s StorageState) error { + if !buildpolicy.Conservative { + return nil + } + extension, exists, err := s.AuthExtension() + if err != nil { + return err + } + if !exists || extension.Source.Browser != "camoufox" { + return fmt.Errorf("this trial requires state created by sign-in in its runtime browser") + } + if extension.OAuth != nil || extension.Bound != nil { + return fmt.Errorf("Chrome OAuth and device-bound renewal material are disabled in the conservative trial") + } + return nil +} + // CookieHeader 为目标 URL 构造当前有效的 Cookie 请求头 func (s StorageState) CookieHeader(targetURL string, now time.Time) (string, error) { target, err := url.Parse(targetURL) diff --git a/internal/aistudio/conservative_test.go b/internal/aistudio/conservative_test.go new file mode 100644 index 00000000..4aad5bb2 --- /dev/null +++ b/internal/aistudio/conservative_test.go @@ -0,0 +1,30 @@ +//go:build conservative + +package aistudio + +import "testing" + +func TestConservativeAllowsBrowserLoginStateOnlyWithoutRenewalKeys(t *testing.T) { + state := StorageState{Cookies: []StateCookie{{Name: "fixture", Value: "fixture", Domain: ".google.com", Path: "/"}}} + if err := state.Validate(); err != nil { + t.Fatal(err) + } + if err := ValidateRuntimeState(state); err == nil { + t.Fatal("copied cookies accepted at runtime") + } + state.SetAuthExtension(AuthExtension{Source: AuthSource{Browser: "camoufox", Email: "fixture@example.invalid"}}) + if err := state.Validate(); err != nil { + t.Fatal(err) + } + if err := ValidateRuntimeState(state); err != nil { + t.Fatal(err) + } + state.SetAuthExtension(AuthExtension{Source: AuthSource{Browser: "camoufox"}, OAuth: &ChromeOAuthMaterial{RefreshToken: "fixture"}}) + if err := state.Validate(); err == nil { + t.Fatal("OAuth material accepted") + } + state.SetAuthExtension(AuthExtension{Source: AuthSource{Browser: "camoufox"}, Bound: &BoundSession{ID: "fixture"}}) + if err := state.Validate(); err == nil { + t.Fatal("bound renewal accepted") + } +} diff --git a/internal/api/conservative_test.go b/internal/api/conservative_test.go new file mode 100644 index 00000000..4e836c57 --- /dev/null +++ b/internal/api/conservative_test.go @@ -0,0 +1,26 @@ +//go:build conservative + +package api + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestConservativeRejectsPairing(t *testing.T) { + handler := NewHandler(nil, Config{}) + for _, request := range []*http.Request{ + httptest.NewRequest(http.MethodPost, "/api/pairing", nil), + httptest.NewRequest(http.MethodGet, "/api/pairing", nil), + httptest.NewRequest(http.MethodPost, "/api/pairing/accounts", strings.NewReader(`{}`)), + httptest.NewRequest(http.MethodPut, "/api/pairing/accounts/account/cookies", strings.NewReader(`{}`)), + } { + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request) + if recorder.Code != http.StatusForbidden { + t.Fatalf("%s %s = %d", request.Method, request.URL.Path, recorder.Code) + } + } +} diff --git a/internal/api/pairing.go b/internal/api/pairing.go index 27525885..a1262857 100644 --- a/internal/api/pairing.go +++ b/internal/api/pairing.go @@ -10,6 +10,7 @@ import ( "time" "github.com/Mag1cFall/AIStudio2API/internal/aistudio" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" ) // pairingTokenLifetime 是远程配对令牌的有效期 @@ -74,6 +75,10 @@ func (tokens *pairingTokens) valid(token string, now time.Time) bool { // handleActivePairing 返回仍在有效期内的远程配对令牌,没有时返回 404 func (s *server) handleActivePairing(w http.ResponseWriter, _ *http.Request) { + if buildpolicy.Conservative { + writeAdminError(w, http.StatusForbidden, "conservative_trial", "Remote pairing is disabled") + return + } token, ok := s.pairing.active(time.Now()) if !ok { writeAdminError(w, http.StatusNotFound, "pairing_token_missing", "No active pairing token") @@ -84,11 +89,19 @@ func (s *server) handleActivePairing(w http.ResponseWriter, _ *http.Request) { // handleCreatePairing 生成远程配对令牌 func (s *server) handleCreatePairing(w http.ResponseWriter, _ *http.Request) { + if buildpolicy.Conservative { + writeAdminError(w, http.StatusForbidden, "conservative_trial", "Remote pairing is disabled") + return + } writeJSON(w, http.StatusCreated, s.pairing.issue(time.Now())) } // handlePairingAccount 凭配对令牌导入一个账户,不经过管理会话 func (s *server) handlePairingAccount(w http.ResponseWriter, r *http.Request) { + if buildpolicy.Conservative { + writeAdminError(w, http.StatusForbidden, "conservative_trial", "Remote pairing is disabled") + return + } w.Header().Set("Cache-Control", "no-store") token, _ := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") if !s.pairing.valid(strings.TrimSpace(token), time.Now()) { @@ -112,6 +125,10 @@ func (s *server) handlePairingAccount(w http.ResponseWriter, r *http.Request) { // handlePairingRenewal 凭配对上传时签发的续签凭据替换该账户的会话 Cookie,不经过管理会话 func (s *server) handlePairingRenewal(w http.ResponseWriter, r *http.Request) { + if buildpolicy.Conservative { + writeAdminError(w, http.StatusForbidden, "conservative_trial", "Remote renewal is disabled") + return + } w.Header().Set("Cache-Control", "no-store") token, _ := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") r.Body = http.MaxBytesReader(w, r.Body, 1<<20) diff --git a/internal/api/pairing_test.go b/internal/api/pairing_test.go index 2a0cabd8..c37450b5 100644 --- a/internal/api/pairing_test.go +++ b/internal/api/pairing_test.go @@ -1,3 +1,5 @@ +//go:build !conservative + package api import ( diff --git a/internal/app/admin.go b/internal/app/admin.go index 70427974..075fd1d4 100644 --- a/internal/app/admin.go +++ b/internal/app/admin.go @@ -16,6 +16,7 @@ import ( "github.com/Mag1cFall/AIStudio2API/internal/aistudio" "github.com/Mag1cFall/AIStudio2API/internal/api" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" "github.com/Mag1cFall/AIStudio2API/internal/camoufoxnative" "github.com/Mag1cFall/AIStudio2API/internal/chromeauth" "github.com/Mag1cFall/AIStudio2API/internal/config" @@ -217,6 +218,9 @@ func (admin *runtimeAdmin) ChromeImportProfiles(context.Context) ([]api.ChromeIm // CookieBrowsers 列出本机开启远程调试的浏览器,读取其 Cookie 并经 proxy 识别其中各会话登录 AI Studio 的账户,每个账户一项,proxy 为空时用默认出口 func (admin *runtimeAdmin) CookieBrowsers(ctx context.Context, proxy string) ([]api.CookieBrowser, error) { + if buildpolicy.Conservative { + return nil, invalidAccount(fmt.Errorf("browser discovery is disabled; sign in in the runtime browser")) + } addresses, err := chromeauth.DebugAddresses(ctx) if err != nil { return nil, err @@ -263,6 +267,9 @@ func (admin *runtimeAdmin) readCookieBrowser(ctx context.Context, browser *api.C // DiscoverCookieAccounts 解析粘贴的 Cookie,返回其中各会话登录 AI Studio 的账户 func (admin *runtimeAdmin) DiscoverCookieAccounts(ctx context.Context, input api.CookieImportInput) ([]api.CookieBrowser, error) { + if buildpolicy.Conservative { + return nil, invalidAccount(fmt.Errorf("cross-browser cookie import is disabled; sign in in the runtime browser")) + } state, err := aistudio.ParseCookieText(input.Cookies) if err != nil { return nil, &adminOperationError{status: http.StatusBadRequest, code: "invalid_cookies", message: err.Error()} @@ -368,6 +375,9 @@ func (admin *runtimeAdmin) ImportChromeAccounts(ctx context.Context, input api.C // ImportAccountState 导入远程配对上传或 Cookie 导入的认证状态与 Camoufox 指纹,未给标签时以 Cookie 中第 auth_user 个会话登录的账户邮箱为标签 func (admin *runtimeAdmin) ImportAccountState(ctx context.Context, input api.AccountStateInput) (api.AdminAccount, error) { + if buildpolicy.Conservative { + return api.AdminAccount{}, invalidAccount(fmt.Errorf("external state import is disabled; sign in in the runtime browser")) + } timezone, err := accountTimezone(input.Timezone) if err != nil { return api.AdminAccount{}, invalidAccount(err) @@ -1111,6 +1121,9 @@ func (admin *runtimeAdmin) UpdateRuntimeConfig(_ context.Context, value api.Runt if err := cfg.Validate(); err != nil { return api.RuntimeConfig{}, invalidConfigError(err) } + if err := config.ValidateRuntimePolicy(cfg); err != nil { + return api.RuntimeConfig{}, invalidConfigError(err) + } if err := cfg.Save(admin.configPath); err != nil { return api.RuntimeConfig{}, err } diff --git a/internal/app/admin_config_test.go b/internal/app/admin_config_test.go index fb709a3f..3313a7b1 100644 --- a/internal/app/admin_config_test.go +++ b/internal/app/admin_config_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/Mag1cFall/AIStudio2API/internal/aistudio" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" "github.com/Mag1cFall/AIStudio2API/internal/config" ) @@ -20,6 +21,7 @@ func TestAdminConfig(t *testing.T) { cfg.AdminAuthEnabled = true cfg.AdminUsername = "operator" cfg.AdminPassword = "test-password" + cfg.ProxyAPIKey = "fixture-key" if err := cfg.Save(path); err != nil { t.Fatal(err) } @@ -68,7 +70,12 @@ func TestAdminConfig(t *testing.T) { t.Fatalf("empty enabled password error = %v", err) } value.AdminAuthEnabled = false - if _, err := admin.UpdateRuntimeConfig(ctx, value); err != nil { + _, err = admin.UpdateRuntimeConfig(ctx, value) + if buildpolicy.Conservative { + if !errors.As(err, &status) || status.HTTPStatus() != http.StatusBadRequest { + t.Fatalf("disabled conservative admin auth error = %v", err) + } + } else if err != nil { t.Fatal(err) } } diff --git a/internal/app/app.go b/internal/app/app.go index 969cbc22..262e1575 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -201,6 +201,9 @@ func parseFlags(args []string, cfg *config.Config) (commandOptions, error) { if err := cfg.Validate(); err != nil { return commandOptions{}, err } + if err := config.ValidateRuntimePolicy(*cfg); err != nil { + return commandOptions{}, err + } options := commandOptions{openUI: *openUI} flags.Visit(func(value *flag.Flag) { switch value.Name { diff --git a/internal/app/auth_retry.go b/internal/app/auth_retry.go index c873493f..11146fda 100644 --- a/internal/app/auth_retry.go +++ b/internal/app/auth_retry.go @@ -12,6 +12,7 @@ import ( "github.com/Mag1cFall/AIStudio2API/internal/aistudio" "github.com/Mag1cFall/AIStudio2API/internal/api" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" "github.com/Mag1cFall/AIStudio2API/internal/camoufoxnative" "github.com/Mag1cFall/AIStudio2API/internal/chromeauth" ) @@ -274,7 +275,7 @@ func (refresher *authRuntimeRefresher) do(ctx context.Context, method string, se if !aistudio.DefinitiveAuthenticationFailure(err) { return response, err } - if attempt == 1 { + if !authenticationRecoveryAllowed(attempt) { return nil, refresher.markAuthenticationRequired(ctx, err) } if err := refresher.Recover(ctx, err, generation); err != nil { @@ -283,6 +284,10 @@ func (refresher *authRuntimeRefresher) do(ctx context.Context, method string, se } } +func authenticationRecoveryAllowed(attempt int) bool { + return !buildpolicy.Conservative && attempt < 1 +} + // Do 在 401 后续签同一账户并重放一次请求 func (transport *authRetryTransport) Do(ctx context.Context, request aistudio.RPCRequest) (*aistudio.RPCResponse, error) { return transport.refresher.do(ctx, request.Method, func() (*aistudio.RPCResponse, error) { diff --git a/internal/app/auth_retry_test.go b/internal/app/auth_retry_test.go index 610ada1e..9087e104 100644 --- a/internal/app/auth_retry_test.go +++ b/internal/app/auth_retry_test.go @@ -1,3 +1,5 @@ +//go:build !conservative + package app import ( diff --git a/internal/app/conservative_test.go b/internal/app/conservative_test.go new file mode 100644 index 00000000..25b7ec42 --- /dev/null +++ b/internal/app/conservative_test.go @@ -0,0 +1,17 @@ +//go:build conservative + +package app + +import "testing" + +func TestConservativeDoesNotRecoverOrRegenerate(t *testing.T) { + if authenticationRecoveryAllowed(0) { + t.Fatal("authentication recovery enabled") + } + if !generationAttemptAllowed(0) { + t.Fatal("first generation disabled") + } + if generationAttemptAllowed(1) { + t.Fatal("automatic generation retry enabled") + } +} diff --git a/internal/app/lifecycle.go b/internal/app/lifecycle.go index 9b3c715c..efadddbb 100644 --- a/internal/app/lifecycle.go +++ b/internal/app/lifecycle.go @@ -186,6 +186,10 @@ func (manager *runtimeManager) startService(ctx context.Context) (api.AdminStatu manager.finishStart(launchCancel) return api.AdminStatus{}, err } + if err := config.ValidateRuntimePolicy(cfg); err != nil { + manager.finishStart(launchCancel) + return api.AdminStatus{}, err + } next, err := manager.factory(launchCtx, manager.lifecycle, cfg, manager.requests) if err != nil { diff --git a/internal/app/runtime.go b/internal/app/runtime.go index 35bedcf1..3cff0b29 100644 --- a/internal/app/runtime.go +++ b/internal/app/runtime.go @@ -17,6 +17,7 @@ import ( "github.com/Mag1cFall/AIStudio2API/internal/aistudio" "github.com/Mag1cFall/AIStudio2API/internal/api" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" "github.com/Mag1cFall/AIStudio2API/internal/config" ) @@ -37,6 +38,11 @@ func newRuntime( if err != nil { return nil, nil, nil, err } + for _, account := range accounts { + if err := aistudio.ValidateRuntimeState(account.StorageState); err != nil { + return nil, nil, nil, fmt.Errorf("account %s: %w", account.ID, err) + } + } if err := launchCtx.Err(); err != nil { return nil, nil, nil, err } @@ -838,6 +844,9 @@ func (service *trackedService) syncAccountModels(ctx context.Context, accountID // retryModelCatalogs 每 30 秒重新载入待同步账户的页面重试目录,自 startedAt 起每 24 小时重新载入启用账户的页面读取权益与目录;闲置的写代码助手应用与到期资源在启动时与每 10 分钟删除 func (service *trackedService) retryModelCatalogs(ctx context.Context, startedAt time.Time) { + if buildpolicy.Conservative { + return + } var patrol sync.WaitGroup defer patrol.Wait() patrol.Go(func() { service.patrolAccountStates(ctx, startedAt) }) @@ -1819,7 +1828,7 @@ func (service *trackedService) generateWithRetry( var activity *upstreamActivity var err error copyFiles := false - for attempt := 0; attempt < retry.maxAttempts; attempt++ { + for attempt := 0; attempt < retry.maxAttempts && generationAttemptAllowed(attempt); attempt++ { selectionAccountID := requestedAccountID recoveringAccount := retry.recoveryAccountID != "" if retry.recoveryAccountID != "" { @@ -2029,6 +2038,10 @@ func (service *trackedService) generateWithRetry( ) } +func generationAttemptAllowed(attempt int) bool { + return !buildpolicy.Conservative || attempt == 0 +} + // markAttemptAccount 把访问日志与活动请求的执行账户与通道记为该租约 func (service *trackedService) markAttemptAccount(requestCtx context.Context, requestID, modelID string, lease *aistudio.AccountLease) { label := lease.Account().Config.Label @@ -2277,6 +2290,9 @@ func (service *trackedService) settleAttempt( retry *generateRetry, mayRecover bool, ) attemptOutcome { + if buildpolicy.Conservative { + mayRecover = false + } err := attempt.err lease := attempt.serving.Load() accountID, accountLabel := lease.Account().ID, lease.Account().Config.Label diff --git a/internal/app/update.go b/internal/app/update.go index 047e187c..2822e61f 100644 --- a/internal/app/update.go +++ b/internal/app/update.go @@ -29,6 +29,7 @@ import ( "golang.org/x/mod/semver" "github.com/Mag1cFall/AIStudio2API/internal/api" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" ) // releaseAPI 为 GitHub 最新发行版本接口 @@ -88,6 +89,9 @@ func newSelfUpdater(version, executable string, proxy func() string, log func(le // updateMode 返回更新方式:managed 由分发方更新,binary 可原地替换,container 随镜像更新,development 为源码构建 func updateMode(version string) string { + if buildpolicy.Conservative { + return "development" + } if managedBy != "" { return "managed" } diff --git a/internal/buildpolicy/conservative.go b/internal/buildpolicy/conservative.go new file mode 100644 index 00000000..4a746b01 --- /dev/null +++ b/internal/buildpolicy/conservative.go @@ -0,0 +1,6 @@ +//go:build conservative + +package buildpolicy + +// Conservative is a local trial profile, not an upstream release policy. +const Conservative = true diff --git a/internal/buildpolicy/default.go b/internal/buildpolicy/default.go new file mode 100644 index 00000000..8d0c908a --- /dev/null +++ b/internal/buildpolicy/default.go @@ -0,0 +1,5 @@ +//go:build !conservative + +package buildpolicy + +const Conservative = false diff --git a/internal/camoufoxnative/conservative_test.go b/internal/camoufoxnative/conservative_test.go new file mode 100644 index 00000000..3c0ab897 --- /dev/null +++ b/internal/camoufoxnative/conservative_test.go @@ -0,0 +1,16 @@ +//go:build conservative + +package camoufoxnative + +import ( + "context" + "testing" +) + +func TestConservativeSkipsDriveConsent(t *testing.T) { + called := false + err := optionalDriveAuthorization(context.Background(), "fixture@example.invalid", func(context.Context, string) error { called = true; return nil }) + if err != nil || called { + t.Fatalf("unexpected authorization: called=%v err=%v", called, err) + } +} diff --git a/internal/camoufoxnative/login.go b/internal/camoufoxnative/login.go index 41dc679d..c7cc37a2 100644 --- a/internal/camoufoxnative/login.go +++ b/internal/camoufoxnative/login.go @@ -14,6 +14,7 @@ import ( "strings" "time" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" "github.com/gorilla/websocket" ) @@ -100,7 +101,7 @@ func Login(ctx context.Context, options LoginOptions) (result LoginResult, err e if email == "" { return LoginResult{}, errors.New("AI Studio 页面没有登录邮箱") } - driveErr := session.authorizeDrive(loginCtx, email) + driveErr := optionalDriveAuthorization(loginCtx, email, session.authorizeDrive) if err := loginCtx.Err(); err != nil { return LoginResult{}, err } @@ -129,6 +130,13 @@ func errorText(err error) string { return err.Error() } +func optionalDriveAuthorization(ctx context.Context, email string, authorize func(context.Context, string) error) error { + if buildpolicy.Conservative { + return nil + } + return authorize(ctx, email) +} + func startLoginSession(ctx context.Context, options LoginOptions, state storageState) (*loginSession, error) { ffVersion := camoufoxFirefoxMajor fingerprintPath := filepath.Join(options.Directory, "storage-state.json") diff --git a/internal/chromeauth/abe_unsupported.go b/internal/chromeauth/abe_unsupported.go index 6f93c0aa..6487e2a1 100644 --- a/internal/chromeauth/abe_unsupported.go +++ b/internal/chromeauth/abe_unsupported.go @@ -1,4 +1,4 @@ -//go:build !windows || !amd64 +//go:build (!windows || !amd64) && !conservative package chromeauth diff --git a/internal/chromeauth/abe_windows_amd64.go b/internal/chromeauth/abe_windows_amd64.go index 4657254a..87cbd552 100644 --- a/internal/chromeauth/abe_windows_amd64.go +++ b/internal/chromeauth/abe_windows_amd64.go @@ -1,4 +1,4 @@ -//go:build windows && amd64 +//go:build windows && amd64 && !conservative package chromeauth diff --git a/internal/chromeauth/cdp.go b/internal/chromeauth/cdp.go index 96601d54..27eb4e62 100644 --- a/internal/chromeauth/cdp.go +++ b/internal/chromeauth/cdp.go @@ -11,6 +11,7 @@ import ( "slices" "strings" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" "github.com/gorilla/websocket" ) @@ -23,6 +24,9 @@ type CDPBrowser struct { // ReadCDPBrowser 经 Chromium 远程调试地址读取浏览器全部未分区 Cookie,并在第一个页面中读取 navigator.language 与 Intl 时区,没有页面时语言与时区为空 func ReadCDPBrowser(ctx context.Context, address string) (CDPBrowser, error) { + if buildpolicy.Conservative { + return CDPBrowser{}, fmt.Errorf("browser cookie extraction is disabled in the conservative trial") + } endpoint, err := cdpBrowserEndpoint(ctx, address) if err != nil { return CDPBrowser{}, err diff --git a/internal/chromeauth/conservative_test.go b/internal/chromeauth/conservative_test.go new file mode 100644 index 00000000..750da387 --- /dev/null +++ b/internal/chromeauth/conservative_test.go @@ -0,0 +1,29 @@ +//go:build conservative + +package chromeauth + +import ( + "context" + "testing" +) + +func TestConservativeRejectsCredentialAccess(t *testing.T) { + if Supported { + t.Fatal("Chrome import advertised") + } + if _, err := DefaultChromeRoot(); err == nil { + t.Fatal("profile lookup enabled") + } + if _, err := Discover("must-not-be-read"); err == nil { + t.Fatal("discovery enabled") + } + if _, err := retrieveV20Key("must-not-be-read"); err == nil { + t.Fatal("ABE access enabled") + } + if _, err := openDeviceBindingKey([]byte("fixture")); err == nil { + t.Fatal("device key access enabled") + } + if _, err := ReadCDPBrowser(context.Background(), "http://127.0.0.1:1"); err == nil { + t.Fatal("CDP cookie import enabled") + } +} diff --git a/internal/chromeauth/ncrypt_other.go b/internal/chromeauth/ncrypt_other.go index 6f9e1607..f992f8a3 100644 --- a/internal/chromeauth/ncrypt_other.go +++ b/internal/chromeauth/ncrypt_other.go @@ -1,4 +1,4 @@ -//go:build !windows +//go:build !windows && !conservative package chromeauth diff --git a/internal/chromeauth/ncrypt_windows.go b/internal/chromeauth/ncrypt_windows.go index 33ab2673..f870e340 100644 --- a/internal/chromeauth/ncrypt_windows.go +++ b/internal/chromeauth/ncrypt_windows.go @@ -1,4 +1,4 @@ -//go:build windows +//go:build windows && !conservative package chromeauth diff --git a/internal/chromeauth/platform_conservative.go b/internal/chromeauth/platform_conservative.go new file mode 100644 index 00000000..3e00adf2 --- /dev/null +++ b/internal/chromeauth/platform_conservative.go @@ -0,0 +1,18 @@ +//go:build conservative + +package chromeauth + +import "errors" + +const Supported = false + +var errConservative = errors.New("this trial requires login in its own browser; Chrome profile/key extraction and OAuth recovery are disabled") + +func DefaultChromeRoot() (string, error) { return "", errConservative } +func ensurePlatformImport() error { return errConservative } +func Discover(string) ([]Account, error) { return nil, errConservative } +func readTokenService(string, string, string) (string, []byte, []byte, error) { + return "", nil, nil, errConservative +} +func retrieveV20Key(string) ([]byte, error) { return nil, errConservative } +func openDeviceBindingKey([]byte) (deviceBindingKey, error) { return nil, errConservative } diff --git a/internal/chromeauth/platform_other.go b/internal/chromeauth/platform_other.go index aeec9b15..552c5d3d 100644 --- a/internal/chromeauth/platform_other.go +++ b/internal/chromeauth/platform_other.go @@ -1,4 +1,4 @@ -//go:build !windows +//go:build !windows && !conservative package chromeauth diff --git a/internal/chromeauth/platform_windows.go b/internal/chromeauth/platform_windows.go index 0861af92..949f84f2 100644 --- a/internal/chromeauth/platform_windows.go +++ b/internal/chromeauth/platform_windows.go @@ -1,4 +1,4 @@ -//go:build windows +//go:build windows && !conservative package chromeauth diff --git a/internal/chromeauth/platform_windows_test.go b/internal/chromeauth/platform_windows_test.go index 0b37752b..02319049 100644 --- a/internal/chromeauth/platform_windows_test.go +++ b/internal/chromeauth/platform_windows_test.go @@ -1,4 +1,4 @@ -//go:build windows +//go:build windows && !conservative package chromeauth diff --git a/internal/config/config.go b/internal/config/config.go index 77e3ee1d..bf122946 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -4,6 +4,7 @@ import ( "bufio" "bytes" "fmt" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" "net" "net/url" "os" @@ -158,7 +159,7 @@ var workerDefaultKeys = []string{"WARM_WORKER_LIMIT", "MAX_ACTIVE_WORKERS"} // defaultsFor 返回 WAA 后端为 backend 时的默认配置,Camoufox 后端的常驻预热账户数与活动 Worker 上限较小 func defaultsFor(backend string) Config { cfg := Default() - if backend == WAABackendCamoufox { + if backend == WAABackendCamoufox && !buildpolicy.Conservative { cfg.WarmWorkerLimit, cfg.MaxActiveWorkers = camoufoxWarmWorkerLimit, camoufoxMaxActiveWorkers } return cfg @@ -166,7 +167,7 @@ func defaultsFor(backend string) Config { // Default 返回可直接启动的默认配置 func Default() Config { - return Config{ + cfg := Config{ AdminUsername: "admin", LogFile: true, LogMaxTotalMB: 500, @@ -191,6 +192,17 @@ func Default() Config { WAABackend: WAABackendSpiderMonkey, MediaOutput: MediaOutputInline, } + if buildpolicy.Conservative { + cfg.AdminAuthEnabled = true + cfg.WAABackend = WAABackendCamoufox + cfg.FirstEventHedge = FirstEventHedgeOff + cfg.PerAccountConcurrency, cfg.WarmStartupConcurrency = 1, 1 + cfg.WarmWorkerLimit, cfg.MaxActiveWorkers = 1, 1 + cfg.SearchModelAliases, cfg.ContinuationRewrite = false, false + cfg.LogMaxTotalMB = 20 + cfg.RoutingStrategy = "fill-first" + } + return cfg } // InvalidValue 是加载时取值无效、改用默认值的配置项 @@ -664,6 +676,9 @@ func appendEnv(path, key, value string) error { // Validate 校验配置值是否能用于服务启动 func (c Config) Validate() error { + if err := validateConservative(c); err != nil { + return err + } if c.AdminAuthEnabled && (strings.TrimSpace(c.AdminUsername) == "" || strings.TrimSpace(c.AdminPassword) == "") { return fmt.Errorf("开启管理登录需要 ADMIN_USERNAME 与 ADMIN_PASSWORD") } diff --git a/internal/config/conservative.go b/internal/config/conservative.go new file mode 100644 index 00000000..57f0db79 --- /dev/null +++ b/internal/config/conservative.go @@ -0,0 +1,43 @@ +package config + +import ( + "fmt" + "net" + "strings" + + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" +) + +func validateConservative(c Config) error { + if !buildpolicy.Conservative { + return nil + } + for _, address := range []string{c.ListenAddr, c.PreviewListenAddr} { + host, _, err := net.SplitHostPort(address) + if err != nil || net.ParseIP(host) == nil || !net.ParseIP(host).IsLoopback() { + return fmt.Errorf("conservative trial requires literal loopback listeners") + } + } + if !c.AdminAuthEnabled || strings.TrimSpace(c.AdminPassword) == "" { + return fmt.Errorf("conservative trial requires separate management authentication") + } + if c.WAABackend != WAABackendCamoufox || c.FirstEventHedge != FirstEventHedgeOff || c.PerAccountConcurrency != 1 || c.MaxActiveWorkers != 1 || c.WarmStartupConcurrency != 1 || c.WarmWorkerLimit > 1 { + return fmt.Errorf("conservative trial requires one browser worker, one concurrent request and no hedging") + } + if c.RequestBodyLog || c.FakeStream || c.StripThoughtSignatures || c.ContinuationRewrite || len(c.UpstreamChannels) != 1 || c.UpstreamChannels[0] != "playground" { + return fmt.Errorf("conservative trial requires native Playground responses and disabled body logging") + } + return nil +} + +// ValidateRuntimePolicy covers the credential-independent Config structure and +// the secret that must be present before the local service can start or persist. +func ValidateRuntimePolicy(c Config) error { + if err := validateConservative(c); err != nil { + return err + } + if buildpolicy.Conservative && strings.TrimSpace(c.ProxyAPIKey) == "" { + return fmt.Errorf("conservative trial requires a local API key") + } + return nil +} diff --git a/internal/config/conservative_test.go b/internal/config/conservative_test.go new file mode 100644 index 00000000..444f8ef8 --- /dev/null +++ b/internal/config/conservative_test.go @@ -0,0 +1,47 @@ +//go:build conservative + +package config + +import "testing" + +func TestConservativeConfiguration(t *testing.T) { + base := Default() + base.ProxyAPIKey = "fixture" + base.AdminPassword = "separate-management-secret" + if err := base.Validate(); err != nil { + t.Fatal(err) + } + if err := ValidateRuntimePolicy(base); err != nil { + t.Fatal(err) + } + for name, change := range map[string]func(*Config){ + "public": func(c *Config) { c.ListenAddr = "0.0.0.0:2048" }, + "preview": func(c *Config) { c.PreviewListenAddr = "0.0.0.0:2050" }, + "adminAuth": func(c *Config) { c.AdminAuthEnabled = false }, + "adminSecret": func(c *Config) { c.AdminPassword = "" }, + "hedge": func(c *Config) { c.FirstEventHedge = "auto" }, + "concurrency": func(c *Config) { c.PerAccountConcurrency = 2 }, + "workers": func(c *Config) { c.MaxActiveWorkers = 2 }, + "emulation": func(c *Config) { c.WAABackend = WAABackendSpiderMonkey }, + "bodylog": func(c *Config) { c.RequestBodyLog = true }, + "fakeStream": func(c *Config) { c.FakeStream = true }, + "signatures": func(c *Config) { c.StripThoughtSignatures = true }, + "rewrite": func(c *Config) { c.ContinuationRewrite = true }, + "build": func(c *Config) { c.UpstreamChannels = []string{"build"} }, + } { + t.Run(name, func(t *testing.T) { + cfg := base + change(&cfg) + if err := ValidateRuntimePolicy(cfg); err == nil { + t.Fatal("restriction not enforced") + } + }) + } + base.ProxyAPIKey = "" + if err := base.Validate(); err != nil { + t.Fatal(err) + } + if err := ValidateRuntimePolicy(base); err == nil { + t.Fatal("empty API key accepted at runtime") + } +} diff --git a/internal/config/env_test.go b/internal/config/env_test.go index b7a1e511..870f203f 100644 --- a/internal/config/env_test.go +++ b/internal/config/env_test.go @@ -1,3 +1,5 @@ +//go:build !conservative + package config import ( diff --git a/internal/setup/setup.go b/internal/setup/setup.go index 9f547ad6..38c2bc5f 100644 --- a/internal/setup/setup.go +++ b/internal/setup/setup.go @@ -20,6 +20,7 @@ import ( "github.com/Mag1cFall/AIStudio2API/internal/aistudio" "github.com/Mag1cFall/AIStudio2API/internal/api" + "github.com/Mag1cFall/AIStudio2API/internal/buildpolicy" "github.com/Mag1cFall/AIStudio2API/internal/camoufoxnative" "github.com/Mag1cFall/AIStudio2API/internal/chromeauth" "github.com/Mag1cFall/AIStudio2API/internal/config" @@ -73,6 +74,9 @@ func Run(ctx context.Context, cfg config.Config, args []string) error { if err != nil { return err } + if buildpolicy.Conservative && (!options.login || options.remote != "" || options.renew) { + return fmt.Errorf("conservative trial supports only local setup --login; browser extraction, cookie copying and remote renewal are disabled") + } client := &http.Client{Timeout: cfg.RequestTimeout, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} diff --git a/web/src/components/AccountsPanel.vue b/web/src/components/AccountsPanel.vue index d06420a8..534241da 100644 --- a/web/src/components/AccountsPanel.vue +++ b/web/src/components/AccountsPanel.vue @@ -743,6 +743,8 @@ async function importBrowserAccounts(): Promise { } } +const conservativeTrial = import.meta.env.VITE_CONSERVATIVE === '1' + // addMethods 是“添加账户”菜单中的导入方式,顺序按常用程度;服务所在平台不能从 Chrome 导入时该项不可选并说明原因 const addMethods = computed< { @@ -990,7 +992,7 @@ async function refreshAccounts(accounts: Account[]): Promise { class="z-[60] max-h-[var(--reka-dropdown-menu-content-available-height)] w-72 max-w-[calc(100vw-2rem)] overflow-y-auto rounded-lg border border-line bg-panel p-1 shadow-xl" > Date: Tue, 10 Nov 2026 14:26:33 +0900 Subject: [PATCH 2/5] fix: allow conservative quota account fallback --- internal/app/conservative_test.go | 11 +++++++---- internal/app/runtime.go | 6 +++--- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/internal/app/conservative_test.go b/internal/app/conservative_test.go index 25b7ec42..aceea69e 100644 --- a/internal/app/conservative_test.go +++ b/internal/app/conservative_test.go @@ -4,14 +4,17 @@ package app import "testing" -func TestConservativeDoesNotRecoverOrRegenerate(t *testing.T) { +func TestConservativeAllowsOnlyQuotaAccountFallback(t *testing.T) { if authenticationRecoveryAllowed(0) { t.Fatal("authentication recovery enabled") } - if !generationAttemptAllowed(0) { + if !generationAttemptAllowed(0, false) { t.Fatal("first generation disabled") } - if generationAttemptAllowed(1) { - t.Fatal("automatic generation retry enabled") + if generationAttemptAllowed(1, false) { + t.Fatal("non-quota automatic generation retry enabled") + } + if !generationAttemptAllowed(1, true) { + t.Fatal("quota account fallback disabled") } } diff --git a/internal/app/runtime.go b/internal/app/runtime.go index 3cff0b29..0a2db065 100644 --- a/internal/app/runtime.go +++ b/internal/app/runtime.go @@ -1828,7 +1828,7 @@ func (service *trackedService) generateWithRetry( var activity *upstreamActivity var err error copyFiles := false - for attempt := 0; attempt < retry.maxAttempts && generationAttemptAllowed(attempt); attempt++ { + for attempt := 0; attempt < retry.maxAttempts && generationAttemptAllowed(attempt, retry.quotaRejected); attempt++ { selectionAccountID := requestedAccountID recoveringAccount := retry.recoveryAccountID != "" if retry.recoveryAccountID != "" { @@ -2038,8 +2038,8 @@ func (service *trackedService) generateWithRetry( ) } -func generationAttemptAllowed(attempt int) bool { - return !buildpolicy.Conservative || attempt == 0 +func generationAttemptAllowed(attempt int, quotaRejected bool) bool { + return !buildpolicy.Conservative || attempt == 0 || quotaRejected } // markAttemptAccount 把访问日志与活动请求的执行账户与通道记为该租约 From 812fd5dd15b8c1c9d75724909324802b702dccf9 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Tue, 17 Nov 2026 16:34:50 +0900 Subject: [PATCH 3/5] fix: retain conservative maintenance and bound quota retries Restore resource cleanup and pending catalog retries while keeping account patrol disabled. Decide conservative replay from the latest plan/daily quota rejection, removing the stale quotaRejected reference. Report invalid worker setting keys and cover offline maintenance/cancellation behavior. --- internal/app/conservative_maintenance_test.go | 90 +++++++++++++++++++ internal/app/conservative_test.go | 38 ++++++-- internal/app/runtime.go | 19 ++-- internal/config/conservative.go | 15 +++- internal/config/conservative_test.go | 27 +++++- 5 files changed, 173 insertions(+), 16 deletions(-) create mode 100644 internal/app/conservative_maintenance_test.go diff --git a/internal/app/conservative_maintenance_test.go b/internal/app/conservative_maintenance_test.go new file mode 100644 index 00000000..c7c84580 --- /dev/null +++ b/internal/app/conservative_maintenance_test.go @@ -0,0 +1,90 @@ +//go:build conservative + +package app + +import ( + "context" + "testing" + "testing/synctest" + "time" + + "github.com/Mag1cFall/AIStudio2API/internal/aistudio" +) + +type conservativeMaintenanceCatalog struct { + modelCatalogService + models []aistudio.Model + refreshed int + expired int + idle int + patrolled int +} + +func (catalog *conservativeMaintenanceCatalog) RefreshAccountModels(context.Context, string, bool) ([]aistudio.Model, error) { + catalog.refreshed++ + return catalog.models, nil +} + +func (catalog *conservativeMaintenanceCatalog) CachedModels() []aistudio.Model { + return catalog.models +} + +func (catalog *conservativeMaintenanceCatalog) ReclaimExpiredResources(context.Context) error { + catalog.expired++ + return nil +} + +func (catalog *conservativeMaintenanceCatalog) ReclaimIdleAssistantApplets(context.Context) error { + catalog.idle++ + return nil +} + +func (catalog *conservativeMaintenanceCatalog) RefreshAccountState(context.Context, string, bool) (aistudio.AccountRefresh, error) { + catalog.patrolled++ + return aistudio.AccountRefresh{}, nil +} + +func TestConservativeMaintenanceRecoversCatalogAndReclaims(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + catalog := &conservativeMaintenanceCatalog{models: []aistudio.Model{{ID: "fixture-model"}}} + account := &aistudio.Account{ID: "fixture", Config: aistudio.DefaultAccountConfig("fixture"), State: aistudio.AccountReady} + service := &trackedService{ + lifecycle: ctx, catalog: catalog, pool: aistudio.NewAccountPool([]*aistudio.Account{account}, 1), + requests: newRequestRegistry(ctx), timeout: time.Minute, + modelRetries: map[string]struct{}{account.ID: {}}, + } + done := make(chan struct{}) + go func() { + service.retryModelCatalogs(ctx, time.Now()) + close(done) + }() + synctest.Wait() + if catalog.expired != 1 || catalog.idle != 1 { + t.Fatalf("startup cleanup: expired=%d idle=%d", catalog.expired, catalog.idle) + } + time.Sleep(modelCatalogRetryInterval) + synctest.Wait() + if catalog.refreshed != 1 || service.modelRetryPending(account.ID) || len(service.modelSnapshot()) != 1 { + t.Fatalf("pending catalog did not recover: refreshed=%d pending=%t models=%d", catalog.refreshed, service.modelRetryPending(account.ID), len(service.modelSnapshot())) + } + time.Sleep(idleResourceReclaimInterval - modelCatalogRetryInterval) + synctest.Wait() + if catalog.expired != 2 || catalog.idle != 2 || catalog.refreshed != 1 { + t.Fatalf("periodic cleanup: expired=%d idle=%d refreshed=%d", catalog.expired, catalog.idle, catalog.refreshed) + } + time.Sleep(accountStateRefreshInterval) + synctest.Wait() + if catalog.patrolled != 0 || catalog.refreshed != 1 { + t.Fatalf("unsolicited account polling: patrolled=%d refreshed=%d", catalog.patrolled, catalog.refreshed) + } + cancel() + synctest.Wait() + select { + case <-done: + default: + t.Fatal("maintenance did not stop on cancellation") + } + }) +} diff --git a/internal/app/conservative_test.go b/internal/app/conservative_test.go index aceea69e..eef51fd5 100644 --- a/internal/app/conservative_test.go +++ b/internal/app/conservative_test.go @@ -2,19 +2,45 @@ package app -import "testing" +import ( + "errors" + "fmt" + "net/http" + "testing" + "time" + + "github.com/Mag1cFall/AIStudio2API/internal/aistudio" +) func TestConservativeAllowsOnlyQuotaAccountFallback(t *testing.T) { if authenticationRecoveryAllowed(0) { t.Fatal("authentication recovery enabled") } - if !generationAttemptAllowed(0, false) { + if !generationAttemptAllowed(0, nil) { t.Fatal("first generation disabled") } - if generationAttemptAllowed(1, false) { - t.Fatal("non-quota automatic generation retry enabled") + planLimit := &aistudio.RPCError{StatusCode: http.StatusTooManyRequests, Message: "You have reached your usage limit"} + dailyLimit := &aistudio.RPCError{StatusCode: http.StatusTooManyRequests, Metadata: map[string]string{"quota_metric": "generate_requests_per_day"}} + for name, test := range map[string]struct { + err error + allowed bool + }{ + "plan": {planLimit, true}, + "daily": {dailyLimit, true}, + "wrapped": {fmt.Errorf("attempt failed: %w", planLimit), true}, + "network": {errors.New("connection reset"), false}, + "auth": {&aistudio.RPCError{StatusCode: http.StatusUnauthorized}, false}, + "server": {&aistudio.RPCError{StatusCode: http.StatusBadGateway}, false}, + "shortQuota": {&aistudio.RPCError{StatusCode: http.StatusTooManyRequests, RetryDelay: time.Minute}, false}, + "noFailure": {nil, false}, + } { + t.Run(name, func(t *testing.T) { + if got := generationAttemptAllowed(1, test.err); got != test.allowed { + t.Fatalf("generation retry allowed = %v, want %v", got, test.allowed) + } + }) } - if !generationAttemptAllowed(1, true) { - t.Fatal("quota account fallback disabled") + if !generationAttemptAllowed(1, planLimit) || generationAttemptAllowed(2, errors.New("connection reset")) { + t.Fatal("an earlier quota failure authorized a later non-quota replay") } } diff --git a/internal/app/runtime.go b/internal/app/runtime.go index 0a2db065..a24da5eb 100644 --- a/internal/app/runtime.go +++ b/internal/app/runtime.go @@ -844,12 +844,11 @@ func (service *trackedService) syncAccountModels(ctx context.Context, accountID // retryModelCatalogs 每 30 秒重新载入待同步账户的页面重试目录,自 startedAt 起每 24 小时重新载入启用账户的页面读取权益与目录;闲置的写代码助手应用与到期资源在启动时与每 10 分钟删除 func (service *trackedService) retryModelCatalogs(ctx context.Context, startedAt time.Time) { - if buildpolicy.Conservative { - return - } var patrol sync.WaitGroup defer patrol.Wait() - patrol.Go(func() { service.patrolAccountStates(ctx, startedAt) }) + if !buildpolicy.Conservative { + patrol.Go(func() { service.patrolAccountStates(ctx, startedAt) }) + } service.reclaimIdleAssistantApplets(ctx) service.reclaimExpiredResources(ctx) ticker := time.NewTicker(modelCatalogRetryInterval) @@ -1828,7 +1827,7 @@ func (service *trackedService) generateWithRetry( var activity *upstreamActivity var err error copyFiles := false - for attempt := 0; attempt < retry.maxAttempts && generationAttemptAllowed(attempt, retry.quotaRejected); attempt++ { + for attempt := 0; attempt < retry.maxAttempts && generationAttemptAllowed(attempt, err); attempt++ { selectionAccountID := requestedAccountID recoveringAccount := retry.recoveryAccountID != "" if retry.recoveryAccountID != "" { @@ -2038,8 +2037,14 @@ func (service *trackedService) generateWithRetry( ) } -func generationAttemptAllowed(attempt int, quotaRejected bool) bool { - return !buildpolicy.Conservative || attempt == 0 || quotaRejected +func generationAttemptAllowed(attempt int, lastError error) bool { + if !buildpolicy.Conservative || attempt == 0 { + return true + } + // Only the immediately preceding plan/daily rejection permits another account. + // An earlier quota failure must not authorize a later non-quota replay. + cooldown, quotaFailure := aistudio.QuotaCooldownForError(lastError, time.Now()) + return quotaFailure && aistudio.RequestQuotaCooldown(cooldown.Reason) } // markAttemptAccount 把访问日志与活动请求的执行账户与通道记为该租约 diff --git a/internal/config/conservative.go b/internal/config/conservative.go index 57f0db79..e110eacf 100644 --- a/internal/config/conservative.go +++ b/internal/config/conservative.go @@ -21,8 +21,19 @@ func validateConservative(c Config) error { if !c.AdminAuthEnabled || strings.TrimSpace(c.AdminPassword) == "" { return fmt.Errorf("conservative trial requires separate management authentication") } - if c.WAABackend != WAABackendCamoufox || c.FirstEventHedge != FirstEventHedgeOff || c.PerAccountConcurrency != 1 || c.MaxActiveWorkers != 1 || c.WarmStartupConcurrency != 1 || c.WarmWorkerLimit > 1 { - return fmt.Errorf("conservative trial requires one browser worker, one concurrent request and no hedging") + switch { + case c.WAABackend != WAABackendCamoufox: + return fmt.Errorf("conservative trial requires WAA_BACKEND=camoufox") + case c.FirstEventHedge != FirstEventHedgeOff: + return fmt.Errorf("conservative trial requires FIRST_EVENT_HEDGE=off") + case c.PerAccountConcurrency != 1: + return fmt.Errorf("conservative trial requires PER_ACCOUNT_CONCURRENCY=1") + case c.MaxActiveWorkers != 1: + return fmt.Errorf("conservative trial requires MAX_ACTIVE_WORKERS=1") + case c.WarmStartupConcurrency != 1: + return fmt.Errorf("conservative trial requires WARM_STARTUP_CONCURRENCY=1") + case c.WarmWorkerLimit > 1: + return fmt.Errorf("conservative trial requires WARM_WORKER_LIMIT<=1") } if c.RequestBodyLog || c.FakeStream || c.StripThoughtSignatures || c.ContinuationRewrite || len(c.UpstreamChannels) != 1 || c.UpstreamChannels[0] != "playground" { return fmt.Errorf("conservative trial requires native Playground responses and disabled body logging") diff --git a/internal/config/conservative_test.go b/internal/config/conservative_test.go index 444f8ef8..9cc2eb2e 100644 --- a/internal/config/conservative_test.go +++ b/internal/config/conservative_test.go @@ -2,7 +2,10 @@ package config -import "testing" +import ( + "strings" + "testing" +) func TestConservativeConfiguration(t *testing.T) { base := Default() @@ -45,3 +48,25 @@ func TestConservativeConfiguration(t *testing.T) { t.Fatal("empty API key accepted at runtime") } } + +func TestConservativeReportsInvalidWorkerSetting(t *testing.T) { + for key, change := range map[string]func(*Config){ + "WAA_BACKEND": func(c *Config) { c.WAABackend = WAABackendSpiderMonkey }, + "FIRST_EVENT_HEDGE": func(c *Config) { c.FirstEventHedge = "auto" }, + "PER_ACCOUNT_CONCURRENCY": func(c *Config) { c.PerAccountConcurrency = 2 }, + "MAX_ACTIVE_WORKERS": func(c *Config) { c.MaxActiveWorkers = 2 }, + "WARM_STARTUP_CONCURRENCY": func(c *Config) { c.WarmStartupConcurrency = 2 }, + "WARM_WORKER_LIMIT": func(c *Config) { c.WarmWorkerLimit = 2 }, + } { + t.Run(key, func(t *testing.T) { + cfg := Default() + cfg.AdminPassword = "fixture-management-secret" + cfg.ProxyAPIKey = "fixture-key" + change(&cfg) + err := ValidateRuntimePolicy(cfg) + if err == nil || !strings.Contains(err.Error(), key) { + t.Fatalf("expected actionable %s error, got %v", key, err) + } + }) + } +} From 82ceb6e6fa2a774bbe76c07e20100ba2df566e74 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Tue, 17 Nov 2026 16:55:19 +0900 Subject: [PATCH 4/5] style(web): format conservative account menu expression --- web/src/components/AccountsPanel.vue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/src/components/AccountsPanel.vue b/web/src/components/AccountsPanel.vue index 669d0090..9b157a7c 100644 --- a/web/src/components/AccountsPanel.vue +++ b/web/src/components/AccountsPanel.vue @@ -1047,7 +1047,7 @@ async function refreshAccounts(accounts: Account[]): Promise { class="z-[60] max-h-[var(--reka-dropdown-menu-content-available-height)] w-72 max-w-[calc(100vw-2rem)] overflow-y-auto rounded-lg border border-line bg-panel p-1 shadow-xl" > Date: Tue, 17 Nov 2026 17:12:40 +0900 Subject: [PATCH 5/5] fix: preserve file account selection before generation Count only started generation attempts so preparing a copy on another account neither consumes the attempt budget nor triggers the replay policy before the first generation. Keep the last-error quota/authentication boundary for actual retries. Exercise the real retry loop and account pool with a narrow lease-acquisition boundary: one copy and generation on the alternate account, explicit failures, cancellation, and a one-account cooling result. --- internal/app/conservative_generation_test.go | 179 +++++++++++++++++++ internal/app/runtime.go | 15 +- 2 files changed, 189 insertions(+), 5 deletions(-) create mode 100644 internal/app/conservative_generation_test.go diff --git a/internal/app/conservative_generation_test.go b/internal/app/conservative_generation_test.go new file mode 100644 index 00000000..6a8007bc --- /dev/null +++ b/internal/app/conservative_generation_test.go @@ -0,0 +1,179 @@ +//go:build conservative + +package app + +import ( + "context" + "errors" + "slices" + "testing" + "time" + + "github.com/Mag1cFall/AIStudio2API/internal/aistudio" +) + +// The real retry loop and account pool run here; browser startup and upstream +// generation are replaced at their boundaries, with no network transport. +type conservativeGenerationService struct { + aistudio.Service + generated []aistudio.GenerateRequest + copiedTo []string +} + +func (service *conservativeGenerationService) Generate(_ context.Context, request aistudio.GenerateRequest) (<-chan aistudio.Event, error) { + service.generated = append(service.generated, request) + events := make(chan aistudio.Event, 2) + events <- aistudio.Event{Kind: aistudio.EventText, Part: aistudio.Part{Text: "fixture reply"}, ProviderModel: request.Model} + events <- aistudio.Event{Kind: aistudio.EventFinish, FinishReason: "STOP", ProviderModel: request.Model} + close(events) + return events, nil +} + +func (service *conservativeGenerationService) CopyFileReferencesToLease(_ context.Context, lease *aistudio.AccountLease, contents []aistudio.Content) ([]aistudio.Content, *aistudio.TemporaryFileCopies, error) { + service.copiedTo = append(service.copiedTo, lease.Account().ID) + copied := slices.Clone(contents) + for index := range copied { + copied[index].Parts = slices.Clone(copied[index].Parts) + for part := range copied[index].Parts { + if original := copied[index].Parts[part].File; original != nil { + file := *original + file.ID = "copied-to-" + lease.Account().ID + copied[index].Parts[part].File = &file + } + } + } + return copied, &aistudio.TemporaryFileCopies{}, nil +} + +func conservativeFileGenerationFixture(t *testing.T, singleAccount bool) (*trackedService, *conservativeGenerationService, aistudio.GenerateRequest, string) { + t.Helper() + owner := &aistudio.Account{ID: "owner@example.invalid", Config: aistudio.DefaultAccountConfig("owner"), State: aistudio.AccountReady} + alternate := &aistudio.Account{ID: "alternate@example.invalid", Config: aistudio.DefaultAccountConfig("alternate"), State: aistudio.AccountReady} + accounts := []*aistudio.Account{owner} + if !singleAccount { + accounts = append(accounts, alternate) + } + pool := aistudio.NewAccountPool(accounts, 1) + pool.SetUpstreamChannels([]aistudio.Channel{aistudio.ChannelPlayground}) + model := aistudio.Model{ID: "fixture-model", Methods: []string{"generateContent"}, Capabilities: map[string]bool{"chat_model": true}} + otherModel := model + otherModel.ID = "owner-only-model" + if singleAccount { + otherModel = model + } + if err := pool.SetCatalog(owner.ID, owner.BenefitTier, []aistudio.Model{otherModel}); err != nil { + t.Fatal(err) + } + if !singleAccount { + if err := pool.SetCatalog(alternate.ID, alternate.BenefitTier, []aistudio.Model{model}); err != nil { + t.Fatal(err) + } + } + const resourceID = "fixture-file" + if err := pool.BindResourceKind(resourceID, owner.ID, "file"); err != nil { + t.Fatal(err) + } + upstream := &conservativeGenerationService{} + service := &trackedService{ + lifecycle: t.Context(), service: upstream, pool: pool, requests: newRequestRegistry(t.Context()), + workers: &accountWorkerManager{accounts: make(map[string]*accountWorker)}, models: []aistudio.Model{model}, + } + request := aistudio.GenerateRequest{ + ID: "file-selection-fixture", Model: model.ID, + Contents: []aistudio.Content{{Role: aistudio.RoleUser, Parts: []aistudio.Part{{File: &aistudio.FileRef{ID: resourceID}}}}}, + } + return service, upstream, request, resourceID +} + +func acquireConservativeFixtureLease(pool *aistudio.AccountPool, ctx context.Context, selection aistudio.AccountSelection) (*aistudio.AccountLease, error) { + lease, _, err := pool.TryAcquireFor(ctx, selection) + if lease == nil && err == nil { + err = pool.NoEligibleError(selection) + } + return lease, err +} + +func TestConservativeFileSelectionCopiesBeforeFirstGeneration(t *testing.T) { + service, upstream, request, resourceID := conservativeFileGenerationFixture(t, false) + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + var selectedResources []string + acquire := func(ctx context.Context, selection aistudio.AccountSelection, _ bool, _ *int, _ *time.Duration) (*aistudio.AccountLease, error) { + selectedResources = append(selectedResources, selection.ResourceID) + return acquireConservativeFixtureLease(service.pool, ctx, selection) + } + events := make(chan aistudio.Event, 8) + service.generateWithRetry(t.Context(), ctx, cancel, time.Now(), request, resourceID, events, acquire) + var kinds []aistudio.EventKind + for event := range events { + if event.Kind == aistudio.EventError { + t.Fatalf("file preparation emitted an error before generation: %v; selections=%v generated=%d", event.Err, selectedResources, len(upstream.generated)) + } + kinds = append(kinds, event.Kind) + } + if !slices.Equal(selectedResources, []string{resourceID, ""}) { + t.Fatalf("resource selections = %v, want owner then copy target", selectedResources) + } + if !slices.Equal(upstream.copiedTo, []string{"alternate@example.invalid"}) || len(upstream.generated) != 1 { + t.Fatalf("copies=%v generation calls=%d, want one copy and one generation on alternate", upstream.copiedTo, len(upstream.generated)) + } + generated := upstream.generated[0] + if generated.AccountID != "alternate@example.invalid" || generated.Contents[0].Parts[0].File.ID != "copied-to-alternate@example.invalid" { + t.Fatalf("generation did not use the alternate account's copy: %+v", generated) + } + if !slices.Equal(kinds, []aistudio.EventKind{aistudio.EventText, aistudio.EventFinish}) { + t.Fatalf("event sequence = %v", kinds) + } +} + +func TestConservativeFileSelectionFailureTerminates(t *testing.T) { + for _, name := range []string{"no_eligible_copy_target", "cancelled_copy_selection", "single_cooling_account"} { + t.Run(name, func(t *testing.T) { + singleAccount := name == "single_cooling_account" + service, upstream, request, resourceID := conservativeFileGenerationFixture(t, singleAccount) + cancelled := name == "cancelled_copy_selection" + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + calls := 0 + acquire := func(ctx context.Context, selection aistudio.AccountSelection, _ bool, _ *int, _ *time.Duration) (*aistudio.AccountLease, error) { + calls++ + if singleAccount { + // Keep the real one-account attempt budget, without waiting for + // the scheduler's cooldown timer at the acquisition boundary. + return nil, &aistudio.AllCoolingError{ModelID: request.Model, Until: time.Now().Add(time.Hour), Reason: "fixture cooldown"} + } + if selection.ResourceID != "" { + return acquireConservativeFixtureLease(service.pool, ctx, selection) + } + if cancelled { + cancel() + return nil, ctx.Err() + } + // The available target can disappear while preparing a file copy. + service.pool.SetModelAccounts(map[string][]string{request.Model: {"owner@example.invalid"}}) + return acquireConservativeFixtureLease(service.pool, ctx, selection) + } + events := make(chan aistudio.Event, 8) + service.generateWithRetry(t.Context(), ctx, cancel, time.Now(), request, resourceID, events, acquire) + want := aistudio.ErrNoEligibleAccount + if cancelled { + want = context.Canceled + } + count := 0 + for event := range events { + count++ + matches := errors.Is(event.Err, want) + if singleAccount { + var cooling *aistudio.AllCoolingError + matches = errors.As(event.Err, &cooling) + } + if event.Kind != aistudio.EventError || !matches { + t.Fatalf("terminal event = %s/%v, want error %v", event.Kind, event.Err, want) + } + } + if calls != 2 || count != 1 || len(upstream.generated) != 0 || len(upstream.copiedTo) != 0 { + t.Fatalf("selections=%d events=%d generations=%d copies=%v", calls, count, len(upstream.generated), upstream.copiedTo) + } + }) + } +} diff --git a/internal/app/runtime.go b/internal/app/runtime.go index 543bde91..3b4aa53b 100644 --- a/internal/app/runtime.go +++ b/internal/app/runtime.go @@ -1881,7 +1881,7 @@ func (service *trackedService) Generate(ctx context.Context, request aistudio.Ge return nil, err } events := make(chan aistudio.Event, 8) - go service.generateWithRetry(ctx, requestCtx, cancel, generationStartedAt, request, resourceID, events) + go service.generateWithRetry(ctx, requestCtx, cancel, generationStartedAt, request, resourceID, events, service.acquireWarmLease) return events, nil } @@ -1949,6 +1949,8 @@ type attemptOutcome struct { accountLabel string } +type warmLeaseAcquirer func(context.Context, aistudio.AccountSelection, bool, *int, *time.Duration) (*aistudio.AccountLease, error) + func (service *trackedService) generateWithRetry( clientCtx context.Context, requestCtx context.Context, @@ -1957,6 +1959,7 @@ func (service *trackedService) generateWithRetry( request aistudio.GenerateRequest, resourceID string, destination chan<- aistudio.Event, + acquire warmLeaseAcquirer, ) { requestedAccountID := strings.TrimSpace(request.AccountID) modelID := strings.TrimPrefix(strings.TrimSpace(request.Model), "models/") @@ -1982,7 +1985,8 @@ func (service *trackedService) generateWithRetry( var activity *upstreamActivity var err error copyFiles := false - for attempt := 0; attempt < retry.maxAttempts && generationAttemptAllowed(attempt, err); attempt++ { + // Account and file selection before startAttempt do not consume a generation attempt. + for attempt := 0; attempt < retry.maxAttempts && generationAttemptAllowed(attempt, err); { selectionAccountID := requestedAccountID recoveringAccount := retry.recoveryAccountID != "" if retry.recoveryAccountID != "" { @@ -2039,14 +2043,14 @@ func (service *trackedService) generateWithRetry( service.requests.logRequestProgress(request.ID, "request", "WARN", "排队等待", "waited", waited, "model", modelID) }) quotaFallback := selection.ResourceID == "" - lease, acquireErr := service.acquireWarmLease(requestCtx, selection, quotaFallback, &retry.failures, &retry.cooled) + lease, acquireErr := acquire(requestCtx, selection, quotaFallback, &retry.failures, &retry.cooled) var buildCooling *aistudio.AllCoolingError if acquireErr != nil && selection.Channel == aistudio.ChannelBuild && requestCtx.Err() == nil && !aistudio.RequestBuildOnly(request) && (errors.Is(acquireErr, aistudio.ErrNoEligibleAccount) || errors.As(acquireErr, &buildCooling)) { // 没有账户能经 Build 服务时改用 Playground,Playground 无法表达的设置按其最接近的形式发送 selection.Channel = "" fallbackReason = "Build 通道没有可用账户" - lease, acquireErr = service.acquireWarmLease(requestCtx, selection, quotaFallback, &retry.failures, &retry.cooled) + lease, acquireErr = acquire(requestCtx, selection, quotaFallback, &retry.failures, &retry.cooled) } queueDelayed := queueWait.finish() if acquireErr == nil && selection.PreferredChannel == aistudio.ChannelBuild && lease.Channel() != aistudio.ChannelBuild { @@ -2091,6 +2095,7 @@ func (service *trackedService) generateWithRetry( service.requests.logRequestProgress(request.ID, accountLabel, "INFO", "排队结束", "waited", time.Since(queueStartedAt)) } service.requests.logRequestProgress(request.ID, accountLabel, "INFO", "等待上游响应") + attempt++ primary := service.startAttempt(requestCtx, request, resourceID, modelID, fallbackReason, lease, selection, false, retry.failures) var plan *hedgePlan if hedgeable && !hedged { @@ -2159,7 +2164,7 @@ func (service *trackedService) generateWithRetry( delete(retry.attempted, last.accountID) retry.maxAttempts++ } - if attempt+1 == retry.maxAttempts { + if attempt == retry.maxAttempts { if service.retryRejectedAccount(request.ID, modelID, retry, err) { continue }