diff --git a/backend/internal/application/gateway/image.go b/backend/internal/application/gateway/image.go index ff2594df..ea96c65c 100644 --- a/backend/internal/application/gateway/image.go +++ b/backend/internal/application/gateway/image.go @@ -306,7 +306,7 @@ func (s *Service) executeImage( } } quotaKind, _ := s.providers.QuotaKind(route.Provider) - refreshMode, decrementMode := imageQuotaFinalizationModes(effectiveQuotaMode, quotaRefreshGroup) + refreshMode, decrementMode := quotaFinalizationModes(effectiveQuotaMode, quotaRefreshGroup) if successful && quotaKind == provider.QuotaRemoteWindow && refreshMode != "" { if decrementMode != "" && decrementMode != "weekly" { units := max(1, response.QuotaUnits) @@ -335,12 +335,12 @@ func (s *Service) executeImage( return &Result{StatusCode: response.StatusCode, Status: response.Status, Header: response.Header, Body: &finalizingBody{ReadCloser: response.Body, finalize: func() { finalize(Usage{}, "", "stream_closed") }}, Finalize: finalize}, nil } -// imageQuotaFinalizationModes separates the immediate local consumption fence -// from the authoritative provider refresh. A refresh group may update several +// quotaFinalizationModes separates the immediate local consumption fence from +// the authoritative provider refresh. A refresh group may update several // upstream windows atomically, while the local fence must charge the exact -// window selected for this account so concurrent requests cannot over-allocate -// during the short refresh delay. -func imageQuotaFinalizationModes(effectiveMode, refreshGroup string) (refreshMode, decrementMode string) { +// window selected for this account so concurrent media requests cannot +// over-allocate during the short refresh delay. +func quotaFinalizationModes(effectiveMode, refreshGroup string) (refreshMode, decrementMode string) { refreshMode = effectiveMode if refreshGroup != "" { refreshMode = refreshGroup diff --git a/backend/internal/application/gateway/selector.go b/backend/internal/application/gateway/selector.go index e68d4ef7..98d168f4 100644 --- a/backend/internal/application/gateway/selector.go +++ b/backend/internal/application/gateway/selector.go @@ -482,7 +482,7 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model continue } consideredCandidates++ - if !s.candidateSupportsModel(provider, upstreamModel, candidate) { + if !s.candidateSupportsModel(provider, upstreamModel, quotaMode, candidate) { continue } supportedCandidates++ @@ -538,7 +538,7 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model if len(probeCandidates) > 0 { staleClaims := 0 capacityMisses := 0 - plan, err := s.planCandidateIndexes(ctx, values, probeCandidates, now, s.resolveTierOrder(provider, upstreamModel)) + plan, err := s.planCandidateIndexes(ctx, values, probeCandidates, now, s.resolveTierOrder(provider, upstreamModel, quotaMode)) if err != nil { return nil, err } @@ -611,7 +611,7 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model // 粘性账号仅因并发满载而暂时不可用时,先等待该账号;超时后允许本次请求临时借用 // 其他账号,但不覆盖原绑定,避免并行请求让活跃会话在账号池中来回抖动。 if saturatedStickyID != 0 { - plan, err := s.planCandidateIndexes(ctx, values, normalCandidates, time.Now().UTC(), s.resolveTierOrder(provider, upstreamModel)) + plan, err := s.planCandidateIndexes(ctx, values, normalCandidates, time.Now().UTC(), s.resolveTierOrder(provider, upstreamModel, quotaMode)) if err != nil { return nil, err } @@ -637,7 +637,7 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model } activeRequest := s.nextSegmentedActiveRequest(provider, upstreamModel, quotaMode, len(normalCandidates)) if activeRequest != nil { - lease, acquireErr := s.acquireSegmentedCandidates(ctx, values, normalCandidates, quotaMode, s.resolveTierOrder(provider, upstreamModel), *activeRequest) + lease, acquireErr := s.acquireSegmentedCandidates(ctx, values, normalCandidates, quotaMode, s.resolveTierOrder(provider, upstreamModel, quotaMode), *activeRequest) if acquireErr != nil || lease == nil || stickyKey == "" { return lease, acquireErr } @@ -653,7 +653,7 @@ func (s *Selector) acquire(ctx context.Context, provider account.Provider, model currentTime := time.Now().UTC() staleClaims := 0 capacityMisses := 0 - plan, err := s.planCandidateIndexes(ctx, values, normalCandidates, currentTime, s.resolveTierOrder(provider, upstreamModel)) + plan, err := s.planCandidateIndexes(ctx, values, normalCandidates, currentTime, s.resolveTierOrder(provider, upstreamModel, quotaMode)) if err != nil { return nil, err } @@ -784,7 +784,7 @@ func (s *Selector) acquirePinned(ctx context.Context, provider account.Provider, return nil, &SelectionUnavailableError{Reason: SelectionNoAccounts} } if inference { - if !s.candidateSupportsModel(provider, upstreamModel, candidate) { + if !s.candidateSupportsModel(provider, upstreamModel, quotaMode, candidate) { return nil, &SelectionUnavailableError{Reason: SelectionUnsupportedModel} } if candidate.ModelQuotaBlock != nil && now.Before(candidate.ModelQuotaBlock.CooldownUntil) { @@ -906,9 +906,9 @@ func effectiveQuotaMode(candidate account.RoutingCandidate, fallback string) str // prevents a historical capability snapshot from blocking a newly enabled // catalog feature, while unknown/manual Web routes and all other providers // retain the persisted snapshot semantics. -func (s *Selector) candidateSupportsModel(provider account.Provider, upstreamModel string, candidate account.RoutingCandidate) bool { +func (s *Selector) candidateSupportsModel(provider account.Provider, upstreamModel, quotaMode string, candidate account.RoutingCandidate) bool { if provider == account.ProviderWeb { - order := s.resolveTierOrder(provider, upstreamModel) + order := s.resolveTierOrder(provider, upstreamModel, quotaMode) if len(order) > 0 { return webTierInOrder(order, candidate.Credential.WebTier) } @@ -2003,10 +2003,15 @@ func retryDelay(now, retryAt time.Time) time.Duration { return retryAt.Sub(now) } -func (s *Selector) resolveTierOrder(provider account.Provider, upstreamModel string) []account.WebTier { +func (s *Selector) resolveTierOrder(provider account.Provider, upstreamModel, quotaMode string) []account.WebTier { if s.tierOrders == nil { return nil } + if resolver, ok := s.tierOrders.(interface { + TierOrderForQuotaMode(account.Provider, string, string) []account.WebTier + }); ok { + return resolver.TierOrderForQuotaMode(provider, upstreamModel, quotaMode) + } return s.tierOrders.TierOrder(provider, upstreamModel) } diff --git a/backend/internal/application/gateway/selector_session.go b/backend/internal/application/gateway/selector_session.go index 563c22bf..3a6181a5 100644 --- a/backend/internal/application/gateway/selector_session.go +++ b/backend/internal/application/gateway/selector_session.go @@ -75,7 +75,7 @@ func (s *Selector) beginSelectionSessionForKey(ctx context.Context, provider acc continue } consideredCandidates++ - if !s.candidateSupportsModel(provider, upstreamModel, candidate) { + if !s.candidateSupportsModel(provider, upstreamModel, quotaMode, candidate) { continue } supportedCandidates++ @@ -179,7 +179,7 @@ func (session *selectionSession) acquireQuotaProbe(ctx context.Context, excluded return nil, nil } if session.probePlan == nil { - plan, err := session.selector.planCandidateIndexes(ctx, session.values, session.probeCandidates, time.Now().UTC(), session.selector.resolveTierOrder(session.provider, session.upstreamModel)) + plan, err := session.selector.planCandidateIndexes(ctx, session.values, session.probeCandidates, time.Now().UTC(), session.selector.resolveTierOrder(session.provider, session.upstreamModel, session.quotaMode)) if err != nil { return nil, err } @@ -256,7 +256,7 @@ func (session *selectionSession) acquireNormal(ctx context.Context, excluded map indexes := session.unexcludedNormalIndexes(excluded) activeRequest := session.selector.nextSegmentedActiveRequest(session.provider, session.upstreamModel, session.quotaMode, len(indexes)) if activeRequest != nil { - lease, err := session.selector.acquireSegmentedCandidates(ctx, session.values, indexes, session.quotaMode, session.selector.resolveTierOrder(session.provider, session.upstreamModel), *activeRequest) + lease, err := session.selector.acquireSegmentedCandidates(ctx, session.values, indexes, session.quotaMode, session.selector.resolveTierOrder(session.provider, session.upstreamModel, session.quotaMode), *activeRequest) if err != nil || lease == nil || session.stickyKey == "" { return lease, err } @@ -270,7 +270,7 @@ func (session *selectionSession) acquireNormal(ctx context.Context, excluded map deadline := time.Now().Add(capacityWait) for { if session.normalPlan == nil { - plan, err := session.selector.planCandidateIndexes(ctx, session.values, session.normalCandidates, time.Now().UTC(), session.selector.resolveTierOrder(session.provider, session.upstreamModel)) + plan, err := session.selector.planCandidateIndexes(ctx, session.values, session.normalCandidates, time.Now().UTC(), session.selector.resolveTierOrder(session.provider, session.upstreamModel, session.quotaMode)) if err != nil { return nil, err } diff --git a/backend/internal/application/gateway/selector_test.go b/backend/internal/application/gateway/selector_test.go index a64b739c..499b6c1b 100644 --- a/backend/internal/application/gateway/selector_test.go +++ b/backend/internal/application/gateway/selector_test.go @@ -658,6 +658,50 @@ func TestSelectorUsesTierSpecificWebImageEditQuotaAndPrefersBasic(t *testing.T) } } +func TestSelectorAllowsBasicOnlyForConfirmedWebVideoQuota(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "selector-web-basic-video.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accounts := relational.NewAccountRepository(database) + models := relational.NewModelRepository(database) + basic, _, err := accounts.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderWeb, AuthType: account.AuthTypeSSO, WebTier: account.WebTierBasic, + Name: "basic-video", SourceKey: "basic-video", EncryptedAccessToken: "encrypted", + AuthStatus: account.AuthStatusActive, MaxConcurrent: 1, + }) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + if err := accounts.SaveQuotaWindows(ctx, basic.ID, account.WebTierBasic, now, []account.QuotaWindow{{ + AccountID: basic.ID, Mode: account.QuotaModeWebVideo720p, Remaining: 1, Total: 1, + SyncedAt: &now, Source: account.QuotaSourceUpstream, + }}); err != nil { + t.Fatal(err) + } + if err := models.ReplaceAccountCapabilities(ctx, basic.ID, []string{"grok-chat-fast"}, now); err != nil { + t.Fatal(err) + } + selector := NewSelector(accounts, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), webVideoTierOrder{}, time.Hour, time.Second, time.Minute) + lease, err := selector.Acquire(ctx, account.ProviderWeb, 0, "grok-imagine-video", account.QuotaModeWebVideo720p, "", nil, false) + if err != nil { + t.Fatal(err) + } + if lease.Credential.ID != basic.ID || lease.QuotaMode != account.QuotaModeWebVideo720p { + t.Fatalf("720p Basic video lease = %#v", lease) + } + lease.Release() + if _, err := selector.Acquire(ctx, account.ProviderWeb, 0, "grok-imagine-video", account.QuotaModeWebVideo, "", nil, false); err == nil { + t.Fatal("Basic account was selected for an unverified Web video quota product") + } +} + func TestSelectorWebCatalogCapabilityStillEnforcesTier(t *testing.T) { candidate := account.RoutingCandidate{ Credential: account.Credential{Provider: account.ProviderWeb, WebTier: account.WebTierBasic}, @@ -666,19 +710,19 @@ func TestSelectorWebCatalogCapabilityStillEnforcesTier(t *testing.T) { imageSelector := NewSelector(nil, memory.NewConcurrencyLimiter(), nil, staticTierOrder{order: []account.WebTier{ account.WebTierBasic, account.WebTierSuper, account.WebTierHeavy, }}, time.Hour, time.Second, time.Minute) - if !imageSelector.candidateSupportsModel(account.ProviderWeb, "imagine-image-edit", candidate) { + if !imageSelector.candidateSupportsModel(account.ProviderWeb, "imagine-image-edit", account.QuotaModeWebImageEdit, candidate) { t.Fatal("recognized Basic image-edit capability was blocked by a stale snapshot") } videoSelector := NewSelector(nil, memory.NewConcurrencyLimiter(), nil, staticTierOrder{order: []account.WebTier{ account.WebTierSuper, account.WebTierHeavy, }}, time.Hour, time.Second, time.Minute) - if videoSelector.candidateSupportsModel(account.ProviderWeb, "grok-imagine-video", candidate) { + if videoSelector.candidateSupportsModel(account.ProviderWeb, "grok-imagine-video", account.QuotaModeWebVideo, candidate) { t.Fatal("Basic account bypassed the video tier requirement") } } func TestImageQuotaFinalizationKeepsEffectiveConsumptionFence(t *testing.T) { - refreshMode, decrementMode := imageQuotaFinalizationModes(account.QuotaModeWebImagePro, account.QuotaGroupWebImagine) + refreshMode, decrementMode := quotaFinalizationModes(account.QuotaModeWebImagePro, account.QuotaGroupWebImagine) if refreshMode != account.QuotaGroupWebImagine || decrementMode != account.QuotaModeWebImagePro { t.Fatalf("refresh=%q decrement=%q", refreshMode, decrementMode) } @@ -1507,6 +1551,19 @@ func (value staticTierOrder) TierOrder(account.Provider, string) []account.WebTi return value.order } +type webVideoTierOrder struct{} + +func (webVideoTierOrder) TierOrder(account.Provider, string) []account.WebTier { + return []account.WebTier{account.WebTierBasic, account.WebTierSuper, account.WebTierHeavy} +} + +func (webVideoTierOrder) TierOrderForQuotaMode(_ account.Provider, _ string, quotaMode string) []account.WebTier { + if quotaMode == account.QuotaModeWebVideo720p { + return []account.WebTier{account.WebTierBasic, account.WebTierSuper, account.WebTierHeavy} + } + return []account.WebTier{account.WebTierSuper, account.WebTierHeavy} +} + func (f failingConcurrencyLimiter) Acquire(context.Context, string, int) (func(), bool, error) { return nil, false, f.err } diff --git a/backend/internal/application/gateway/video.go b/backend/internal/application/gateway/video.go index 58245927..7e3570a7 100644 --- a/backend/internal/application/gateway/video.go +++ b/backend/internal/application/gateway/video.go @@ -736,12 +736,7 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model return } s.selector.MarkSuccess(context.Background(), lease.Credential) - refreshMode := lease.QuotaMode - decrementMode := lease.QuotaMode - if quotaRefreshGroup != "" { - refreshMode = quotaRefreshGroup - decrementMode = quotaMode - } + refreshMode, decrementMode := quotaFinalizationModes(lease.QuotaMode, quotaRefreshGroup) if decrementMode != "" && decrementMode != "weekly" { quotaCtx, quotaCancel := context.WithTimeout(context.Background(), accountStateWriteTimeout) updated, quotaErr := s.accounts.DecrementQuota(quotaCtx, job.AccountID, decrementMode, 1) diff --git a/backend/internal/application/gateway/video_test.go b/backend/internal/application/gateway/video_test.go index 07445f74..d03fe8ba 100644 --- a/backend/internal/application/gateway/video_test.go +++ b/backend/internal/application/gateway/video_test.go @@ -46,6 +46,13 @@ func TestVideoQuotaModeUsesWeb720pProduct(t *testing.T) { } } +func TestVideoQuotaFinalizationKeepsEffectiveConsumptionFence(t *testing.T) { + refreshMode, decrementMode := quotaFinalizationModes(account.QuotaModeWebVideo720p, account.QuotaGroupWebImagine) + if refreshMode != account.QuotaGroupWebImagine || decrementMode != account.QuotaModeWebVideo720p { + t.Fatalf("refresh=%q decrement=%q", refreshMode, decrementMode) + } +} + func TestGetVideoExposesOnlyReadableResultAsset(t *testing.T) { completed := media.Job{ ID: "video_status", ClientKeyID: 7, Status: media.StatusCompleted, diff --git a/backend/internal/infra/persistence/relational/model_capability_repository_test.go b/backend/internal/infra/persistence/relational/model_capability_repository_test.go index 428ca3de..990c557d 100644 --- a/backend/internal/infra/persistence/relational/model_capability_repository_test.go +++ b/backend/internal/infra/persistence/relational/model_capability_repository_test.go @@ -835,7 +835,7 @@ func TestWebRediscoveryRestoresCatalogRouteDefaults(t *testing.T) { } } -func TestWebImageEditCatalogRemainsAvailableAcrossStaleBasicSnapshots(t *testing.T) { +func TestWebBasicMediaCatalogRemainsAvailableAcrossStaleSnapshots(t *testing.T) { ctx := context.Background() database := openTestDatabase(t) accounts := NewAccountRepository(database) @@ -847,29 +847,38 @@ func TestWebImageEditCatalogRemainsAvailableAcrossStaleBasicSnapshots(t *testing if err != nil { t.Fatal(err) } - // Record a successful historical sync that does not contain image edit. + // Record a successful historical sync that predates Basic image-edit and + // video support. if err := models.ReplaceAccountCapabilities(ctx, basic.ID, []string{"grok-chat-fast"}, time.Now().UTC()); err != nil { t.Fatal(err) } - if err := models.UpsertRoutes(ctx, []model.Route{{ - PublicID: "grok-imagine-image-edit", Provider: account.ProviderWeb, UpstreamModel: "imagine-image-edit", - Capability: model.CapabilityImageEdit, Origin: model.OriginCatalog, Enabled: true, - }}); err != nil { + if err := models.UpsertRoutes(ctx, []model.Route{ + { + PublicID: "grok-imagine-image-edit", Provider: account.ProviderWeb, UpstreamModel: "imagine-image-edit", + Capability: model.CapabilityImageEdit, Origin: model.OriginCatalog, Enabled: true, + }, + { + PublicID: "grok-imagine-video", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-video", + Capability: model.CapabilityVideo, Origin: model.OriginCatalog, Enabled: true, + }, + }); err != nil { t.Fatal(err) } routes, err := models.ListEnabled(ctx) if err != nil { t.Fatal(err) } - var imageEdit *model.Route + mediaRoutes := make(map[string]model.Route) for index := range routes { - if routes[index].Provider == account.ProviderWeb && routes[index].UpstreamModel == "imagine-image-edit" { - imageEdit = &routes[index] - break + if routes[index].Provider == account.ProviderWeb { + mediaRoutes[routes[index].UpstreamModel] = routes[index] } } - if imageEdit == nil || imageEdit.SupportedAccounts != 1 || imageEdit.TotalAccounts != 1 { - t.Fatalf("Web image-edit catalog route = %#v; routes=%#v", imageEdit, routes) + for _, upstreamModel := range []string{"imagine-image-edit", "grok-imagine-video"} { + value, ok := mediaRoutes[upstreamModel] + if !ok || value.SupportedAccounts != 1 || value.TotalAccounts != 1 { + t.Fatalf("Web Basic media route %s = %#v; routes=%#v", upstreamModel, value, routes) + } } unknown, err := models.Create(ctx, model.Route{ PublicID: "unknown-web-image-edit", Provider: account.ProviderWeb, UpstreamModel: "unknown-image-edit", diff --git a/backend/internal/infra/persistence/relational/model_repository.go b/backend/internal/infra/persistence/relational/model_repository.go index c733ccc0..ef34f9f4 100644 --- a/backend/internal/infra/persistence/relational/model_repository.go +++ b/backend/internal/infra/persistence/relational/model_repository.go @@ -49,12 +49,12 @@ const modelConsoleStaticSupportAvailabilityExpression = `(route.provider = 'grok ) ))` -// Web image editing is a catalog capability for every Web tier. Older account -// snapshots may predate Basic support, so the catalog route (and aliases that -// resolve to the same catalog capability) must remain discoverable while the -// runtime selector still enforces the adapter's current tier order. -const modelWebImageEditStaticSupportExpression = `(model_routes.provider = 'grok_web' - AND model_routes.upstream_model = 'imagine-image-edit' +// These Web media catalog capabilities are available to Basic accounts for +// their confirmed quota products. Older capability snapshots may predate that +// support, so catalog routes (and their aliases) remain discoverable while the +// runtime selector enforces the adapter's parameter-specific tier order. +const modelWebBasicMediaStaticSupportExpression = `(model_routes.provider = 'grok_web' + AND model_routes.upstream_model IN ('imagine-image-edit', 'grok-imagine-video') AND ( model_routes.origin = 'catalog' OR EXISTS ( @@ -66,8 +66,8 @@ const modelWebImageEditStaticSupportExpression = `(model_routes.provider = 'grok ) ))` -const modelWebImageEditStaticSupportAvailabilityExpression = `(route.provider = 'grok_web' - AND route.upstream_model = 'imagine-image-edit' +const modelWebBasicMediaStaticSupportAvailabilityExpression = `(route.provider = 'grok_web' + AND route.upstream_model IN ('imagine-image-edit', 'grok-imagine-video') AND ( route.origin = 'catalog' OR EXISTS ( @@ -95,7 +95,7 @@ const availableRoutePredicate = ` NOT EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id) AND ( ` + modelConsoleStaticSupportExpression + ` - OR ` + modelWebImageEditStaticSupportExpression + ` + OR ` + modelWebBasicMediaStaticSupportExpression + ` OR EXISTS ( SELECT 1 FROM account_model_capabilities capability WHERE capability.account_id = account.id @@ -174,7 +174,7 @@ const modelRouteAccountCapabilityPredicate = `( NOT EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id) AND ( ` + modelConsoleStaticSupportExpression + ` - OR ` + modelWebImageEditStaticSupportExpression + ` + OR ` + modelWebBasicMediaStaticSupportExpression + ` OR EXISTS ( SELECT 1 FROM account_model_capabilities capability WHERE capability.account_id = account.id @@ -195,7 +195,7 @@ const modelAvailableRouteAccountCapabilityPredicate = `( NOT EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id) AND ( ` + modelConsoleStaticSupportExpression + ` - OR ` + modelWebImageEditStaticSupportExpression + ` + OR ` + modelWebBasicMediaStaticSupportExpression + ` OR EXISTS ( SELECT 1 FROM account_model_capabilities capability WHERE capability.account_id = account.id @@ -240,7 +240,7 @@ func modelTierAvailabilityPredicateWithAvailability(tiers []string, activeOnly b const ( modelProviderPriorityExpression = "CASE model_routes.provider WHEN 'grok_build' THEN 0 WHEN 'grok_web' THEN 1 WHEN 'grok_console' THEN 2 ELSE 3 END" - modelSupportSortExpression = `(SELECT COUNT(*) FROM provider_accounts account WHERE account.provider = model_routes.provider AND account.enabled = TRUE AND account.auth_status = 'active' AND (EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id AND binding.account_id = account.id) OR (NOT EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id) AND (` + modelConsoleStaticSupportExpression + ` OR ` + modelWebImageEditStaticSupportExpression + ` OR EXISTS (SELECT 1 FROM account_model_capabilities capability WHERE capability.account_id = account.id AND capability.upstream_model = model_routes.upstream_model) OR ` + modelSharedPaidBuildSupportSortExpression + `))))` + modelSupportSortExpression = `(SELECT COUNT(*) FROM provider_accounts account WHERE account.provider = model_routes.provider AND account.enabled = TRUE AND account.auth_status = 'active' AND (EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id AND binding.account_id = account.id) OR (NOT EXISTS (SELECT 1 FROM model_route_accounts binding WHERE binding.model_route_id = model_routes.id) AND (` + modelConsoleStaticSupportExpression + ` OR ` + modelWebBasicMediaStaticSupportExpression + ` OR EXISTS (SELECT 1 FROM account_model_capabilities capability WHERE capability.account_id = account.id AND capability.upstream_model = model_routes.upstream_model) OR ` + modelSharedPaidBuildSupportSortExpression + `))))` modelSyncedSortExpression = `(SELECT MAX(sync.last_success_at) FROM provider_accounts account JOIN account_model_sync_states sync ON sync.account_id = account.id WHERE account.provider = model_routes.provider AND account.enabled = TRUE AND account.auth_status = 'active')` ) @@ -1223,7 +1223,7 @@ func (r *ModelRepository) annotateAvailability(ctx context.Context, values []mod SELECT route.id AS route_id, CASE WHEN COUNT(DISTINCT binding.account_id) > 0 THEN COUNT(DISTINCT CASE WHEN account.enabled = TRUE AND account.auth_status = ? AND binding.account_id IS NOT NULL THEN account.id END) - ELSE COUNT(DISTINCT CASE WHEN account.enabled = TRUE AND account.auth_status = ? AND (`+modelConsoleStaticSupportAvailabilityExpression+` OR `+modelWebImageEditStaticSupportAvailabilityExpression+` OR capability.account_id IS NOT NULL OR `+modelSharedPaidBuildSupportAvailabilityExpression+`) THEN account.id END) + ELSE COUNT(DISTINCT CASE WHEN account.enabled = TRUE AND account.auth_status = ? AND (`+modelConsoleStaticSupportAvailabilityExpression+` OR `+modelWebBasicMediaStaticSupportAvailabilityExpression+` OR capability.account_id IS NOT NULL OR `+modelSharedPaidBuildSupportAvailabilityExpression+`) THEN account.id END) END AS supported_accounts, CASE WHEN COUNT(DISTINCT binding.account_id) > 0 THEN COUNT(DISTINCT CASE WHEN account.enabled = TRUE AND account.auth_status = ? AND binding.account_id IS NOT NULL AND sync.last_success_at IS NOT NULL THEN account.id END) diff --git a/backend/internal/infra/provider/provider.go b/backend/internal/infra/provider/provider.go index 87b048e3..7f6de4df 100644 --- a/backend/internal/infra/provider/provider.go +++ b/backend/internal/infra/provider/provider.go @@ -767,6 +767,13 @@ type RoutingMetadataAdapter interface { TierOrder(upstreamModel string) []account.WebTier } +// QuotaTierOrderAdapter optionally narrows account tiers for a concrete quota +// product. It is used when one public model exposes parameter variants backed +// by different upstream entitlements. +type QuotaTierOrderAdapter interface { + TierOrderForQuotaMode(upstreamModel, quotaMode string) []account.WebTier +} + // ModelAlias resolves a hidden compatibility model name to one public route and can fix reasoning effort. type ModelAlias struct { Alias string @@ -1154,6 +1161,21 @@ func (r *Registry) TierOrder(value account.Provider, upstreamModel string) []acc return metadata.TierOrder(upstreamModel) } +func (r *Registry) TierOrderForQuotaMode(value account.Provider, upstreamModel, quotaMode string) []account.WebTier { + adapter, ok := r.Get(value) + if !ok { + return nil + } + if metadata, ok := adapter.(QuotaTierOrderAdapter); ok { + return metadata.TierOrderForQuotaMode(upstreamModel, quotaMode) + } + metadata, ok := adapter.(RoutingMetadataAdapter) + if !ok { + return nil + } + return metadata.TierOrder(upstreamModel) +} + func (r *Registry) PricingModel(value account.Provider, upstreamModel string) string { adapter, ok := r.Get(value) if !ok { diff --git a/backend/internal/infra/provider/web/adapter.go b/backend/internal/infra/provider/web/adapter.go index a487e154..5434748c 100644 --- a/backend/internal/infra/provider/web/adapter.go +++ b/backend/internal/infra/provider/web/adapter.go @@ -137,6 +137,24 @@ func (a *Adapter) TierOrder(upstreamModel string) []account.WebTier { } } +func (a *Adapter) TierOrderForQuotaMode(upstreamModel, quotaMode string) []account.WebTier { + order := a.TierOrder(upstreamModel) + spec, ok := Resolve(upstreamModel) + if !ok || spec.Capability != modeldomain.CapabilityVideo || quotaMode == account.QuotaModeWebVideo720p { + return order + } + // Basic video entitlement is currently confirmed only for the default + // 720p product. Other video quota products remain on paid Web tiers until + // independently verified upstream. + filtered := make([]account.WebTier, 0, len(order)) + for _, tier := range order { + if tier != account.WebTierBasic { + filtered = append(filtered, tier) + } + } + return filtered +} + func (a *Adapter) PricingModel(upstreamModel string) string { spec, ok := Resolve(upstreamModel) if ok { diff --git a/backend/internal/infra/provider/web/catalog.go b/backend/internal/infra/provider/web/catalog.go index 41ba42c0..ea48d7ec 100644 --- a/backend/internal/infra/provider/web/catalog.go +++ b/backend/internal/infra/provider/web/catalog.go @@ -20,12 +20,13 @@ var catalog = []ModelSpec{ {PublicID: "grok-chat-expert", UpstreamModel: "grok-chat-expert", Capability: modeldomain.CapabilityChat, Mode: "expert", MinimumTier: account.WebTierSuper}, {PublicID: "grok-chat-heavy", UpstreamModel: "grok-chat-heavy", Capability: modeldomain.CapabilityChat, Mode: "heavy", MinimumTier: account.WebTierHeavy}, // Web generation is exposed with a -lite suffix so it remains visibly - // distinct from the Console resource API. Image editing is also available - // to Basic accounts, but consumes a tier-specific upstream quota window. + // distinct from the Console resource API. Image editing and the default + // 720p video product are also available to Basic accounts, with runtime + // selection fenced by their tier-specific upstream quota windows. {PublicID: "grok-imagine-image-lite", UpstreamModel: "grok-imagine-image", ProtocolModel: "imagine-lite", Capability: modeldomain.CapabilityImage, Mode: "fast", MinimumTier: account.WebTierBasic}, {PublicID: "grok-imagine-image-quality-lite", UpstreamModel: "grok-imagine-image-quality", ProtocolModel: "imagine", Capability: modeldomain.CapabilityImage, Mode: "image_pro", MinimumTier: account.WebTierBasic}, {PublicID: "grok-imagine-image-edit", UpstreamModel: "imagine-image-edit", Capability: modeldomain.CapabilityImageEdit, Mode: "image_edit", MinimumTier: account.WebTierBasic}, - {PublicID: "grok-imagine-video", UpstreamModel: "grok-imagine-video", ProtocolModel: "imagine-video-gen", Capability: modeldomain.CapabilityVideo, Mode: "video", MinimumTier: account.WebTierSuper}, + {PublicID: "grok-imagine-video", UpstreamModel: "grok-imagine-video", ProtocolModel: "imagine-video-gen", Capability: modeldomain.CapabilityVideo, Mode: "video", MinimumTier: account.WebTierBasic}, } func Catalog() []ModelSpec { return append([]ModelSpec(nil), catalog...) } diff --git a/backend/internal/infra/provider/web/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index 9c8984f0..b5fc1d05 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -1205,7 +1205,7 @@ func TestModelsUseLowestSufficientTierFirst(t *testing.T) { {model: "grok-imagine-image", want: []account.WebTier{account.WebTierBasic, account.WebTierSuper, account.WebTierHeavy}}, {model: "grok-imagine-image-quality", want: []account.WebTier{account.WebTierBasic, account.WebTierSuper, account.WebTierHeavy}}, {model: "imagine-image-edit", want: []account.WebTier{account.WebTierBasic, account.WebTierSuper, account.WebTierHeavy}}, - {model: "grok-imagine-video", want: []account.WebTier{account.WebTierSuper, account.WebTierHeavy}}, + {model: "grok-imagine-video", want: []account.WebTier{account.WebTierBasic, account.WebTierSuper, account.WebTierHeavy}}, } for _, test := range tests { got := adapter.TierOrder(test.model) @@ -1215,6 +1215,20 @@ func TestModelsUseLowestSufficientTierFirst(t *testing.T) { } } +func TestWebVideoTierOrderFollowsConfirmedQuotaProduct(t *testing.T) { + adapter := &Adapter{} + if got := adapter.TierOrderForQuotaMode("grok-imagine-video", account.QuotaModeWebVideo720p); !slices.Equal(got, []account.WebTier{ + account.WebTierBasic, account.WebTierSuper, account.WebTierHeavy, + }) { + t.Fatalf("720p video tier order = %v", got) + } + if got := adapter.TierOrderForQuotaMode("grok-imagine-video", account.QuotaModeWebVideo); !slices.Equal(got, []account.WebTier{ + account.WebTierSuper, account.WebTierHeavy, + }) { + t.Fatalf("unverified video product tier order = %v", got) + } +} + func TestOnlyChatModelsExposeRateLimitModes(t *testing.T) { for _, spec := range Catalog() { if spec.Capability == modeldomain.CapabilityChat { diff --git a/backend/internal/infra/provider/web/quota.go b/backend/internal/infra/provider/web/quota.go index eb47bd6a..0762fd54 100644 --- a/backend/internal/infra/provider/web/quota.go +++ b/backend/internal/infra/provider/web/quota.go @@ -200,7 +200,11 @@ func decodeImagineQuotaSnapshot(body []byte, accountID uint64, now time.Time) ([ if product.NextAvailableAt != nil { value := product.NextAvailableAt.UTC() resetAt = &value - } else if !*product.Available || remaining == 0 { + } else { + // Imagine exposes the quota-window length but omits its anchor while + // the product is available. Match Web chat quota semantics by using + // the observation time as the rolling prediction anchor; every sync + // replaces this estimate, while an explicit nextAvailableAt wins. value := now.Add(time.Duration(windowSeconds) * time.Second) resetAt = &value } diff --git a/backend/internal/infra/provider/web/quota_test.go b/backend/internal/infra/provider/web/quota_test.go index 9c7e8bab..76a19b46 100644 --- a/backend/internal/infra/provider/web/quota_test.go +++ b/backend/internal/infra/provider/web/quota_test.go @@ -467,14 +467,31 @@ func TestDecodeImagineQuotaSnapshotMatchesObservedProtocol(t *testing.T) { if len(windows) != 2 { t.Fatalf("windows = %#v", windows) } - if windows[0].Mode != account.QuotaModeWebImagePro || windows[0].Remaining != 4 || windows[0].Total != 0 || windows[0].ResetAt != nil { + wantResetAt := now.Add(24 * time.Hour) + if windows[0].Mode != account.QuotaModeWebImagePro || windows[0].Remaining != 4 || windows[0].Total != 0 || windows[0].ResetAt == nil || !windows[0].ResetAt.Equal(wantResetAt) { t.Fatalf("image_pro = %#v", windows[0]) } - if windows[1].Mode != account.QuotaModeWebVideo720p || windows[1].Remaining != 1 || windows[1].Total != 0 || windows[1].ResetAt != nil { + if windows[1].Mode != account.QuotaModeWebVideo720p || windows[1].Remaining != 1 || windows[1].Total != 0 || windows[1].ResetAt == nil || !windows[1].ResetAt.Equal(wantResetAt) { t.Fatalf("video_720p = %#v", windows[1]) } } +func TestDecodeImagineQuotaSnapshotPrefersUpstreamNextAvailableAt(t *testing.T) { + now := time.Date(2026, 8, 13, 8, 0, 0, 0, time.UTC) + upstreamResetAt := now.Add(37 * time.Minute) + body := []byte(`{ + "image":null,"imageEdit":null,"video":null,"video720p":null, + "imagePro":{"available":true,"remainingQueries":4,"windowSizeSeconds":86400,"nextAvailableAt":"` + upstreamResetAt.Format(time.RFC3339) + `"} + }`) + windows, err := decodeImagineQuotaSnapshot(body, 42, now) + if err != nil { + t.Fatal(err) + } + if len(windows) != 1 || windows[0].ResetAt == nil || !windows[0].ResetAt.Equal(upstreamResetAt) { + t.Fatalf("windows = %#v", windows) + } +} + func TestDecodeImagineQuotaSnapshotRequiresCompleteResponse(t *testing.T) { now := time.Now().UTC() _, err := decodeImagineQuotaSnapshot([]byte(`{"image":null,"imageEdit":null,"imagePro":null,"video":null}`), 42, now) diff --git a/frontend/src/features/accounts/account-quota.tsx b/frontend/src/features/accounts/account-quota.tsx index 8843cb6e..b34d7e64 100644 --- a/frontend/src/features/accounts/account-quota.tsx +++ b/frontend/src/features/accounts/account-quota.tsx @@ -120,12 +120,12 @@ export function ConsoleQuota({ windows, locale }: { windows: NonNullable{t("accounts.quotaNotSynced")}; const windowsByMode = new Map(windows.map((window) => [window.mode, window])); const modes = [ - { mode: "console", label: t("creativeConsole.modes.chat") }, - { mode: "console_image", label: t("creativeConsole.modes.image") }, - { mode: "console_video", label: t("creativeConsole.modes.video") }, + { mode: "console", label: "Chat" }, + { mode: "console_image", label: "Image" }, + { mode: "console_video", label: "Video" }, ] as const; return ( -
+
{modes.map(({ mode, label }) => { const window = windowsByMode.get(mode); if (!window) { @@ -163,9 +163,11 @@ export function WebQuota({ windows, locale, tier }: { windows: NonNullable - {mainBlock} - +
+
{mainBlock}
+
+ +
); } @@ -201,7 +203,7 @@ function ImagineQuotaRow({ windows, locale, t }: { windows: WebQuotaWindow[]; lo ) : hasTotal ? ( {formatNumber(window.remaining, locale, 0)}/{formatNumber(window.total, locale, 0)} ) : ( - {t("accounts.imagineQuotaRemaining", { remaining: formatNumber(window.remaining, locale, 0) })} + {formatNumber(window.remaining, locale, 0)}/- )}
diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index 9c3192ee..f97180da 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -597,10 +597,10 @@ const resources = { imagineQuota: "Imagine 配额", imagineQuotaRemaining: "剩余 {{remaining}} 次", imagineQuotaExhausted: "已耗尽,冷却中", - imagineModeImagePro: "生图", + imagineModeImagePro: "Image", imagineModeImageEdit: "图片编辑", imagineModeVideo: "视频", - imagineModeVideo720p: "视频 720p", + imagineModeVideo720p: "Video 720p", created: "账号接入成功", createdWithSyncFailure: "账号已接入,但额度或模型初始同步失败", updated: "账号已更新",