From 03aa05fd9fa0d33757aa70833da170adbe9f1263 Mon Sep 17 00:00:00 2001 From: Brisbanehuang Date: Sat, 21 Nov 2026 07:02:53 -0800 Subject: [PATCH] =?UTF-8?q?feat(accounts):=20=E6=8C=89=E8=B4=A6=E5=8F=B7?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E5=90=8C=E6=AD=A5=E4=B8=8A=E6=B8=B8=E5=88=86?= =?UTF-8?q?=E7=BB=84=E5=90=8D=E7=A7=B0=E4=B8=8E=E5=A4=87=E6=B3=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/handler/admin/account_handler.go | 4 + .../internal/handler/gateway_key_billing.go | 7 +- backend/internal/repository/account_repo.go | 117 +++++++++--------- .../account_repo_grok_managed_extra_test.go | 6 +- ...epo_ollama_cloud_usage_integration_test.go | 4 +- .../account_repo_opencode_go_usage_test.go | 6 +- ...nt_repo_upstream_billing_probe_cas_test.go | 12 +- ...repo_upstream_billing_probe_update_test.go | 24 ++-- ...ling_probe_persistence_integration_test.go | 55 ++++++-- backend/internal/server/api_contract_test.go | 4 +- .../server/routes/gateway_key_billing_test.go | 30 +++-- backend/internal/service/account_service.go | 19 ++- backend/internal/service/admin_account.go | 50 ++++++-- ...min_account_upstream_billing_probe_test.go | 36 ++++-- backend/internal/service/admin_service.go | 2 + backend/internal/service/crs_sync_service.go | 7 +- .../service/upstream_billing_probe.go | 50 ++++++-- .../service/upstream_billing_probe_test.go | 48 +++++++ .../components/account/CreateAccountModal.vue | 17 +++ .../components/account/EditAccountModal.vue | 18 +++ .../account/UpstreamGroupSyncButton.vue | 32 +++-- .../__tests__/CreateAccountModal.spec.ts | 20 +++ .../__tests__/EditAccountModal.spec.ts | 20 +++ .../src/i18n/locales/en/admin/accounts.ts | 2 + .../src/i18n/locales/zh/admin/accounts.ts | 2 + frontend/src/types/index.ts | 3 + 26 files changed, 433 insertions(+), 162 deletions(-) diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go index 225f18f372..ca51136705 100644 --- a/backend/internal/handler/admin/account_handler.go +++ b/backend/internal/handler/admin/account_handler.go @@ -136,6 +136,7 @@ type CreateAccountRequest struct { ExpiresAt *int64 `json:"expires_at"` AutoPauseOnExpired *bool `json:"auto_pause_on_expired"` ProbeEnabled *bool `json:"upstream_billing_probe_enabled"` + GroupSyncEnabled *bool `json:"upstream_billing_group_sync_enabled"` ConfirmMixedChannelRisk *bool `json:"confirm_mixed_channel_risk"` // 用户确认混合渠道风险 } @@ -157,6 +158,7 @@ type UpdateAccountRequest struct { ExpiresAt *int64 `json:"expires_at"` AutoPauseOnExpired *bool `json:"auto_pause_on_expired"` ProbeEnabled *bool `json:"upstream_billing_probe_enabled"` + GroupSyncEnabled *bool `json:"upstream_billing_group_sync_enabled"` RateSyncEnabled *bool `json:"upstream_billing_rate_sync_enabled"` ConfirmMixedChannelRisk *bool `json:"confirm_mixed_channel_risk"` // 用户确认混合渠道风险 } @@ -1062,6 +1064,7 @@ func (h *AccountHandler) Create(c *gin.Context) { ExpiresAt: req.ExpiresAt, AutoPauseOnExpired: req.AutoPauseOnExpired, ProbeEnabled: req.ProbeEnabled, + GroupSyncEnabled: req.GroupSyncEnabled, SkipMixedChannelCheck: skipCheck, }) if execErr != nil { @@ -1194,6 +1197,7 @@ func (h *AccountHandler) Update(c *gin.Context) { ExpiresAt: req.ExpiresAt, AutoPauseOnExpired: req.AutoPauseOnExpired, ProbeEnabled: req.ProbeEnabled, + GroupSyncEnabled: req.GroupSyncEnabled, RateSyncEnabled: req.RateSyncEnabled, SkipMixedChannelCheck: skipCheck, }) diff --git a/backend/internal/handler/gateway_key_billing.go b/backend/internal/handler/gateway_key_billing.go index 154692ceb3..59e33e43b7 100644 --- a/backend/internal/handler/gateway_key_billing.go +++ b/backend/internal/handler/gateway_key_billing.go @@ -1,6 +1,7 @@ package handler import ( + "log/slog" "net/http" "time" @@ -62,10 +63,10 @@ func (h *GatewayHandler) KeyBillingInfo(c *gin.Context) { if c.Query("include") == "group" { group, err := h.apiKeyService.GetBillingGroupInfo(c.Request.Context(), *apiKey.GroupID, c.GetHeader("Accept-Language")) if err != nil { - h.errorResponse(c, http.StatusInternalServerError, "api_error", "Billing information is unavailable") - return + slog.WarnContext(c.Request.Context(), "billing group display text unavailable", "group_id", *apiKey.GroupID, "error", err) + } else { + info.BillingGroupInfo = group } - info.BillingGroupInfo = group } c.Header("Cache-Control", "no-store") c.JSON(http.StatusOK, info) diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index 80bebe8314..bdbf25219b 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -61,6 +61,7 @@ var schedulerNeutralExtraKeyPrefixes = []string{ "passive_usage_", "upstream_billing_probe", "upstream_billing_rate_sync", + "upstream_billing_group_sync", "ollama_cloud_usage", } @@ -449,7 +450,7 @@ func (r *accountRepository) Update(ctx context.Context, account *service.Account if scoped := r.accountTransactionScope(ctx); scoped != r { return scoped.Update(ctx, account) } - return r.updateAccount(ctx, account, nil, nil, account.RateMultiplier) + return r.updateAccount(ctx, account, service.AccountBillingSettingsUpdate{RateMultiplier: account.RateMultiplier, SetName: true, SetNotes: true}) } // UpdateWithAccountBillingSettings applies an admin account edit while @@ -458,19 +459,15 @@ func (r *accountRepository) Update(ctx context.Context, account *service.Account func (r *accountRepository) UpdateWithAccountBillingSettings( ctx context.Context, account *service.Account, - probeEnabled *bool, - rateSyncEnabled *bool, - rateMultiplier *float64, + settings service.AccountBillingSettingsUpdate, ) error { - return r.updateAccount(ctx, account, probeEnabled, rateSyncEnabled, rateMultiplier) + return r.updateAccount(ctx, account, settings) } func (r *accountRepository) updateAccount( ctx context.Context, account *service.Account, - explicitProbeEnabled *bool, - explicitRateSyncEnabled *bool, - explicitRateMultiplier *float64, + settings service.AccountBillingSettingsUpdate, ) error { if account == nil { return nil @@ -499,9 +496,7 @@ func (r *accountRepository) updateAccount( ctx, client, account, - explicitProbeEnabled, - explicitRateSyncEnabled, - explicitRateMultiplier, + settings, ) if err != nil { return translatePersistenceError(err, service.ErrAccountNotFound, nil) @@ -528,11 +523,9 @@ func (r *accountRepository) updateLockedAccount( ctx context.Context, client *dbent.Client, account *service.Account, - explicitProbeEnabled *bool, - explicitRateSyncEnabled *bool, - explicitRateMultiplier *float64, + settings service.AccountBillingSettingsUpdate, ) (*dbent.Account, error) { - extra, err := lockAndMergeAccountProbeExtra(ctx, client, account, explicitProbeEnabled, explicitRateSyncEnabled) + extra, err := lockAndMergeAccountProbeExtra(ctx, client, account, settings) if err != nil { return nil, err } @@ -544,8 +537,6 @@ func (r *accountRepository) updateLockedAccount( } builder := client.Account.UpdateOneID(account.ID). - SetName(account.Name). - SetNillableNotes(account.Notes). SetPlatform(account.Platform). SetType(account.Type). SetCredentials(normalizeJSONMap(account.Credentials)). @@ -557,8 +548,18 @@ func (r *accountRepository) updateLockedAccount( SetSchedulable(schedulable). SetAutoPauseOnExpired(account.AutoPauseOnExpired) - if explicitRateMultiplier != nil { - builder.SetRateMultiplier(*explicitRateMultiplier) + if settings.SetName { + builder.SetName(account.Name) + } + if settings.SetNotes { + if account.Notes == nil { + builder.ClearNotes() + } else { + builder.SetNotes(*account.Notes) + } + } + if settings.RateMultiplier != nil { + builder.SetRateMultiplier(*settings.RateMultiplier) } if account.LoadFactor != nil { builder.SetLoadFactor(*account.LoadFactor) @@ -611,10 +612,6 @@ func (r *accountRepository) updateLockedAccount( } else { builder.ClearSessionWindowStatus() } - if account.Notes == nil { - builder.ClearNotes() - } - builder.SetQuotaDimension(dbaccount.QuotaDimension(account.QuotaDimensionOrDefault())) builder.SetNillableParentAccountID(account.ParentAccountID) @@ -625,8 +622,7 @@ func lockAndMergeAccountProbeExtra( ctx context.Context, client *dbent.Client, account *service.Account, - explicitProbeEnabled *bool, - explicitRateSyncEnabled *bool, + settings service.AccountBillingSettingsUpdate, ) (map[string]any, error) { credentials, err := json.Marshal(normalizeJSONMap(account.Credentials)) if err != nil { @@ -682,7 +678,8 @@ func lockAndMergeAccountProbeExtra( extra -> 'opencode_go_usage_auto_refresh', extra -> 'opencode_go_usage_snapshot', extra -> 'grok_observed_models', - extra -> 'upstream_model_metadata' + extra -> 'upstream_model_metadata', + extra -> 'upstream_billing_group_sync_enabled' FROM accounts WHERE id = $1 AND deleted_at IS NULL FOR NO KEY UPDATE @@ -705,6 +702,7 @@ func lockAndMergeAccountProbeExtra( opencodeGroupIdentityUnchanged bool currentEnabled []byte currentRateSyncEnabled []byte + currentGroupSyncEnabled []byte currentSnapshot []byte currentOllamaSession []byte currentOllamaAutoRefresh []byte @@ -729,6 +727,7 @@ func lockAndMergeAccountProbeExtra( ¤tOpenCodeSnapshot, ¤tGrokObservedModels, ¤tUpstreamModelMetadata, + ¤tGroupSyncEnabled, ); err != nil { return nil, err } @@ -740,6 +739,7 @@ func lockAndMergeAccountProbeExtra( for _, key := range []string{ service.UpstreamBillingProbeEnabledExtraKey, service.UpstreamBillingRateSyncEnabledExtraKey, + service.UpstreamBillingGroupSyncEnabledExtraKey, service.UpstreamBillingProbeExtraKey, service.OllamaCloudUsageSessionExtraKey, service.OllamaCloudUsageAutoRefreshExtraKey, @@ -759,40 +759,32 @@ func lockAndMergeAccountProbeExtra( probeEnabled = value probeEnabledPresent = true } - if explicitProbeEnabled != nil { - probeEnabled = *explicitProbeEnabled + if settings.ProbeEnabled != nil { + probeEnabled = *settings.ProbeEnabled probeEnabledPresent = true } - } - rateSyncEnabled := false - rateSyncEnabledPresent := false - if probeAccount { - if enabled, ok, err := decodeAccountExtraJSON(currentRateSyncEnabled); err != nil { - return nil, err - } else if value, isBool := enabled.(bool); ok && isBool { - rateSyncEnabled = value - rateSyncEnabledPresent = true - } - if explicitRateSyncEnabled != nil { - rateSyncEnabled = *explicitRateSyncEnabled - rateSyncEnabledPresent = true - } - if explicitProbeEnabled != nil && !*explicitProbeEnabled { - rateSyncEnabled = false - rateSyncEnabledPresent = true - } - // 同步依赖探测,方向是单向的:探测关闭(或探测键缺失)一律把同步归零。 - // 不做反向推导——由 rate_sync=true 推出 probe=true 会让一条"同步开、探测键 - // 缺失"的僵尸记录在任意一次无关编辑时静默打开周期性外呼。需要同时打开两个 - // 开关的调用方(管理端编辑)自己显式传 explicitProbeEnabled=true。 - if !probeEnabled { - rateSyncEnabled = false - } if probeEnabledPresent { extra[service.UpstreamBillingProbeEnabledExtraKey] = probeEnabled } - if rateSyncEnabledPresent { - extra[service.UpstreamBillingRateSyncEnabledExtraKey] = rateSyncEnabled + for _, flag := range []struct { + key string + stored []byte + requested *bool + }{ + {service.UpstreamBillingRateSyncEnabledExtraKey, currentRateSyncEnabled, settings.RateSyncEnabled}, + {service.UpstreamBillingGroupSyncEnabledExtraKey, currentGroupSyncEnabled, settings.GroupSyncEnabled}, + } { + value, _, err := decodeAccountExtraJSON(flag.stored) + if err != nil { + return nil, err + } + enabled, present := value.(bool) + if flag.requested != nil { + enabled, present = *flag.requested, true + } + if present || (settings.ProbeEnabled != nil && !*settings.ProbeEnabled) { + extra[flag.key] = probeEnabled && enabled + } } } probeExplicitlyDisabled := probeEnabledPresent && !probeEnabled @@ -2973,24 +2965,26 @@ func (r *accountRepository) UpdateUpstreamBillingProbeSnapshot( account *service.Account, snapshot *service.UpstreamBillingProbeSnapshot, rateMultiplier *float64, + group service.BillingGroupInfo, ) error { if account == nil || snapshot == nil { return service.ErrAccountNilInput } if snapshot.Status != service.UpstreamBillingProbeStatusOK { rateMultiplier = nil + group = service.BillingGroupInfo{} } if dbent.TxFromContext(ctx) == nil { tx, err := r.client.Tx(ctx) if errors.Is(err, dbent.ErrTxStarted) { - return r.updateUpstreamBillingProbeSnapshotInTx(ctx, account, snapshot, rateMultiplier) + return r.updateUpstreamBillingProbeSnapshotInTx(ctx, account, snapshot, rateMultiplier, group) } if err != nil { return err } defer func() { _ = tx.Rollback() }() - if err := r.updateUpstreamBillingProbeSnapshotInTx(dbent.NewTxContext(ctx, tx), account, snapshot, rateMultiplier); err != nil { + if err := r.updateUpstreamBillingProbeSnapshotInTx(dbent.NewTxContext(ctx, tx), account, snapshot, rateMultiplier, group); err != nil { return err } if err := tx.Commit(); err != nil { @@ -3001,7 +2995,7 @@ func (r *accountRepository) UpdateUpstreamBillingProbeSnapshot( r.syncSchedulerAccountSnapshot(ctx, account.ID) return nil } - return r.updateUpstreamBillingProbeSnapshotInTx(ctx, account, snapshot, rateMultiplier) + return r.updateUpstreamBillingProbeSnapshotInTx(ctx, account, snapshot, rateMultiplier, group) } func (r *accountRepository) updateUpstreamBillingProbeSnapshotInTx( @@ -3009,6 +3003,7 @@ func (r *accountRepository) updateUpstreamBillingProbeSnapshotInTx( account *service.Account, snapshot *service.UpstreamBillingProbeSnapshot, rateMultiplier *float64, + group service.BillingGroupInfo, ) error { payload, err := json.Marshal(map[string]any{service.UpstreamBillingProbeExtraKey: snapshot}) if err != nil { @@ -3065,6 +3060,10 @@ func (r *accountRepository) updateUpstreamBillingProbeSnapshotInTx( THEN $10::numeric ELSE rate_multiplier END, + name = CASE WHEN extra @> '{"upstream_billing_group_sync_enabled": true, "upstream_billing_probe_enabled": true}'::jsonb + THEN COALESCE(NULLIF($11, ''), name) ELSE name END, + notes = CASE WHEN extra @> '{"upstream_billing_group_sync_enabled": true, "upstream_billing_probe_enabled": true}'::jsonb + THEN COALESCE(NULLIF($12, ''), notes) ELSE notes END, updated_at = NOW() WHERE id = $2 AND platform = $3 @@ -3075,7 +3074,7 @@ func (r *accountRepository) updateUpstreamBillingProbeSnapshotInTx( AND COALESCE(extra -> 'upstream_billing_probe_enabled', 'null'::jsonb) = $8::jsonb AND COALESCE(extra -> 'upstream_billing_rate_sync_enabled', 'null'::jsonb) = $9::jsonb AND deleted_at IS NULL - `, string(payload), account.ID, account.Platform, account.Type, string(credentials), proxyID, string(expectedSnapshotJSON), string(expectedEnabledJSON), string(expectedRateSyncEnabledJSON), rateMultiplier) + `, string(payload), account.ID, account.Platform, account.Type, string(credentials), proxyID, string(expectedSnapshotJSON), string(expectedEnabledJSON), string(expectedRateSyncEnabledJSON), rateMultiplier, group.Name, group.Description) if err != nil { return err } diff --git a/backend/internal/repository/account_repo_grok_managed_extra_test.go b/backend/internal/repository/account_repo_grok_managed_extra_test.go index ff224d210b..cf4e36bc03 100644 --- a/backend/internal/repository/account_repo_grok_managed_extra_test.go +++ b/backend/internal/repository/account_repo_grok_managed_extra_test.go @@ -142,8 +142,8 @@ func TestLockAndMergeAccountProbeExtraKeepsLatestGrokManagedKeys(t *testing.T) { "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", - "grok_observed_models", "upstream_model_metadata", - }).AddRow(false, false, true, nil, nil, nil, nil, nil, nil, false, nil, nil, tt.databaseModels, tt.databaseMetadata)) + "grok_observed_models", "upstream_model_metadata", "group_sync_enabled", + }).AddRow(false, false, true, nil, nil, nil, nil, nil, nil, false, nil, nil, tt.databaseModels, tt.databaseMetadata, nil)) account := &service.Account{ ID: 41, @@ -152,7 +152,7 @@ func TestLockAndMergeAccountProbeExtraKeepsLatestGrokManagedKeys(t *testing.T) { Credentials: tt.credentials, Extra: tt.inputExtra, } - got, err := lockAndMergeAccountProbeExtra(context.Background(), client, account, nil, nil) + got, err := lockAndMergeAccountProbeExtra(context.Background(), client, account, service.AccountBillingSettingsUpdate{}) require.NoError(t, err) require.Equal(t, "from-form", got["note"]) if tt.wantModels == nil { diff --git a/backend/internal/repository/account_repo_ollama_cloud_usage_integration_test.go b/backend/internal/repository/account_repo_ollama_cloud_usage_integration_test.go index 71fbc0b4c7..753d1bef26 100644 --- a/backend/internal/repository/account_repo_ollama_cloud_usage_integration_test.go +++ b/backend/internal/repository/account_repo_ollama_cloud_usage_integration_test.go @@ -229,7 +229,7 @@ func TestLockAndMergeAccountProbeExtraCoalescesNullableOllamaGroupIdentity(t *te loaded, err := newAccountRepositoryWithSQL(tx.Client(), tx, nil).GetByID(ctx, account.ID) require.NoError(t, err) - merged, err := lockAndMergeAccountProbeExtra(ctx, tx.Client(), loaded, nil, nil) + merged, err := lockAndMergeAccountProbeExtra(ctx, tx.Client(), loaded, service.AccountBillingSettingsUpdate{}) require.NoError(t, err, "a NULL Ollama eligibility expression must scan as false") require.NotContains(t, merged, service.OllamaCloudUsageSessionExtraKey) @@ -421,7 +421,7 @@ func TestOllamaCloudUsageEligibilityExtendsToCNOpenAICompatPlatforms(t *testing. // lockAndMerge 组身份守卫:CN 行凭证未变时必须保留 ollama 托管键。 kimiLoaded, err := repo.GetByID(ctx, kimi.ID) require.NoError(t, err) - merged, err := lockAndMergeAccountProbeExtra(ctx, tx.Client(), kimiLoaded, nil, nil) + merged, err := lockAndMergeAccountProbeExtra(ctx, tx.Client(), kimiLoaded, service.AccountBillingSettingsUpdate{}) require.NoError(t, err) require.Equal(t, "cipher:cn-shared", merged[service.OllamaCloudUsageSessionExtraKey]) require.Equal(t, true, merged[service.OllamaCloudUsageAutoRefreshExtraKey]) diff --git a/backend/internal/repository/account_repo_opencode_go_usage_test.go b/backend/internal/repository/account_repo_opencode_go_usage_test.go index 43581ec231..fa0b6b0021 100644 --- a/backend/internal/repository/account_repo_opencode_go_usage_test.go +++ b/backend/internal/repository/account_repo_opencode_go_usage_test.go @@ -76,7 +76,7 @@ func openCodeGoMergeMockColumns() []string { "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", - "grok_observed_models", "upstream_model_metadata", + "grok_observed_models", "upstream_model_metadata", "group_sync_enabled", } } @@ -189,9 +189,9 @@ func TestLockAndMergeAccountProbeExtraPreservesOpenCodeGoManagedState(t *testing mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")). WithArgs(tt.account.ID, tt.account.Platform, tt.account.Type, string(credentials), nil). WillReturnRows(sqlmock.NewRows(openCodeGoMergeMockColumns()). - AddRow(false, false, tt.proxyUnchanged, nil, nil, nil, nil, nil, nil, tt.groupUnchanged, tt.databaseAuto, tt.databaseSnapshot, nil, nil)) + AddRow(false, false, tt.proxyUnchanged, nil, nil, nil, nil, nil, nil, tt.groupUnchanged, tt.databaseAuto, tt.databaseSnapshot, nil, nil, nil)) - got, err := lockAndMergeAccountProbeExtra(context.Background(), client, tt.account, nil, nil) + got, err := lockAndMergeAccountProbeExtra(context.Background(), client, tt.account, service.AccountBillingSettingsUpdate{}) require.NoError(t, err) if tt.wantAuto == nil { require.NotContains(t, got, service.OpenCodeGoUsageAutoRefreshExtraKey) diff --git a/backend/internal/repository/account_repo_upstream_billing_probe_cas_test.go b/backend/internal/repository/account_repo_upstream_billing_probe_cas_test.go index f9fe019554..77410d05d9 100644 --- a/backend/internal/repository/account_repo_upstream_billing_probe_cas_test.go +++ b/backend/internal/repository/account_repo_upstream_billing_probe_cas_test.go @@ -42,7 +42,7 @@ func TestUpdateUpstreamBillingProbeSnapshotRequiresSameIdentityAndSnapshot(t *te WillReturnRows(sqlmock.NewRows([]string{"protocol", "host", "port", "username", "password", "status"}). AddRow("http", "127.0.0.1", 3128, "user", "pass", service.StatusActive)) mock.ExpectExec(`(?s)`+regexp.QuoteMeta("UPDATE accounts")+`.*`+regexp.QuoteMeta("WHERE id = $2")+`.*`+regexp.QuoteMeta("AND platform = $3")+`.*`+regexp.QuoteMeta("AND type = $4")+`.*`+regexp.QuoteMeta("AND credentials = $5::jsonb")+`.*`+regexp.QuoteMeta("AND proxy_id IS NOT DISTINCT FROM $6")+`.*`+regexp.QuoteMeta("COALESCE(extra -> 'upstream_billing_probe', 'null'::jsonb) = $7::jsonb")+`.*`+regexp.QuoteMeta("COALESCE(extra -> 'upstream_billing_probe_enabled', 'null'::jsonb) = $8::jsonb")+`.*`+regexp.QuoteMeta("COALESCE(extra -> 'upstream_billing_rate_sync_enabled', 'null'::jsonb) = $9::jsonb")). - WithArgs(sqlmock.AnyArg(), int64(17), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test","base_url":"http://127.0.0.1:8080"}`, int64(9), `{"status":"stale"}`, "null", "null", nil). + WithArgs(sqlmock.AnyArg(), int64(17), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test","base_url":"http://127.0.0.1:8080"}`, int64(9), `{"status":"stale"}`, "null", "null", nil, "", ""). WillReturnResult(sqlmock.NewResult(0, tt.affected)) if tt.affected > 0 { mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox")). @@ -75,7 +75,7 @@ func TestUpdateUpstreamBillingProbeSnapshotRequiresSameIdentityAndSnapshot(t *te } txCtx := dbent.NewTxContext(context.Background(), tx) - err = repo.UpdateUpstreamBillingProbeSnapshot(txCtx, account, &service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK}, nil) + err = repo.UpdateUpstreamBillingProbeSnapshot(txCtx, account, &service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK}, nil, service.BillingGroupInfo{}) if tt.wantErr != nil { require.ErrorIs(t, err, tt.wantErr) @@ -99,7 +99,7 @@ func TestUpdateUpstreamBillingProbeSnapshotCommitsSnapshotAndOutboxAtomically(t mock.ExpectBegin() mock.ExpectExec(`(?s)`+regexp.QuoteMeta("UPDATE accounts")+`.*`+regexp.QuoteMeta("rate_multiplier = CASE")+`.*`+regexp.QuoteMeta("THEN $10::numeric")+`.*`+regexp.QuoteMeta("AND credentials = $5::jsonb")+`.*`+regexp.QuoteMeta("AND proxy_id IS NOT DISTINCT FROM $6")+`.*`+regexp.QuoteMeta("COALESCE(extra -> 'upstream_billing_probe', 'null'::jsonb) = $7::jsonb")). - WithArgs(sqlmock.AnyArg(), int64(17), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil, "null", "true", "true", 0.065). + WithArgs(sqlmock.AnyArg(), int64(17), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil, "null", "true", "true", 0.065, "", ""). WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox")). WithArgs(service.SchedulerOutboxEventAccountChanged, int64(17), nil, nil, sqlmock.AnyArg()). @@ -124,6 +124,7 @@ func TestUpdateUpstreamBillingProbeSnapshotCommitsSnapshotAndOutboxAtomically(t account, &service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK}, &rateMultiplier, + service.BillingGroupInfo{}, ) require.NoError(t, err) @@ -158,7 +159,7 @@ func TestUpdateUpstreamBillingProbeSnapshotRejectsChangedProxyIdentity(t *testin }, } repo := newAccountRepositoryWithSQL(client, db, nil) - err = repo.UpdateUpstreamBillingProbeSnapshot(dbent.NewTxContext(context.Background(), tx), account, &service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK}, nil) + err = repo.UpdateUpstreamBillingProbeSnapshot(dbent.NewTxContext(context.Background(), tx), account, &service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK}, nil, service.BillingGroupInfo{}) require.ErrorIs(t, err, service.ErrUpstreamBillingProbeIdentityChanged) mock.ExpectRollback() @@ -176,7 +177,7 @@ func TestUpdateUpstreamBillingProbeSnapshotRollsBackWhenOutboxFails(t *testing.T mock.ExpectBegin() mock.ExpectExec(`(?s)`+regexp.QuoteMeta("UPDATE accounts")+`.*`+regexp.QuoteMeta("AND proxy_id IS NOT DISTINCT FROM $6")+`.*`+regexp.QuoteMeta("COALESCE(extra -> 'upstream_billing_probe', 'null'::jsonb) = $7::jsonb")). - WithArgs(sqlmock.AnyArg(), int64(18), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil, "null", "true", "true", 0.7). + WithArgs(sqlmock.AnyArg(), int64(18), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil, "null", "true", "true", 0.7, "", ""). WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox")).WillReturnError(errors.New("outbox failed")) mock.ExpectRollback() @@ -199,6 +200,7 @@ func TestUpdateUpstreamBillingProbeSnapshotRollsBackWhenOutboxFails(t *testing.T account, &service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK}, &rateMultiplier, + service.BillingGroupInfo{}, ) require.EqualError(t, err, "outbox failed") diff --git a/backend/internal/repository/account_repo_upstream_billing_probe_update_test.go b/backend/internal/repository/account_repo_upstream_billing_probe_update_test.go index 15bccacf79..bf7b45add5 100644 --- a/backend/internal/repository/account_repo_upstream_billing_probe_update_test.go +++ b/backend/internal/repository/account_repo_upstream_billing_probe_update_test.go @@ -81,8 +81,8 @@ func TestLockAndMergeAccountProbeExtraUsesCurrentDatabaseSnapshot(t *testing.T) mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")). WithArgs(int64(27), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil). - WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata"}). - AddRow(tt.identityUnchanged, false, true, tt.databaseEnabled, nil, tt.databaseSnapshot, nil, nil, nil, false, nil, nil, nil, nil)) + WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata", "group_sync_enabled"}). + AddRow(tt.identityUnchanged, false, true, tt.databaseEnabled, nil, tt.databaseSnapshot, nil, nil, nil, false, nil, nil, nil, nil, nil)) account := &service.Account{ ID: 27, @@ -91,7 +91,7 @@ func TestLockAndMergeAccountProbeExtraUsesCurrentDatabaseSnapshot(t *testing.T) Credentials: map[string]any{"api_key": "sk-test"}, Extra: tt.inputExtra, } - got, err := lockAndMergeAccountProbeExtra(context.Background(), client, account, nil, nil) + got, err := lockAndMergeAccountProbeExtra(context.Background(), client, account, service.AccountBillingSettingsUpdate{}) require.NoError(t, err) if tt.wantSnapshot == nil { require.NotContains(t, got, service.UpstreamBillingProbeExtraKey) @@ -172,8 +172,8 @@ func TestLockAndMergeAccountProbeExtraNeverInfersProbeFromRateSync(t *testing.T) mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")). WithArgs(int64(31), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil). - WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata"}). - AddRow(true, false, true, tt.databaseEnabled, tt.databaseRateSync, nil, nil, nil, nil, false, nil, nil, nil, nil)) + WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata", "group_sync_enabled"}). + AddRow(true, false, true, tt.databaseEnabled, tt.databaseRateSync, nil, nil, nil, nil, false, nil, nil, nil, nil, nil)) account := &service.Account{ ID: 31, @@ -182,7 +182,7 @@ func TestLockAndMergeAccountProbeExtraNeverInfersProbeFromRateSync(t *testing.T) Credentials: map[string]any{"api_key": "sk-test"}, } got, err := lockAndMergeAccountProbeExtra( - context.Background(), client, account, tt.explicitProbeEnabled, tt.explicitRateSync, + context.Background(), client, account, service.AccountBillingSettingsUpdate{ProbeEnabled: tt.explicitProbeEnabled, RateSyncEnabled: tt.explicitRateSync}, ) require.NoError(t, err) if tt.wantEnabled == nil { @@ -211,8 +211,8 @@ func TestLockAndMergeAccountProbeExtraProtectsOllamaManagedFields(t *testing.T) mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")). WithArgs(int64(29), service.PlatformAnthropic, service.AccountTypeAPIKey, `{"api_key":"key","base_url":"https://ollama.com"}`, nil). - WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata"}). - AddRow(identityUnchanged, identityUnchanged, true, nil, nil, nil, []byte(`"local-ciphertext"`), []byte(`true`), []byte(`{"status":"ok"}`), false, nil, nil, nil, nil)) + WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata", "group_sync_enabled"}). + AddRow(identityUnchanged, identityUnchanged, true, nil, nil, nil, []byte(`"local-ciphertext"`), []byte(`true`), []byte(`{"status":"ok"}`), false, nil, nil, nil, nil, nil)) account := &service.Account{ ID: 29, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, @@ -223,7 +223,7 @@ func TestLockAndMergeAccountProbeExtraProtectsOllamaManagedFields(t *testing.T) service.OllamaCloudUsageSnapshotExtraKey: map[string]any{"status": "forged"}, }, } - got, err := lockAndMergeAccountProbeExtra(context.Background(), client, account, nil, nil) + got, err := lockAndMergeAccountProbeExtra(context.Background(), client, account, service.AccountBillingSettingsUpdate{}) require.NoError(t, err) if identityUnchanged { require.Equal(t, "local-ciphertext", got[service.OllamaCloudUsageSessionExtraKey]) @@ -371,8 +371,8 @@ func TestUpdateWithAccountBillingSettingsRollsBackWhenOutboxFails(t *testing.T) mock.ExpectBegin() mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")). WithArgs(int64(27), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil). - WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata"}). - AddRow(true, false, true, []byte(`true`), []byte(`true`), []byte(`{"status":"ok"}`), nil, nil, nil, false, nil, nil, nil, nil)) + WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata", "group_sync_enabled"}). + AddRow(true, false, true, []byte(`true`), []byte(`true`), []byte(`{"status":"ok"}`), nil, nil, nil, false, nil, nil, nil, nil, nil)) mock.ExpectExec(`(?s)UPDATE .*accounts.*SET.*WHERE .*id.*`). WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectQuery(`(?s)SELECT .* FROM "accounts" WHERE "id" = \$1`). @@ -398,7 +398,7 @@ func TestUpdateWithAccountBillingSettingsRollsBackWhenOutboxFails(t *testing.T) } probeDisabled := false - err = repo.UpdateWithAccountBillingSettings(context.Background(), account, &probeDisabled, nil, nil) + err = repo.UpdateWithAccountBillingSettings(context.Background(), account, service.AccountBillingSettingsUpdate{ProbeEnabled: &probeDisabled}) require.EqualError(t, err, "outbox failed") require.Equal(t, false, account.Extra[service.UpstreamBillingProbeEnabledExtraKey]) diff --git a/backend/internal/repository/upstream_billing_probe_persistence_integration_test.go b/backend/internal/repository/upstream_billing_probe_persistence_integration_test.go index 6e7631ac0e..8f88bb77bb 100644 --- a/backend/internal/repository/upstream_billing_probe_persistence_integration_test.go +++ b/backend/internal/repository/upstream_billing_probe_persistence_integration_test.go @@ -30,7 +30,7 @@ func TestAccountUpdatePreservesConcurrentProbeSnapshot(t *testing.T) { require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, stale, &service.UpstreamBillingProbeSnapshot{ Status: service.UpstreamBillingProbeStatusOK, LastAttemptAt: time.Now().UTC(), - }, nil)) + }, nil, service.BillingGroupInfo{})) stale.Name = "ordinary-edit" require.NoError(t, repo.Update(ctx, stale)) @@ -72,10 +72,10 @@ func TestAdminAccountEditPreservesRateSynchronizedAfterLoad(t *testing.T) { require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, probeAccount, &service.UpstreamBillingProbeSnapshot{ Status: service.UpstreamBillingProbeStatusOK, LastAttemptAt: time.Now().UTC(), - }, &synchronizedRate)) + }, &synchronizedRate, service.BillingGroupInfo{})) staleAdminEdit.Name = "name-only-edit" - require.NoError(t, repo.UpdateWithAccountBillingSettings(ctx, staleAdminEdit, nil, nil, nil)) + require.NoError(t, repo.UpdateWithAccountBillingSettings(ctx, staleAdminEdit, service.AccountBillingSettingsUpdate{SetName: true})) got, err := repo.GetByID(ctx, account.ID) require.NoError(t, err) @@ -107,7 +107,7 @@ func TestProbeSnapshotSyncsRateOnlyForSuccessfulEnabledAccount(t *testing.T) { require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, loaded, &service.UpstreamBillingProbeSnapshot{ Status: service.UpstreamBillingProbeStatusOK, LastAttemptAt: time.Now().UTC(), - }, &syncedRate)) + }, &syncedRate, service.BillingGroupInfo{})) got, err := repo.GetByID(ctx, account.ID) require.NoError(t, err) @@ -118,7 +118,7 @@ func TestProbeSnapshotSyncsRateOnlyForSuccessfulEnabledAccount(t *testing.T) { require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, got, &service.UpstreamBillingProbeSnapshot{ Status: service.UpstreamBillingProbeStatusFailed, LastAttemptAt: time.Now().UTC(), - }, &failedRate)) + }, &failedRate, service.BillingGroupInfo{})) got, err = repo.GetByID(ctx, account.ID) require.NoError(t, err) require.NotNil(t, got.RateMultiplier) @@ -133,7 +133,7 @@ func TestProbeSnapshotSyncsRateOnlyForSuccessfulEnabledAccount(t *testing.T) { require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, manual, &service.UpstreamBillingProbeSnapshot{ Status: service.UpstreamBillingProbeStatusOK, LastAttemptAt: time.Now().UTC(), - }, &manualProbeRate)) + }, &manualProbeRate, service.BillingGroupInfo{})) got, err = repo.GetByID(ctx, account.ID) require.NoError(t, err) require.NotNil(t, got.RateMultiplier) @@ -148,7 +148,7 @@ func TestProbeSnapshotSyncsRateOnlyForSuccessfulEnabledAccount(t *testing.T) { require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, disabled, &service.UpstreamBillingProbeSnapshot{ Status: service.UpstreamBillingProbeStatusOK, LastAttemptAt: time.Now().UTC(), - }, &manualProbeRate)) + }, &manualProbeRate, service.BillingGroupInfo{})) got, err = repo.GetByID(ctx, account.ID) require.NoError(t, err) require.NotNil(t, got.RateMultiplier) @@ -275,7 +275,7 @@ func TestProbeSnapshotCASIncludesLoadedEnabledState(t *testing.T) { err = repo.UpdateUpstreamBillingProbeSnapshot(ctx, inFlight, &service.UpstreamBillingProbeSnapshot{ Status: service.UpstreamBillingProbeStatusOK, LastAttemptAt: time.Now().UTC(), - }, nil) + }, nil, service.BillingGroupInfo{}) if tt.wantConflict { require.ErrorIs(t, err, service.ErrUpstreamBillingProbeIdentityChanged) } else { @@ -315,13 +315,13 @@ func TestProbeSnapshotCASProtectsManualRateAfterSyncDisabled(t *testing.T) { require.NoError(t, err) manualRate := 0.8 syncDisabled := false - require.NoError(t, repo.UpdateWithAccountBillingSettings(ctx, manual, nil, &syncDisabled, &manualRate)) + require.NoError(t, repo.UpdateWithAccountBillingSettings(ctx, manual, service.AccountBillingSettingsUpdate{RateSyncEnabled: &syncDisabled, RateMultiplier: &manualRate})) probedRate := 0.1 err = repo.UpdateUpstreamBillingProbeSnapshot(ctx, inFlight, &service.UpstreamBillingProbeSnapshot{ Status: service.UpstreamBillingProbeStatusOK, LastAttemptAt: time.Now().UTC(), - }, &probedRate) + }, &probedRate, service.BillingGroupInfo{}) require.ErrorIs(t, err, service.ErrUpstreamBillingProbeIdentityChanged) got, err := repo.GetByID(ctx, account.ID) @@ -398,7 +398,7 @@ func TestProxyIdentityUpdateInvalidatesProbeAndRejectsInFlightSnapshot(t *testin err = accountRepo.UpdateUpstreamBillingProbeSnapshot(ctx, inFlight, &service.UpstreamBillingProbeSnapshot{ Status: service.UpstreamBillingProbeStatusOK, LastAttemptAt: time.Now().UTC(), - }, nil) + }, nil, service.BillingGroupInfo{}) require.ErrorIs(t, err, service.ErrUpstreamBillingProbeIdentityChanged) rows, err := tx.QueryContext(ctx, ` @@ -542,3 +542,36 @@ func latestBulkAccountOutboxPayload(t *testing.T, ctx context.Context, tx sqlQue require.NoError(t, json.Unmarshal(payloadJSON, &payload)) return payload.AccountIDs } + +func TestProbeGroupWriteHonorsDisableDuringRequest(t *testing.T) { + ctx := context.Background() + tx := testEntTx(t) + repo := newAccountRepositoryWithSQL(tx.Client(), tx, nil) + rate, notes := 0.25, "local notes" + account := &service.Account{ + Name: "local", Notes: ¬es, Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Credentials: map[string]any{"api_key": "test-key"}, RateMultiplier: &rate, + Extra: map[string]any{service.UpstreamBillingProbeEnabledExtraKey: true, service.UpstreamBillingGroupSyncEnabledExtraKey: true}, + } + require.NoError(t, repo.Create(ctx, account)) + loaded, err := repo.GetByID(ctx, account.ID) + require.NoError(t, err) + group := service.BillingGroupInfo{Name: "Pro"} + snapshot := &service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK} + require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, loaded, snapshot, nil, group)) + inFlight, err := repo.GetByID(ctx, account.ID) + require.NoError(t, err) + require.Equal(t, "Pro", inFlight.Name) + require.Equal(t, notes, *inFlight.Notes) + require.Equal(t, rate, *inFlight.RateMultiplier) + + disabled := false + require.NoError(t, repo.UpdateWithAccountBillingSettings(ctx, loaded, service.AccountBillingSettingsUpdate{GroupSyncEnabled: &disabled})) + group.Name, group.Description = "too late", "too late" + require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, inFlight, snapshot, nil, group)) + after, err := repo.GetByID(ctx, account.ID) + require.NoError(t, err) + require.Equal(t, "Pro", after.Name) + require.Equal(t, notes, *after.Notes) + require.Equal(t, false, after.Extra[service.UpstreamBillingGroupSyncEnabledExtraKey]) +} diff --git a/backend/internal/server/api_contract_test.go b/backend/internal/server/api_contract_test.go index 6af2658708..0970d7f1fc 100644 --- a/backend/internal/server/api_contract_test.go +++ b/backend/internal/server/api_contract_test.go @@ -1908,9 +1908,7 @@ func (s *stubAccountRepo) Update(ctx context.Context, account *service.Account) func (s *stubAccountRepo) UpdateWithAccountBillingSettings( ctx context.Context, account *service.Account, - probeEnabled *bool, - rateSyncEnabled *bool, - rateMultiplier *float64, + settings service.AccountBillingSettingsUpdate, ) error { return errors.New("not implemented") } diff --git a/backend/internal/server/routes/gateway_key_billing_test.go b/backend/internal/server/routes/gateway_key_billing_test.go index 8581eb4387..1c46dd76b1 100644 --- a/backend/internal/server/routes/gateway_key_billing_test.go +++ b/backend/internal/server/routes/gateway_key_billing_test.go @@ -41,7 +41,7 @@ type keyBillingRouteGroupRepo struct { } func (r *keyBillingRouteGroupRepo) GetByIDLite(_ context.Context, id int64) (*service.Group, error) { - if id != r.group.ID { + if r.group == nil || id != r.group.ID { return nil, service.ErrGroupNotFound } return r.group, nil @@ -56,7 +56,7 @@ func (r *keyBillingRouteRateRepo) GetRPMOverrideByUserAndGroup(context.Context, return nil, nil } -func newKeyBillingRouteTestRouter(runMode string) (*gin.Engine, *keyBillingRouteRateRepo, string) { +func newKeyBillingRouteTestRouter(runMode string, groups service.GroupRepository) (*gin.Engine, *keyBillingRouteRateRepo, string) { gin.SetMode(gin.TestMode) group := &service.Group{ ID: 42, @@ -87,8 +87,11 @@ func newKeyBillingRouteTestRouter(runMode string) (*gin.Engine, *keyBillingRoute } cfg := &config.Config{RunMode: runMode} rateRepo := &keyBillingRouteRateRepo{} + if groups == nil { + groups = &keyBillingRouteGroupRepo{group: group} + } apiKeyService := service.NewAPIKeyService( - &keyBillingRouteAPIKeyRepo{apiKey: apiKey}, nil, &keyBillingRouteGroupRepo{group: group}, nil, rateRepo, nil, cfg, + &keyBillingRouteAPIKeyRepo{apiKey: apiKey}, nil, groups, nil, rateRepo, nil, cfg, ) gatewayService := service.NewGatewayService( nil, nil, nil, nil, nil, nil, rateRepo, nil, cfg, nil, nil, nil, nil, nil, @@ -135,7 +138,7 @@ func TestGatewayRoutesKeyBillingInfoPathIsRegistered(t *testing.T) { func TestGatewayRoutesKeyBillingInfoEndToEnd(t *testing.T) { t.Run("missing credentials", func(t *testing.T) { - router, rateRepo, _ := newKeyBillingRouteTestRouter(config.RunModeStandard) + router, rateRepo, _ := newKeyBillingRouteTestRouter(config.RunModeStandard, nil) w := httptest.NewRecorder() router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/v1/sub2api/billing", nil)) @@ -147,7 +150,7 @@ func TestGatewayRoutesKeyBillingInfoEndToEnd(t *testing.T) { }) t.Run("standard mode", func(t *testing.T) { - router, rateRepo, key := newKeyBillingRouteTestRouter(config.RunModeStandard) + router, rateRepo, key := newKeyBillingRouteTestRouter(config.RunModeStandard, nil) req := httptest.NewRequest(http.MethodGet, "/v1/sub2api/billing", nil) req.Header.Set("Authorization", "Bearer "+key) w := httptest.NewRecorder() @@ -168,7 +171,7 @@ func TestGatewayRoutesKeyBillingInfoEndToEnd(t *testing.T) { }) t.Run("requested group belongs to the calling key", func(t *testing.T) { - router, _, key := newKeyBillingRouteTestRouter(config.RunModeStandard) + router, _, key := newKeyBillingRouteTestRouter(config.RunModeStandard, nil) req := httptest.NewRequest(http.MethodGet, "/v1/sub2api/billing?include=group&group_id=99", nil) req.Header.Set("x-api-key", key) req.Header.Set("Accept-Language", "en") @@ -185,8 +188,21 @@ func TestGatewayRoutesKeyBillingInfoEndToEnd(t *testing.T) { require.NotContains(t, w.Body.String(), key) }) + t.Run("optional group lookup failure preserves billing rates", func(t *testing.T) { + router, _, key := newKeyBillingRouteTestRouter(config.RunModeStandard, &keyBillingRouteGroupRepo{}) + req := httptest.NewRequest(http.MethodGet, "/v1/sub2api/billing?include=group", nil) + req.Header.Set("x-api-key", key) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + require.Equal(t, http.StatusOK, w.Code) + var body map[string]any + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body)) + require.Equal(t, 0.75, body["effective_rate_multiplier"]) + require.NotContains(t, body, "group_name") + }) + t.Run("simple mode", func(t *testing.T) { - router, rateRepo, key := newKeyBillingRouteTestRouter(config.RunModeSimple) + router, rateRepo, key := newKeyBillingRouteTestRouter(config.RunModeSimple, nil) req := httptest.NewRequest(http.MethodGet, "/v1/sub2api/billing", nil) req.Header.Set("x-api-key", key) w := httptest.NewRecorder() diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go index 541d6abd77..0d2ff14ce1 100644 --- a/backend/internal/service/account_service.go +++ b/backend/internal/service/account_service.go @@ -136,17 +136,16 @@ type AccountDuplicateRepository interface { CreateWithAccountGroups(ctx context.Context, account *Account, groups []AccountGroup) error } -// AccountBillingSettingsRepository applies an admin edit without overwriting a -// rate_multiplier that a successful upstream probe synchronized after the edit -// form was loaded. A nil rateMultiplier means the request did not edit it. +// AccountBillingSettingsUpdate carries explicit edits to fields shared with the billing probe. +// Omitted fields retain the values in the locked row. +type AccountBillingSettingsUpdate struct { + ProbeEnabled, RateSyncEnabled, GroupSyncEnabled *bool + RateMultiplier *float64 + SetName, SetNotes bool +} + type AccountBillingSettingsRepository interface { - UpdateWithAccountBillingSettings( - ctx context.Context, - account *Account, - probeEnabled *bool, - rateSyncEnabled *bool, - rateMultiplier *float64, - ) error + UpdateWithAccountBillingSettings(context.Context, *Account, AccountBillingSettingsUpdate) error } // AdminAccountRepository makes the account-duplication write capability an explicit diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go index 0521f7a90b..3649f5e11d 100644 --- a/backend/internal/service/admin_account.go +++ b/backend/internal/service/admin_account.go @@ -100,6 +100,8 @@ func cloneAccountJSONMap(value map[string]any) (map[string]any, error) { var duplicateAccountDiscardedExtraKeys = map[string]struct{}{ // A retry identity belongs to the operation that created one copy, not to later copies. duplicateAccountOperationIDExtraKey: {}, + // Keep the copy's local name until its administrator opts into group sync. + UpstreamBillingGroupSyncEnabledExtraKey: {}, // External sync identity belongs to one local account only. "crs_account_id": {}, "crs_kind": {}, @@ -414,9 +416,10 @@ func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]an if input.Platform == PlatformTypeSafe && input.Type != AccountTypeAPIKey { return nil, errors.New("typesafe accounts only support apikey credentials") } - // Probe/session state is system-managed. New accounts always start with automatic refresh disabled. + // Probe/session state is system-managed. Only explicit account settings can enable it. delete(accountExtra, UpstreamBillingProbeEnabledExtraKey) delete(accountExtra, UpstreamBillingRateSyncEnabledExtraKey) + delete(accountExtra, UpstreamBillingGroupSyncEnabledExtraKey) delete(accountExtra, UpstreamBillingProbeExtraKey) delete(accountExtra, OllamaCloudUsageSessionExtraKey) delete(accountExtra, OllamaCloudUsageAutoRefreshExtraKey) @@ -437,7 +440,11 @@ func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]an Status: StatusActive, Schedulable: true, } - if input.ProbeEnabled != nil && *input.ProbeEnabled { + groupSync := input.GroupSyncEnabled != nil && *input.GroupSyncEnabled + if groupSync && input.ProbeEnabled != nil && !*input.ProbeEnabled { + return nil, ErrUpstreamBillingGroupSyncRequiresProbe + } + if groupSync || (input.ProbeEnabled != nil && *input.ProbeEnabled) { if !isUpstreamBillingProbeAccount(account) { return nil, ErrUpstreamBillingProbeAccountInvalid } @@ -445,6 +452,9 @@ func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]an account.Extra = make(map[string]any) } account.Extra[UpstreamBillingProbeEnabledExtraKey] = true + if groupSync { + account.Extra[UpstreamBillingGroupSyncEnabledExtraKey] = true + } } // 预计算固定时间重置的下次重置时间 if account.Extra != nil { @@ -667,6 +677,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U // 关闭配额限制时前端会删除 quota_* 键并提交 extra:{},此时也必须落库。 requestedProbeEnabledUpdate := input.ProbeEnabled requestedRateSyncEnabledUpdate := input.RateSyncEnabled + groupSyncUpdate := input.GroupSyncEnabled if input.Extra != nil { requestedProbeEnabled, hasRequestedProbeEnabled := normalizedExtra[UpstreamBillingProbeEnabledExtraKey] if hasRequestedProbeEnabled { @@ -681,6 +692,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U } delete(normalizedExtra, UpstreamBillingProbeEnabledExtraKey) delete(normalizedExtra, UpstreamBillingRateSyncEnabledExtraKey) + delete(normalizedExtra, UpstreamBillingGroupSyncEnabledExtraKey) delete(normalizedExtra, UpstreamBillingProbeExtraKey) delete(normalizedExtra, OllamaCloudUsageSessionExtraKey) delete(normalizedExtra, OllamaCloudUsageAutoRefreshExtraKey) @@ -702,6 +714,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U UpstreamModelMetadataExtraKey, UpstreamBillingProbeEnabledExtraKey, UpstreamBillingRateSyncEnabledExtraKey, + UpstreamBillingGroupSyncEnabledExtraKey, UpstreamBillingProbeExtraKey, OllamaCloudUsageSessionExtraKey, OllamaCloudUsageAutoRefreshExtraKey, @@ -737,6 +750,12 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U if input.Extra == nil { account.Extra = prepareCodexFingerprintExtraForUpdate(account, account.Extra) } + if groupSyncUpdate != nil && *groupSyncUpdate { + if requestedProbeEnabledUpdate != nil && !*requestedProbeEnabledUpdate { + return nil, ErrUpstreamBillingGroupSyncRequiresProbe + } + requestedProbeEnabledUpdate = groupSyncUpdate + } if requestedRateSyncEnabledUpdate != nil && *requestedRateSyncEnabledUpdate { if requestedProbeEnabledUpdate != nil && !*requestedProbeEnabledUpdate { return nil, infraerrors.BadRequest( @@ -750,6 +769,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U if requestedProbeEnabledUpdate != nil && !*requestedProbeEnabledUpdate { disabled := false requestedRateSyncEnabledUpdate = &disabled + groupSyncUpdate = &disabled } if (requestedProbeEnabledUpdate != nil && *requestedProbeEnabledUpdate) || (requestedRateSyncEnabledUpdate != nil && *requestedRateSyncEnabledUpdate) { @@ -757,7 +777,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U return nil, ErrUpstreamBillingProbeAccountInvalid } } - if account.Extra == nil && (requestedProbeEnabledUpdate != nil || requestedRateSyncEnabledUpdate != nil) { + if account.Extra == nil && (requestedProbeEnabledUpdate != nil || requestedRateSyncEnabledUpdate != nil || groupSyncUpdate != nil) { account.Extra = make(map[string]any) } if requestedProbeEnabledUpdate != nil { @@ -766,6 +786,9 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U if requestedRateSyncEnabledUpdate != nil { account.Extra[UpstreamBillingRateSyncEnabledExtraKey] = *requestedRateSyncEnabledUpdate } + if groupSyncUpdate != nil { + account.Extra[UpstreamBillingGroupSyncEnabledExtraKey] = *groupSyncUpdate + } // 影子代理恒继承母账号(由 propagateProxyToShadows 同步),不接受独立编辑——外审 B/P1; // 否则要等母账号下次改 proxy 才被覆盖,期间影子会出现"有时继承、有时独立"的漂移。 if input.ProxyID != nil && !account.IsCredentialShadow() { @@ -782,6 +805,7 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U if !isUpstreamBillingProbeAccount(account) { delete(account.Extra, UpstreamBillingProbeEnabledExtraKey) delete(account.Extra, UpstreamBillingRateSyncEnabledExtraKey) + delete(account.Extra, UpstreamBillingGroupSyncEnabledExtraKey) } } if account.Extra != nil { @@ -878,11 +902,11 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U } if updater != nil { if err := updater.UpdateWithAccountBillingSettings( - ctx, - account, - requestedProbeEnabledUpdate, - requestedRateSyncEnabledUpdate, - input.RateMultiplier, + ctx, account, AccountBillingSettingsUpdate{ + ProbeEnabled: requestedProbeEnabledUpdate, RateSyncEnabled: requestedRateSyncEnabledUpdate, + GroupSyncEnabled: groupSyncUpdate, RateMultiplier: input.RateMultiplier, + SetName: input.Name != "", SetNotes: input.Notes != nil, + }, ); err != nil { return nil, err } @@ -892,15 +916,18 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U if err := s.accountRepo.Update(ctx, account); err != nil { return nil, err } - if (requestedProbeEnabledUpdate != nil || requestedRateSyncEnabledUpdate != nil) && + if (requestedProbeEnabledUpdate != nil || requestedRateSyncEnabledUpdate != nil || groupSyncUpdate != nil) && isUpstreamBillingProbeAccount(account) { - settings := make(map[string]any, 2) + settings := make(map[string]any, 3) if requestedProbeEnabledUpdate != nil { settings[UpstreamBillingProbeEnabledExtraKey] = *requestedProbeEnabledUpdate } if requestedRateSyncEnabledUpdate != nil { settings[UpstreamBillingRateSyncEnabledExtraKey] = *requestedRateSyncEnabledUpdate } + if groupSyncUpdate != nil { + settings[UpstreamBillingGroupSyncEnabledExtraKey] = *groupSyncUpdate + } if err := s.accountRepo.UpdateExtra(ctx, account.ID, settings); err != nil { return nil, err } @@ -937,6 +964,7 @@ func (s *adminServiceImpl) UpdateAccountExtra(ctx context.Context, id int64, upd updates = stripOpenAIAutoResetCreditManagedExtra(updates, true) delete(updates, UpstreamBillingProbeEnabledExtraKey) delete(updates, UpstreamBillingRateSyncEnabledExtraKey) + delete(updates, UpstreamBillingGroupSyncEnabledExtraKey) delete(updates, UpstreamBillingProbeExtraKey) delete(updates, OllamaCloudUsageSessionExtraKey) delete(updates, OllamaCloudUsageAutoRefreshExtraKey) @@ -966,6 +994,7 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp input.Extra = stripOpenAIAutoResetCreditManagedExtra(input.Extra, true) delete(input.Extra, UpstreamBillingProbeEnabledExtraKey) delete(input.Extra, UpstreamBillingRateSyncEnabledExtraKey) + delete(input.Extra, UpstreamBillingGroupSyncEnabledExtraKey) delete(input.Extra, UpstreamBillingProbeExtraKey) delete(input.Extra, OllamaCloudUsageSessionExtraKey) delete(input.Extra, OllamaCloudUsageAutoRefreshExtraKey) @@ -1132,6 +1161,7 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp repoUpdates.Extra[UpstreamBillingProbeEnabledExtraKey] = *input.ProbeEnabled if !*input.ProbeEnabled { repoUpdates.Extra[UpstreamBillingRateSyncEnabledExtraKey] = false + repoUpdates.Extra[UpstreamBillingGroupSyncEnabledExtraKey] = false } } if updatesUpstreamBillingProbeIdentity(input.Credentials) || input.ProxyID != nil { diff --git a/backend/internal/service/admin_account_upstream_billing_probe_test.go b/backend/internal/service/admin_account_upstream_billing_probe_test.go index 42988062c3..69b4e3e04c 100644 --- a/backend/internal/service/admin_account_upstream_billing_probe_test.go +++ b/backend/internal/service/admin_account_upstream_billing_probe_test.go @@ -28,9 +28,7 @@ type accountBillingSettingsAdminRepo struct { func (r *accountBillingSettingsAdminRepo) UpdateWithAccountBillingSettings( _ context.Context, account *Account, - probeEnabled *bool, - rateSyncEnabled *bool, - rateMultiplier *float64, + settings AccountBillingSettingsUpdate, ) error { r.mu.Lock() defer r.mu.Unlock() @@ -45,15 +43,15 @@ func (r *accountBillingSettingsAdminRepo) UpdateWithAccountBillingSettings( if updated.Extra == nil { updated.Extra = make(map[string]any) } - if probeEnabled != nil { - updated.Extra[UpstreamBillingProbeEnabledExtraKey] = *probeEnabled + if settings.ProbeEnabled != nil { + updated.Extra[UpstreamBillingProbeEnabledExtraKey] = *settings.ProbeEnabled } - if rateSyncEnabled != nil { - updated.Extra[UpstreamBillingRateSyncEnabledExtraKey] = *rateSyncEnabled + if settings.RateSyncEnabled != nil { + updated.Extra[UpstreamBillingRateSyncEnabledExtraKey] = *settings.RateSyncEnabled } switch { - case rateMultiplier != nil: - value := *rateMultiplier + case settings.RateMultiplier != nil: + value := *settings.RateMultiplier updated.RateMultiplier = &value r.lastExplicitRate = &value case r.concurrentRate != nil: @@ -913,3 +911,23 @@ func TestCreateAccountDropsOpenCodeGoManagedKeys(t *testing.T) { require.NotContains(t, created.Extra, OpenCodeGoUsageSnapshotExtraKey) require.Equal(t, "value", created.Extra["custom"]) } + +func TestCreateAccountGroupSyncIsExplicitAndEnablesOnlyTheProbe(t *testing.T) { + enabled, disabled := true, false + input := &CreateAccountInput{Platform: PlatformOpenAI, Type: AccountTypeAPIKey} + account, err := buildAccountForCreate(input, map[string]any{UpstreamBillingGroupSyncEnabledExtraKey: true}) + require.NoError(t, err) + require.NotContains(t, account.Extra, UpstreamBillingGroupSyncEnabledExtraKey) + input.GroupSyncEnabled = &enabled + account, err = buildAccountForCreate(input, nil) + require.NoError(t, err) + require.True(t, upstreamBillingProbeEnabled(account)) + require.Equal(t, true, account.Extra[UpstreamBillingGroupSyncEnabledExtraKey]) + require.False(t, upstreamBillingRateSyncEnabled(account)) + copyExtra, err := duplicateAccountExtra(account.Extra) + require.NoError(t, err) + require.NotContains(t, copyExtra, UpstreamBillingGroupSyncEnabledExtraKey) + input.ProbeEnabled = &disabled + _, err = buildAccountForCreate(input, nil) + require.ErrorIs(t, err, ErrUpstreamBillingGroupSyncRequiresProbe) +} diff --git a/backend/internal/service/admin_service.go b/backend/internal/service/admin_service.go index 5a8b764e1d..87f4ffe5c9 100644 --- a/backend/internal/service/admin_service.go +++ b/backend/internal/service/admin_service.go @@ -420,6 +420,7 @@ type CreateAccountInput struct { ExpiresAt *int64 AutoPauseOnExpired *bool ProbeEnabled *bool + GroupSyncEnabled *bool // SkipDefaultGroupBind prevents auto-binding to platform default group when GroupIDs is empty. SkipDefaultGroupBind bool // SkipMixedChannelCheck skips the mixed channel risk check when binding groups. @@ -453,6 +454,7 @@ type UpdateAccountInput struct { ExpiresAt *int64 AutoPauseOnExpired *bool ProbeEnabled *bool + GroupSyncEnabled *bool RateSyncEnabled *bool SkipMixedChannelCheck bool // 跳过混合渠道检查(用户已确认风险) } diff --git a/backend/internal/service/crs_sync_service.go b/backend/internal/service/crs_sync_service.go index e5a72b4c44..77df6d33c1 100644 --- a/backend/internal/service/crs_sync_service.go +++ b/backend/internal/service/crs_sync_service.go @@ -1163,6 +1163,7 @@ func reconcileCRSUpstreamBillingProbeExtra( for _, key := range []string{ UpstreamBillingProbeEnabledExtraKey, UpstreamBillingRateSyncEnabledExtraKey, + UpstreamBillingGroupSyncEnabledExtraKey, UpstreamBillingProbeExtraKey, OllamaCloudUsageSessionExtraKey, OllamaCloudUsageAutoRefreshExtraKey, @@ -1180,8 +1181,10 @@ func reconcileCRSUpstreamBillingProbeExtra( extra[UpstreamBillingProbeEnabledExtraKey] = enabled probeEnabled, _ = enabled.(bool) } - if enabled, ok := existing.Extra[UpstreamBillingRateSyncEnabledExtraKey].(bool); ok { - extra[UpstreamBillingRateSyncEnabledExtraKey] = enabled && probeEnabled + for _, key := range []string{UpstreamBillingRateSyncEnabledExtraKey, UpstreamBillingGroupSyncEnabledExtraKey} { + if enabled, ok := existing.Extra[key].(bool); ok { + extra[key] = enabled && probeEnabled + } } if reflect.DeepEqual(upstreamBillingProbeIdentity(existing), upstreamBillingProbeIdentity(target)) { if snapshot, ok := existing.Extra[UpstreamBillingProbeExtraKey]; ok { diff --git a/backend/internal/service/upstream_billing_probe.go b/backend/internal/service/upstream_billing_probe.go index ea68260575..7f8982eeea 100644 --- a/backend/internal/service/upstream_billing_probe.go +++ b/backend/internal/service/upstream_billing_probe.go @@ -23,15 +23,17 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" "github.com/google/uuid" + "github.com/tidwall/gjson" "golang.org/x/sync/errgroup" "golang.org/x/sync/singleflight" ) const ( // These values live in accounts.extra so PR2 does not require a schema migration. - UpstreamBillingProbeExtraKey = "upstream_billing_probe" - UpstreamBillingProbeEnabledExtraKey = "upstream_billing_probe_enabled" - UpstreamBillingRateSyncEnabledExtraKey = "upstream_billing_rate_sync_enabled" + UpstreamBillingProbeExtraKey = "upstream_billing_probe" + UpstreamBillingProbeEnabledExtraKey = "upstream_billing_probe_enabled" + UpstreamBillingRateSyncEnabledExtraKey = "upstream_billing_rate_sync_enabled" + UpstreamBillingGroupSyncEnabledExtraKey = "upstream_billing_group_sync_enabled" upstreamBillingProbeDefaultIntervalMinutes = 30 upstreamBillingProbeMinIntervalMinutes = 5 @@ -70,7 +72,8 @@ const UpstreamBillingProbeMaxBatchSize = upstreamBillingProbeMaxPerCycle const upstreamBillingRateSyncMaxMultiplier = 100.0 var ( - ErrUpstreamBillingProbeUnavailable = infraerrors.ServiceUnavailable( + ErrUpstreamBillingGroupSyncRequiresProbe = infraerrors.BadRequest("UPSTREAM_BILLING_GROUP_SYNC_REQUIRES_PROBE", "upstream group sync requires upstream billing probe") + ErrUpstreamBillingProbeUnavailable = infraerrors.ServiceUnavailable( "UPSTREAM_BILLING_PROBE_UNAVAILABLE", "upstream billing probe is unavailable", ) ErrUpstreamBillingProbeAccountInvalid = infraerrors.BadRequest( @@ -258,7 +261,7 @@ type UpstreamBillingProbeService struct { } type upstreamBillingProbeSnapshotWriter interface { - UpdateUpstreamBillingProbeSnapshot(context.Context, *Account, *UpstreamBillingProbeSnapshot, *float64) error + UpdateUpstreamBillingProbeSnapshot(context.Context, *Account, *UpstreamBillingProbeSnapshot, *float64, BillingGroupInfo) error } type upstreamBillingProbeDueAccountLister interface { @@ -610,11 +613,11 @@ func (s *UpstreamBillingProbeService) SetAccountEnabled(ctx context.Context, acc updates := map[string]any{UpstreamBillingProbeEnabledExtraKey: enabled} if !enabled { updates[UpstreamBillingRateSyncEnabledExtraKey] = false + updates[UpstreamBillingGroupSyncEnabledExtraKey] = false } return s.accountRepo.UpdateExtra(ctx, accountID, updates) } -// The probe persists rates, while the account form only reads display text. type upstreamBillingReply struct { body []byte status int @@ -732,7 +735,6 @@ func (s *UpstreamBillingProbeService) PreviewGroup(ctx context.Context, account return nil, infraerrors.New(http.StatusBadGateway, "UPSTREAM_GROUP_PREVIEW_FAILED", "Could not read group information from the upstream") } var info struct { - BillingGroupInfo Object string `json:"object"` SchemaVersion int `json:"schema_version"` BillingScope string `json:"billing_scope"` @@ -740,12 +742,31 @@ func (s *UpstreamBillingProbeService) PreviewGroup(ctx context.Context, account if json.Unmarshal(reply.body, &info) != nil || info.Object != "sub2api.key_billing" || info.SchemaVersion != 1 || info.BillingScope != "token" { return nil, infraerrors.New(http.StatusBadGateway, "UPSTREAM_GROUP_PREVIEW_INVALID", "Invalid upstream billing response") } - return &info.BillingGroupInfo, nil + group := upstreamBillingGroupInfo(reply.body) + return &group, nil +} + +// Treat each optional text field independently so an invalid field cannot block rate updates. +func upstreamBillingGroupInfo(body []byte) BillingGroupInfo { + text := func(key string) string { + value := gjson.GetBytes(body, key) + if value.Type != gjson.String || strings.ContainsRune(value.Str, 0) { + return "" + } + return strings.TrimSpace(value.Str) + } + name := text("group_name") + if len(name) > 100 { // accounts.name uses Ent MaxLen(100). + name = "" + } + return BillingGroupInfo{Name: name, Description: text("group_description")} } func (s *UpstreamBillingProbeService) probeLoadedAccount(ctx context.Context, account *Account, intervalMinutes int) (*UpstreamBillingProbeSnapshot, error) { now := s.currentTime().UTC() - reply, err := s.fetchBilling(ctx, account, false, now) + groupSync, _ := account.Extra[UpstreamBillingGroupSyncEnabledExtraKey].(bool) + includeGroup := groupSync && upstreamBillingProbeEnabled(account) + reply, err := s.fetchBilling(ctx, account, includeGroup, now) if errors.Is(err, ErrUpstreamBillingProbeIdentityChanged) { return nil, err } @@ -785,7 +806,11 @@ func (s *UpstreamBillingProbeService) probeLoadedAccount(ctx context.Context, ac ) } } - if err := s.updateSnapshot(ctx, account, snapshot, syncRate); err != nil { + var group BillingGroupInfo + if includeGroup { + group = upstreamBillingGroupInfo(reply.body) + } + if err := s.updateSnapshot(ctx, account, snapshot, syncRate, group); err != nil { return nil, err } if syncRate != nil { @@ -837,7 +862,7 @@ func (s *UpstreamBillingProbeService) persistProbeFailure( snapshot.FreshUntil = probeTimePtr(previous.ReceivedAt.Add(2 * time.Duration(intervalMinutes) * time.Minute)) } } - if err := s.updateSnapshot(ctx, account, snapshot, nil); err != nil { + if err := s.updateSnapshot(ctx, account, snapshot, nil, BillingGroupInfo{}); err != nil { return nil, err } return snapshot, nil @@ -848,12 +873,13 @@ func (s *UpstreamBillingProbeService) updateSnapshot( account *Account, snapshot *UpstreamBillingProbeSnapshot, rateMultiplier *float64, + group BillingGroupInfo, ) error { writer, ok := s.accountRepo.(upstreamBillingProbeSnapshotWriter) if !ok { return ErrUpstreamBillingProbeUnavailable } - return writer.UpdateUpstreamBillingProbeSnapshot(ctx, account, snapshot, rateMultiplier) + return writer.UpdateUpstreamBillingProbeSnapshot(ctx, account, snapshot, rateMultiplier, group) } func parseUpstreamBillingProbeResponse(body []byte) (map[string]any, error) { diff --git a/backend/internal/service/upstream_billing_probe_test.go b/backend/internal/service/upstream_billing_probe_test.go index 68df096efe..670fc9b58d 100644 --- a/backend/internal/service/upstream_billing_probe_test.go +++ b/backend/internal/service/upstream_billing_probe_test.go @@ -115,6 +115,7 @@ func (r *upstreamBillingProbeAccountRepo) UpdateUpstreamBillingProbeSnapshot( expected *Account, snapshot *UpstreamBillingProbeSnapshot, rateMultiplier *float64, + group BillingGroupInfo, ) error { r.mu.Lock() defer r.mu.Unlock() @@ -126,6 +127,12 @@ func (r *upstreamBillingProbeAccountRepo) UpdateUpstreamBillingProbeSnapshot( account.Extra = make(map[string]any) } account.Extra[UpstreamBillingProbeExtraKey] = snapshot + if group.Name != "" { + account.Name = group.Name + } + if group.Description != "" { + account.Notes = &group.Description + } if snapshot.Status == UpstreamBillingProbeStatusOK && rateMultiplier != nil && upstreamBillingRateSyncEnabled(account) { @@ -1302,3 +1309,44 @@ func TestUpstreamBillingProbeLeaderLockCoversStaggeredInstancesInCadenceWindow(t require.NoError(t, staggered.RunDue(context.Background())) require.Equal(t, int64(1), upstream.calls.Load(), "a staggered instance must not start a second batch inside the cadence window") } + +func TestUpstreamBillingGroupSyncSharesOneProbeAndPreservesLocalFields(t *testing.T) { + for _, tt := range []struct { + name string + groupSync, rateSync bool + fields, wantName, wantNotes string + wantRate float64 + }{ + {"group only", true, false, `"group_name":"Pro","group_description":"shared"`, "Pro", "shared", 1}, + {"both with blank notes", true, true, `"group_name":"Pro","group_description":" "`, "Pro", "local notes", 0.5}, + {"invalid name", true, true, `"group_name":12,"group_description":"shared"`, "local", "shared", 0.5}, + {"old upstream", true, true, `"unrelated":true`, "local", "local notes", 0.5}, + {"rate only", false, true, `"group_name":"Pro","group_description":"shared"`, "local", "local notes", 0.5}, + } { + t.Run(tt.name, func(t *testing.T) { + rate, notes := 1.0, "local notes" + account := &Account{ + ID: 17, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, + Name: "local", Notes: ¬es, RateMultiplier: &rate, + Credentials: map[string]any{"api_key": "key", "base_url": "https://upstream.example"}, + Extra: map[string]any{ + UpstreamBillingProbeEnabledExtraKey: true, + UpstreamBillingGroupSyncEnabledExtraKey: tt.groupSync, + UpstreamBillingRateSyncEnabledExtraKey: tt.rateSync, + }, + } + body := `{"object":"sub2api.key_billing","schema_version":1,"billing_scope":"token","group_rate_multiplier":0.5,"resolved_rate_multiplier":0.5,"effective_rate_multiplier":0.5,"peak_rate_enabled":false,"observed_at":"2026-07-13T01:00:00Z",` + tt.fields + "}" + upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body))}} + repo := &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{account.ID: account}} + svc := newUpstreamBillingProbeTestService(repo, upstream, &upstreamBillingProbeSettingRepo{}) + snapshot, err := svc.probeScheduledAccount(context.Background(), account.ID, 30) + require.NoError(t, err) + require.Equal(t, UpstreamBillingProbeStatusOK, snapshot.Status) + require.Len(t, upstream.requests, 1) + require.Equal(t, tt.groupSync, upstream.lastReq.URL.Query().Get("include") == "group") + require.Equal(t, tt.wantName, account.Name) + require.Equal(t, tt.wantNotes, *account.Notes) + require.Equal(t, tt.wantRate, *account.RateMultiplier) + }) + } +} diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index 96c7934a47..297bb0a4e1 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -53,6 +53,9 @@ v-model:name="form.name" v-model:notes="form.notes" :source="upstreamGroupSource" + allow-auto + :auto="upstreamGroupSyncEnabled" + @update:auto="setUpstreamGroupSync" /> +

+ {{ t('admin.accounts.upstreamBilling.autoSyncGroupHint') }} +

@@ -4433,7 +4439,15 @@ const accountCategory = ref<'oauth-based' | 'apikey' | 'bedrock' | 'service_acco const addMethod = ref('oauth') // For oauth-based: 'oauth' or 'setup-token' const apiKeyBaseUrl = ref('https://api.anthropic.com') const apiKeyValue = ref('') +const upstreamGroupSyncEnabled = ref(false) +function setUpstreamGroupSync(enabled: boolean) { + upstreamGroupSyncEnabled.value = enabled + if (enabled) upstreamBillingAutoProbeEnabled.value = true +} const upstreamBillingAutoProbeEnabled = ref(true) +watch(upstreamBillingAutoProbeEnabled, (enabled) => { + if (!enabled) upstreamGroupSyncEnabled.value = false +}) // ── 国产供应商(Kimi / Zhipu / DeepSeek)账号类型、API 协议与端点 ── // 多协议供应商(国产厂商与走通用表单的供应商)的接入模式;OpenCode 用 openCodeAccountMode。 @@ -5687,6 +5701,7 @@ const resetForm = () => { apiKeyValue.value = '' upstreamRequestIdHeader.value = '' upstreamBillingAutoProbeEnabled.value = true + upstreamGroupSyncEnabled.value = false editQuotaLimit.value = null editQuotaDailyLimit.value = null editQuotaWeeklyLimit.value = null @@ -6285,6 +6300,7 @@ const handleSubmit = async () => { group_ids: form.group_ids, extra: withUpstreamRequestIdHeader(extra), upstream_billing_probe_enabled: upstreamBillingAutoProbeEnabled.value, + upstream_billing_group_sync_enabled: upstreamGroupSyncEnabled.value, auto_pause_on_expired: autoPauseOnExpired.value }) } @@ -6416,6 +6432,7 @@ const createAccountAndFinish = async ( // 上游倍率探测对全部 API-key 平台开放(antigravity upstream 走本 helper); // 非 apikey 类型(bedrock/oauth)不传,后端不动作。 upstream_billing_probe_enabled: type === 'apikey' ? upstreamBillingAutoProbeEnabled.value : undefined, + upstream_billing_group_sync_enabled: type === 'apikey' ? upstreamGroupSyncEnabled.value : undefined, auto_pause_on_expired: autoPauseOnExpired.value }) } diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index 4fb7dca38c..7585061d05 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -19,9 +19,15 @@ v-model:name="form.name" v-model:notes="form.notes" :source="upstreamGroupSource" + :allow-auto="account.type === 'apikey'" + :auto="upstreamGroupSyncEnabled" + @update:auto="setUpstreamGroupSync" />
+

+ {{ t('admin.accounts.upstreamBilling.autoSyncGroupHint') }} +

@@ -4119,6 +4125,11 @@ const autoPause7dDisabled = ref(false) const autoResetCreditEnabled = ref(false) const autoResetCredit5hThreshold = ref(100) const autoResetCredit7dThreshold = ref(100) +const upstreamGroupSyncEnabled = ref(false) +function setUpstreamGroupSync(enabled: boolean) { + upstreamGroupSyncEnabled.value = enabled + if (enabled) upstreamBillingAutoProbeEnabled.value = true +} const upstreamBillingAutoProbeEnabled = ref(false) const upstreamBillingRateSyncEnabled = ref(false) const mixedScheduling = ref(false) // For antigravity accounts: enable mixed scheduling @@ -4569,6 +4580,7 @@ const handleUpstreamBillingAutoProbeChange = (enabled: boolean) => { upstreamBillingAutoProbeEnabled.value = enabled if (!enabled) { upstreamBillingRateSyncEnabled.value = false + upstreamGroupSyncEnabled.value = false } } @@ -4701,6 +4713,8 @@ const syncFormFromAccount = (newAccount: Account | null) => { autoResetCredit7dThreshold.value = typeof extra?.auto_reset_credit_7d_threshold === 'number' ? extra.auto_reset_credit_7d_threshold * 100 : 100 upstreamBillingAutoProbeEnabled.value = extra?.upstream_billing_probe_enabled === true + upstreamGroupSyncEnabled.value = + upstreamBillingAutoProbeEnabled.value && extra?.upstream_billing_group_sync_enabled === true upstreamBillingRateSyncEnabled.value = upstreamBillingAutoProbeEnabled.value && extra?.upstream_billing_rate_sync_enabled === true @@ -5720,6 +5734,9 @@ const handleSubmit = async () => { } updatePayload.auto_pause_on_expired = autoPauseOnExpired.value if (props.account.type === 'apikey') { + if (form.name === props.account.name) delete updatePayload.name + if (form.notes === (props.account.notes || '')) delete updatePayload.notes + updatePayload.upstream_billing_group_sync_enabled = upstreamGroupSyncEnabled.value updatePayload.upstream_billing_probe_enabled = upstreamBillingAutoProbeEnabled.value updatePayload.upstream_billing_rate_sync_enabled = upstreamBillingRateSyncEnabled.value if (upstreamBillingRateSyncEnabled.value) { @@ -6397,6 +6414,7 @@ const handleSubmit = async () => { if (props.account.type === 'apikey') { delete newExtra.upstream_billing_probe_enabled delete newExtra.upstream_billing_rate_sync_enabled + delete newExtra.upstream_billing_group_sync_enabled } // Total quota if (editQuotaLimit.value != null && editQuotaLimit.value > 0) { diff --git a/frontend/src/components/account/UpstreamGroupSyncButton.vue b/frontend/src/components/account/UpstreamGroupSyncButton.vue index 06c6356e61..357b9a8783 100644 --- a/frontend/src/components/account/UpstreamGroupSyncButton.vue +++ b/frontend/src/components/account/UpstreamGroupSyncButton.vue @@ -1,14 +1,22 @@