Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: support unified instance license mode (#20155)

p0nyf0b33713deca
diff --git a/backend/api/v1/actuator_service.go b/backend/api/v1/actuator_service.go
index 58bc835462..0527ea1f7d 100644
--- a/backend/api/v1/actuator_service.go
+++ b/backend/api/v1/actuator_service.go
@@ -194,17 +194,21 @@ func (s *ActuatorService) getServerInfo(ctx context.Context, workspaceID string)
}
serverInfo.ExternalUrl = externalURL
- activatedInstanceCount, err := s.store.GetActivatedInstanceCount(ctx, workspaceID)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to count activated instance"))
- }
- serverInfo.ActivatedInstanceCount = int32(activatedInstanceCount)
-
activeInstanceCount, err := s.store.CountActiveInstances(ctx, workspaceID)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to count total instance"))
}
serverInfo.TotalInstanceCount = int32(activeInstanceCount)
+
+ if s.licenseService.IsUnifiedInstanceLicense(ctx, workspaceID) {
+ serverInfo.ActivatedInstanceCount = int32(activeInstanceCount)
+ } else {
+ activatedInstanceCount, err := s.store.GetActivatedInstanceCount(ctx, workspaceID)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to count activated instance"))
+ }
+ serverInfo.ActivatedInstanceCount = int32(activatedInstanceCount)
+ }
}
return &serverInfo, nil
diff --git a/backend/api/v1/database_service.go b/backend/api/v1/database_service.go
index 8592642d67..b046073393 100644
--- a/backend/api/v1/database_service.go
+++ b/backend/api/v1/database_service.go
@@ -18,6 +18,7 @@ import (
"github.com/bytebase/bytebase/backend/common/permission"
"github.com/bytebase/bytebase/backend/component/config"
"github.com/bytebase/bytebase/backend/component/iam"
+ "github.com/bytebase/bytebase/backend/enterprise"
storepb "github.com/bytebase/bytebase/backend/generated-go/store"
v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
"github.com/bytebase/bytebase/backend/generated-go/v1/v1connect"
@@ -30,19 +31,21 @@ import (
// DatabaseService implements the database service.
type DatabaseService struct {
v1connect.UnimplementedDatabaseServiceHandler
- store *store.Store
- schemaSyncer *schemasync.Syncer
- profile *config.Profile
- iamManager *iam.Manager
+ store *store.Store
+ schemaSyncer *schemasync.Syncer
+ profile *config.Profile
+ iamManager *iam.Manager
+ licenseService *enterprise.LicenseService
}
// NewDatabaseService creates a new DatabaseService.
-func NewDatabaseService(store *store.Store, schemaSyncer *schemasync.Syncer, profile *config.Profile, iamManager *iam.Manager) *DatabaseService {
+func NewDatabaseService(store *store.Store, schemaSyncer *schemasync.Syncer, profile *config.Profile, iamManager *iam.Manager, licenseService *enterprise.LicenseService) *DatabaseService {
return &DatabaseService{
- store: store,
- schemaSyncer: schemaSyncer,
- profile: profile,
- iamManager: iamManager,
+ store: store,
+ schemaSyncer: schemaSyncer,
+ profile: profile,
+ iamManager: iamManager,
+ licenseService: licenseService,
}
}
@@ -995,7 +998,10 @@ func (s *DatabaseService) convertToDatabase(ctx context.Context, database *store
if database.EffectiveEnvironmentID != nil && *database.EffectiveEnvironmentID != "" {
effectiveEnvironment = new(common.FormatEnvironment(*database.EffectiveEnvironmentID))
}
- instanceResource := convertToV1InstanceResource(instance)
+ instanceResource := convertToV1InstanceResource(
+ instance,
+ s.licenseService.IsInstanceEffectivelyActivated(ctx, common.GetWorkspaceIDFromContext(ctx), instance),
+ )
return &v1pb.Database{
Name: common.FormatDatabase(database.InstanceID, database.DatabaseName),
State: convertDeletedToState(database.Deleted),
diff --git a/backend/api/v1/instance_service.go b/backend/api/v1/instance_service.go
index a7f31bd8ca..20e536942f 100644
--- a/backend/api/v1/instance_service.go
+++ b/backend/api/v1/instance_service.go
@@ -61,7 +61,7 @@ func (s *InstanceService) GetInstance(ctx context.Context, req *connect.Request[
if err != nil {
return nil, err
}
- result := convertToV1Instance(instance)
+ result := s.convertToV1Instance(ctx, instance)
return connect.NewResponse(result), nil
}
@@ -111,8 +111,9 @@ func (s *InstanceService) ListInstances(ctx context.Context, req *connect.Reques
response := &v1pb.ListInstancesResponse{
NextPageToken: nextPageToken,
}
+ workspaceID := common.GetWorkspaceIDFromContext(ctx)
for _, instance := range instances {
- ins := convertToV1Instance(instance)
+ ins := convertToV1Instance(instance, s.licenseService.IsInstanceEffectivelyActivated(ctx, workspaceID, instance))
response.Instances = append(response.Instances, ins)
}
return connect.NewResponse(response), nil
@@ -210,19 +211,12 @@ func (s *InstanceService) CreateInstance(ctx context.Context, req *connect.Reque
}
}
- result := convertToV1Instance(instanceMessage)
+ result := s.convertToV1Instance(ctx, instanceMessage)
return connect.NewResponse(result), nil
}
- activatedInstanceLimit := s.licenseService.GetActivatedInstanceLimit(ctx, workspaceID)
- if instanceMessage.Metadata.GetActivation() {
- count, err := s.store.GetActivatedInstanceCount(ctx, workspaceID)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, err)
- }
- if count >= activatedInstanceLimit {
- return nil, connect.NewError(connect.CodeResourceExhausted, errors.Errorf(instanceExceededError, activatedInstanceLimit))
- }
+ if err := s.checkActivationLimit(ctx, workspaceID, instanceMessage.Metadata.GetActivation()); err != nil {
+ return nil, err
}
instance, err := s.store.CreateInstance(ctx, instanceMessage)
@@ -248,7 +242,7 @@ func (s *InstanceService) CreateInstance(ctx context.Context, req *connect.Reque
s.schemaSyncer.SyncAllDatabases(ctx, instance)
}
- result := convertToV1Instance(instance)
+ result := s.convertToV1Instance(ctx, instance)
return connect.NewResponse(result), nil
}
@@ -258,6 +252,10 @@ func instanceWithMetadata(instance *store.InstanceMessage, metadata *storepb.Ins
return &candidate
}
+func (s *InstanceService) convertToV1Instance(ctx context.Context, instance *store.InstanceMessage) *v1pb.Instance {
+ return convertToV1Instance(instance, s.licenseService.IsInstanceEffectivelyActivated(ctx, common.GetWorkspaceIDFromContext(ctx), instance))
+}
+
func (s *InstanceService) checkInstanceDataSources(ctx context.Context, instance *store.InstanceMessage, dataSources []*storepb.DataSource) error {
for _, ds := range dataSources {
if err := s.checkDataSource(ctx, instance, ds); err != nil {
@@ -398,6 +396,21 @@ func parseInlinePrivateKey(der []byte) (any, error) {
const instanceExceededError = "activation instance count has reached the limit (%v)"
+func (s *InstanceService) checkActivationLimit(ctx context.Context, workspaceID string, activating bool) error {
+ if !activating || s.licenseService.IsUnifiedInstanceLicense(ctx, workspaceID) {
+ return nil
+ }
+ activatedInstanceLimit := s.licenseService.GetActivatedInstanceLimit(ctx, workspaceID)
+ count, err := s.store.GetActivatedInstanceCount(ctx, workspaceID)
+ if err != nil {
+ return connect.NewError(connect.CodeInternal, err)
+ }
+ if count >= activatedInstanceLimit {
+ return connect.NewError(connect.CodeResourceExhausted, errors.Errorf(instanceExceededError, activatedInstanceLimit))
+ }
+ return nil
+}
+
func (s *InstanceService) checkDataSource(ctx context.Context, instance *store.InstanceMessage, dataSource *storepb.DataSource) error {
if dataSource.GetId() == "" {
return connect.NewError(connect.CodeInvalidArgument, errors.New("data source id is required"))
@@ -557,22 +570,15 @@ func (s *InstanceService) UpdateInstance(ctx context.Context, req *connect.Reque
}
workspaceID := common.GetWorkspaceIDFromContext(ctx)
- activatedInstanceLimit := s.licenseService.GetActivatedInstanceLimit(ctx, workspaceID)
- if updateActivation {
- count, err := s.store.GetActivatedInstanceCount(ctx, workspaceID)
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, err)
- }
- if count >= activatedInstanceLimit {
- return nil, connect.NewError(connect.CodeResourceExhausted, errors.Errorf(instanceExceededError, activatedInstanceLimit))
- }
+ if err := s.checkActivationLimit(ctx, workspaceID, updateActivation); err != nil {
+ return nil, err
}
ins, err := s.store.UpdateInstance(ctx, patch)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
- result := convertToV1Instance(ins)
+ result := s.convertToV1Instance(ctx, ins)
return connect.NewResponse(result), nil
}
@@ -659,7 +665,7 @@ func (s *InstanceService) UndeleteInstance(ctx context.Context, req *connect.Req
}
// Idempotent: if already active, return the instance
if !instance.Deleted {
- result := convertToV1Instance(instance)
+ result := s.convertToV1Instance(ctx, instance)
return connect.NewResponse(result), nil
}
if err := s.instanceCountGuard(ctx); err != nil {
@@ -682,7 +688,7 @@ func (s *InstanceService) UndeleteInstance(ctx context.Context, req *connect.Req
}
}
- result := convertToV1Instance(ins)
+ result := s.convertToV1Instance(ctx, ins)
return connect.NewResponse(result), nil
}
@@ -817,7 +823,7 @@ func (s *InstanceService) AddDataSource(ctx context.Context, req *connect.Reques
if err != nil {
return nil, err
}
- result := convertToV1Instance(instanceWithMetadata(instance, metadata))
+ result := s.convertToV1Instance(ctx, instanceWithMetadata(instance, metadata))
return connect.NewResponse(result), nil
}
@@ -834,7 +840,7 @@ func (s *InstanceService) AddDataSource(ctx context.Context, req *connect.Reques
return nil, connect.NewError(connect.CodeInternal, err)
}
- result := convertToV1Instance(instance)
+ result := s.convertToV1Instance(ctx, instance)
return connect.NewResponse(result), nil
}
@@ -1035,7 +1041,7 @@ func (s *InstanceService) UpdateDataSource(ctx context.Context, req *connect.Req
if err != nil {
return nil, err
}
- result := convertToV1Instance(instanceWithMetadata(instance, metadata))
+ result := s.convertToV1Instance(ctx, instanceWithMetadata(instance, metadata))
return connect.NewResponse(result), nil
}
@@ -1047,7 +1053,7 @@ func (s *InstanceService) UpdateDataSource(ctx context.Context, req *connect.Req
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
- result := convertToV1Instance(instance)
+ result := s.convertToV1Instance(ctx, instance)
return connect.NewResponse(result), nil
}
@@ -1094,7 +1100,7 @@ func (s *InstanceService) RemoveDataSource(ctx context.Context, req *connect.Req
return nil, connect.NewError(connect.CodeInternal, err)
}
- result := convertToV1Instance(instance)
+ result := s.convertToV1Instance(ctx, instance)
return connect.NewResponse(result), nil
}
diff --git a/backend/api/v1/instance_service_converter.go b/backend/api/v1/instance_service_converter.go
index c6640c53c0..13080ab110 100644
--- a/backend/api/v1/instance_service_converter.go
+++ b/backend/api/v1/instance_service_converter.go
@@ -12,7 +12,7 @@ import (
"github.com/bytebase/bytebase/backend/store"
)
-func convertToV1Instance(instance *store.InstanceMessage) *v1pb.Instance {
+func convertToV1Instance(instance *store.InstanceMessage, activation bool) *v1pb.Instance {
engine := convertToEngine(instance.Metadata.GetEngine())
dataSources := convertDataSources(instance.Metadata.GetDataSources())
@@ -25,7 +25,7 @@ func convertToV1Instance(instance *store.InstanceMessage) *v1pb.Instance {
DataSources: dataSources,
State: convertDeletedToState(instance.Deleted),
Environment: buildEnvironmentName(instance.EnvironmentID),
- Activation: instance.Metadata.GetActivation(),
+ Activation: activation,
SyncInterval: instance.Metadata.GetSyncInterval(),
SyncDatabases: instance.Metadata.GetSyncDatabases(),
Roles: convertInstanceRoles(instance, instance.Metadata.GetRoles()),
@@ -93,16 +93,15 @@ func convertToStoreInstance(instanceID string, instance *v1pb.Instance) (*store.
}, nil
}
-func convertToV1InstanceResource(instanceMessage *store.InstanceMessage) *v1pb.InstanceResource {
- instance := convertToV1Instance(instanceMessage)
+func convertToV1InstanceResource(instanceMessage *store.InstanceMessage, activation bool) *v1pb.InstanceResource {
return &v1pb.InstanceResource{
- Name: instance.Name,
- Title: instance.Title,
- Engine: instance.Engine,
- EngineVersion: instance.EngineVersion,
- DataSources: instance.DataSources,
- Activation: instance.Activation,
- Environment: instance.Environment,
+ Name: buildInstanceName(instanceMessage.ResourceID),
+ Title: instanceMessage.Metadata.GetTitle(),
+ Engine: convertToEngine(instanceMessage.Metadata.GetEngine()),
+ EngineVersion: instanceMessage.Metadata.GetVersion(),
+ DataSources: convertDataSources(instanceMessage.Metadata.GetDataSources()),
+ Activation: activation,
+ Environment: buildEnvironmentName(instanceMessage.EnvironmentID),
}
}
diff --git a/backend/enterprise/license.go b/backend/enterprise/license.go
index ba32dbb1d3..007cb32677 100644
--- a/backend/enterprise/license.go
+++ b/backend/enterprise/license.go
@@ -307,21 +307,16 @@ func (s *LicenseService) IsFeatureEnabledForInstance(ctx context.Context, worksp
if err := s.IsFeatureEnabled(ctx, workspaceID, f); err != nil {
return err
}
- if !instance.Metadata.GetActivation() {
- return errors.Errorf(`feature "%s" is not available for instance %s, please assign license to the instance to enable it`, f.String(), instance.ResourceID)
+ if !s.IsInstanceEffectivelyActivated(ctx, workspaceID, instance) {
+ instanceID := ""
+ if instance != nil {
+ instanceID = instance.ResourceID
+ }
+ return errors.Errorf(`feature "%s" requires an activated instance under the current license: %s`, f.String(), instanceID)
}
return nil
}
-// GetActivatedInstanceLimit returns the activated instance limit for the current subscription.
-func (s *LicenseService) GetActivatedInstanceLimit(ctx context.Context, workspaceID string) int {
- limit := s.LoadSubscription(ctx, workspaceID).ActiveInstances
- if limit < 0 {
- return math.MaxInt
- }
- return int(limit)
-}
-
// GetUserLimit gets the user limit value for the plan.
func (s *LicenseService) GetUserLimit(ctx context.Context, workspaceID string) int {
subscription := s.LoadSubscription(ctx, workspaceID)
@@ -363,6 +358,35 @@ func (s *LicenseService) GetInstanceLimit(ctx context.Context, workspaceID strin
return limit
}
+// GetActivatedInstanceLimit returns the activated instance limit for the current subscription.
+func (s *LicenseService) GetActivatedInstanceLimit(ctx context.Context, workspaceID string) int {
+ limit := s.LoadSubscription(ctx, workspaceID).ActiveInstances
+ if limit < 0 {
+ return math.MaxInt
+ }
+ return int(limit)
+}
+
+func isUnifiedInstanceLimit(instanceLimit, activatedInstanceLimit int) bool {
+ return instanceLimit <= activatedInstanceLimit
+}
+
+// IsUnifiedInstanceLicense returns whether every registrable instance is effectively activated.
+func (s *LicenseService) IsUnifiedInstanceLicense(ctx context.Context, workspaceID string) bool {
+ return isUnifiedInstanceLimit(
+ s.GetInstanceLimit(ctx, workspaceID),
+ s.GetActivatedInstanceLimit(ctx, workspaceID),
+ )
+}
+
+// IsInstanceEffectivelyActivated returns whether the instance can use instance-gated features.
+func (s *LicenseService) IsInstanceEffectivelyActivated(ctx context.Context, workspaceID string, instance *store.InstanceMessage) bool {
+ if instance == nil {
+ return false
+ }
+ return instance.Metadata.GetActivation() || s.IsUnifiedInstanceLicense(ctx, workspaceID)
+}
+
// StoreLicense will store license into file.
func (s *LicenseService) StoreLicense(ctx context.Context, workspaceID string, license string) error {
if license != "" {
@@ -390,6 +414,16 @@ type LicenseParams struct {
ExpiresAt time.Time // zero value means no expiration
}
+func newLicenseClaims(params *LicenseParams) *Claims {
+ return &Claims{
+ Plan: params.Plan,
+ Seats: params.Seats,
+ ActiveInstances: params.Instances,
+ Instances: params.Instances,
+ WorkspaceID: params.WorkspaceID,
+ }
+}
+
// CreateLicense signs a new license JWT from business params.
// Only available when private key is configured (SaaS mode).
// Handles JWT plumbing (issuer, audience, kid) internally.
@@ -398,13 +432,7 @@ func (s *LicenseService) CreateLicense(params *LicenseParams) (string, error) {
return "", errors.New("license signing not available: private key not configured")
}
- c := &Claims{
- Plan: params.Plan,
- Seats: params.Seats,
- ActiveInstances: params.Instances,
- Instances: params.Instances,
- WorkspaceID: params.WorkspaceID,
- }
+ c := newLicenseClaims(params)
c.Issuer = s.config.Issuer
c.Audience = jwt.ClaimStrings{s.config.Audience}
c.IssuedAt = jwt.NewNumericDate(time.Now())
diff --git a/backend/enterprise/license_test.go b/backend/enterprise/license_test.go
new file mode 100644
index 0000000000..1fc56f8b96
--- /dev/null
+++ b/backend/enterprise/license_test.go
@@ -0,0 +1,128 @@
+package enterprise
+
+import (
+ "context"
+ "math"
+ "testing"
+ "time"
+
+ "github.com/hashicorp/golang-lru/v2/expirable"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+func newTestLicenseService(sub *v1pb.Subscription) *LicenseService {
+ s := &LicenseService{
+ cache: expirable.NewLRU[string, *v1pb.Subscription](8, nil, time.Minute),
+ }
+ s.cache.Add(licenseCacheKey("test-workspace"), sub)
+ return s
+}
+
+func TestIsUnifiedInstanceLimit(t *testing.T) {
+ tests := []struct {
+ name string
+ instanceLimit int
+ activatedLimit int
+ want bool
+ }{
+ {name: "equal finite caps", instanceLimit: 10, activatedLimit: 10, want: true},
+ {name: "activated cap larger than registration cap", instanceLimit: 10, activatedLimit: 20, want: true},
+ {name: "split cap", instanceLimit: 50, activatedLimit: 20, want: false},
+ {name: "unlimited both sides", instanceLimit: math.MaxInt, activatedLimit: math.MaxInt, want: true},
+ {name: "unlimited registration finite activation", instanceLimit: math.MaxInt, activatedLimit: 20, want: false},
+ {name: "finite registration unlimited activation", instanceLimit: 20, activatedLimit: math.MaxInt, want: true},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := isUnifiedInstanceLimit(tt.instanceLimit, tt.activatedLimit); got != tt.want {
+ t.Fatalf("isUnifiedInstanceLimit(%d, %d) = %v, want %v", tt.instanceLimit, tt.activatedLimit, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestIsFeatureEnabledForInstanceUnifiedLicense(t *testing.T) {
+ ctx := context.Background()
+ instance := &store.InstanceMessage{
+ ResourceID: "prod",
+ Workspace: "test-workspace",
+ Metadata: &storepb.Instance{Activation: false},
+ }
+ service := newTestLicenseService(&v1pb.Subscription{
+ Plan: v1pb.PlanType_ENTERPRISE,
+ Instances: 10,
+ ActiveInstances: 10,
+ })
+
+ if err := service.IsFeatureEnabledForInstance(ctx, "test-workspace", v1pb.PlanFeature_FEATURE_DATA_MASKING, instance); err != nil {
+ t.Fatalf("unified license should enable feature for inactive stored instance: %v", err)
+ }
+}
+
+func TestIsFeatureEnabledForInstanceSplitLicense(t *testing.T) {
+ ctx := context.Background()
+ instance := &store.InstanceMessage{
+ ResourceID: "prod",
+ Workspace: "test-workspace",
+ Metadata: &storepb.Instance{Activation: false},
+ }
+ service := newTestLicenseService(&v1pb.Subscription{
+ Plan: v1pb.PlanType_ENTERPRISE,
+ Instances: 50,
+ ActiveInstances: 20,
+ })
+
+ if err := service.IsFeatureEnabledForInstance(ctx, "test-workspace", v1pb.PlanFeature_FEATURE_DATA_MASKING, instance); err == nil {
+ t.Fatal("split license should still require stored activation")
+ }
+}
+
+func TestIsInstanceEffectivelyActivated(t *testing.T) {
+ ctx := context.Background()
+ instance := &store.InstanceMessage{
+ ResourceID: "prod",
+ Workspace: "test-workspace",
+ Metadata: &storepb.Instance{Activation: false},
+ }
+
+ unifiedService := newTestLicenseService(&v1pb.Subscription{
+ Plan: v1pb.PlanType_ENTERPRISE,
+ Instances: 10,
+ ActiveInstances: 10,
+ })
+ if !unifiedService.IsInstanceEffectivelyActivated(ctx, "test-workspace", instance) {
+ t.Fatal("unified license should effectively activate stored inactive instance")
+ }
+
+ splitService := newTestLicenseService(&v1pb.Subscription{
+ Plan: v1pb.PlanType_ENTERPRISE,
+ Instances: 50,
+ ActiveInstances: 20,
+ })
+ if splitService.IsInstanceEffectivelyActivated(ctx, "test-workspace", instance) {
+ t.Fatal("split license should use stored inactive state")
+ }
+
+ instance.Metadata.Activation = true
+ if !splitService.IsInstanceEffectivelyActivated(ctx, "test-workspace", instance) {
+ t.Fatal("split license should keep stored active state")
+ }
+}
+
+func TestCreateLicenseUsesEqualInstanceClaims(t *testing.T) {
+ claims := newLicenseClaims(&LicenseParams{
+ Plan: v1pb.PlanType_ENTERPRISE.String(),
+ Seats: 5,
+ Instances: 10,
+ WorkspaceID: "test-workspace",
+ })
+ if claims.Instances != 10 {
+ t.Fatalf("Instances = %d, want 10", claims.Instances)
+ }
+ if claims.ActiveInstances != 10 {
+ t.Fatalf("ActiveInstances = %d, want 10", claims.ActiveInstances)
+ }
+}
diff --git a/backend/runner/schemasync/syncer.go b/backend/runner/schemasync/syncer.go
index 163bd56057..07dadef6df 100644
--- a/backend/runner/schemasync/syncer.go
+++ b/backend/runner/schemasync/syncer.go
@@ -178,7 +178,7 @@ func (s *Syncer) trySyncAll(ctx context.Context) {
now := time.Now()
for _, instance := range instances {
instance := instance
- interval := getOrDefaultSyncInterval(instance)
+ interval := s.getOrDefaultSyncInterval(ctx, instance)
if interval == defaultSyncInterval {
continue
}
@@ -221,7 +221,7 @@ func (s *Syncer) trySyncAll(ctx context.Context) {
continue
}
// The database inherits the sync interval from the instance.
- interval := getOrDefaultSyncInterval(instance)
+ interval := s.getOrDefaultSyncInterval(ctx, instance)
if interval == defaultSyncInterval {
continue
}
@@ -519,8 +519,12 @@ func (s *Syncer) databaseBackupAvailable(ctx context.Context, instance *store.In
return false
}
-func getOrDefaultSyncInterval(instance *store.InstanceMessage) time.Duration {
- if !instance.Metadata.GetActivation() {
+func (s *Syncer) getOrDefaultSyncInterval(ctx context.Context, instance *store.InstanceMessage) time.Duration {
+ activated := instance.Metadata.GetActivation()
+ if s.licenseService != nil {
+ activated = s.licenseService.IsInstanceEffectivelyActivated(ctx, instance.Workspace, instance)
+ }
+ if !activated {
return defaultSyncInterval
}
if !instance.Metadata.GetSyncInterval().IsValid() {
diff --git a/backend/runner/schemasync/syncer_test.go b/backend/runner/schemasync/syncer_test.go
index b35ccd1b37..1fcaec6740 100644
--- a/backend/runner/schemasync/syncer_test.go
+++ b/backend/runner/schemasync/syncer_test.go
@@ -3,8 +3,13 @@ package schemasync
import (
"context"
"testing"
+ "time"
"github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/types/known/durationpb"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ "github.com/bytebase/bytebase/backend/store"
)
// TestSyncDatabaseSchemaNilDatabase pins the guard that prevents a nil
@@ -27,3 +32,20 @@ func TestSyncDatabaseSchemaNilDatabase(t *testing.T) {
require.Error(t, err)
require.Contains(t, err.Error(), "nil database")
}
+
+func TestGetOrDefaultSyncIntervalUsesEffectiveActivation(t *testing.T) {
+ ctx := context.Background()
+ customInterval := 10 * time.Minute
+ instance := &store.InstanceMessage{
+ Metadata: &storepb.Instance{
+ Activation: false,
+ SyncInterval: durationpb.New(customInterval),
+ },
+ }
+ s := &Syncer{}
+
+ require.Equal(t, defaultSyncInterval, s.getOrDefaultSyncInterval(ctx, instance))
+
+ instance.Metadata.Activation = true
+ require.Equal(t, customInterval, s.getOrDefaultSyncInterval(ctx, instance))
+}
diff --git a/backend/server/grpc_routes.go b/backend/server/grpc_routes.go
index 416f110318..da4d6ff8a0 100644
--- a/backend/server/grpc_routes.go
+++ b/backend/server/grpc_routes.go
@@ -95,7 +95,7 @@ func configureGrpcRouters(
celService := apiv1.NewCelService()
databaseCatalogService := apiv1.NewDatabaseCatalogService(stores)
databaseGroupService := apiv1.NewDatabaseGroupService(stores, licenseService)
- databaseService := apiv1.NewDatabaseService(stores, schemaSyncer, profile, iamManager)
+ databaseService := apiv1.NewDatabaseService(stores, schemaSyncer, profile, iamManager, licenseService)
groupService := apiv1.NewGroupService(stores, iamManager, licenseService)
identityProviderService := apiv1.NewIdentityProviderService(stores, licenseService, profile)
instanceRoleService := apiv1.NewInstanceRoleService(stores)
diff --git a/docs/superpowers/plans/2026-04-28-unified-instance-license.md b/docs/superpowers/plans/2026-04-28-unified-instance-license.md
new file mode 100644
index 0000000000..fd38f65882
--- /dev/null
+++ b/docs/superpowers/plans/2026-04-28-unified-instance-license.md
@@ -0,0 +1,799 @@
+# Unified Instance License Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Make licenses whose effective registration cap is less than or equal to their effective activated cap behave and present as one-number instance licenses.
+
+**Architecture:** Add one centralized backend license-mode helper, then use it to compute effective activation without mutating stored instance metadata. Mirror the same effective-limit rule in the frontend subscription store so feature guards and settings pages hide assignment-oriented UI in unified mode while legacy split-cap licenses keep current behavior.
+
+**Tech Stack:** Go backend services and tests, Connect v1 API, Pinia/Vue subscription store, React settings/components, Vitest frontend tests.
+
+---
+
+## File Structure
+
+- Modify `backend/enterprise/license.go`: add `IsUnifiedInstanceLicense` and make `IsFeatureEnabledForInstance` use effective activation.
+- Add `backend/enterprise/license_test.go`: unit coverage for unified limit comparison, feature gating, and `CreateLicense` equal-count claims.
+- Modify `backend/api/v1/instance_service.go`: skip activation quota checks in unified mode and return effective activation for instance service responses.
+- Modify `backend/api/v1/instance_service_converter.go`: add a small helper to override response activation without changing store metadata.
+- Modify `backend/api/v1/actuator_service.go`: report all registered instances as activated in unified mode.
+- Modify `frontend/src/store/modules/v1/subscription.ts`: add `hasUnifiedInstanceLicense` and use it in instance feature/missing-license helpers.
+- Modify `frontend/src/react/pages/settings/SubscriptionPage.tsx`: show one-number instance quota and hide assignment sheet trigger in unified mode.
+- Modify `frontend/src/react/components/FeatureAttention.tsx`: prevent assignment sheet rendering/action in unified mode through store helpers.
+- Modify `frontend/src/react/components/instance/InstanceFormBody.tsx`: hide the activation toggle in unified mode.
+- Add focused frontend tests in `frontend/src/react/components/FeatureAttention.test.tsx` and a new `frontend/src/store/modules/v1/subscription.test.ts`.
+
+## Task 1: Backend Unified License Helper
+
+**Files:**
+- Modify: `backend/enterprise/license.go`
+- Add: `backend/enterprise/license_test.go`
+
+- [ ] **Step 1: Write failing tests for the normalized limit rule**
+
+Add `backend/enterprise/license_test.go` in package `enterprise` with table tests for a pure helper:
+
+```go
+package enterprise
+
+import (
+ "math"
+ "testing"
+)
+
+func TestIsUnifiedInstanceLimit(t *testing.T) {
+ tests := []struct {
+ name string
+ instanceLimit int
+ activatedLimit int
+ want bool
+ }{
+ {name: "equal finite caps", instanceLimit: 10, activatedLimit: 10, want: true},
+ {name: "activated cap larger than registration cap", instanceLimit: 10, activatedLimit: 20, want: true},
+ {name: "split cap", instanceLimit: 50, activatedLimit: 20, want: false},
+ {name: "unlimited both sides", instanceLimit: math.MaxInt, activatedLimit: math.MaxInt, want: true},
+ {name: "unlimited registration finite activation", instanceLimit: math.MaxInt, activatedLimit: 20, want: false},
+ {name: "finite registration unlimited activation", instanceLimit: 20, activatedLimit: math.MaxInt, want: true},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := isUnifiedInstanceLimit(tt.instanceLimit, tt.activatedLimit); got != tt.want {
+ t.Fatalf("isUnifiedInstanceLimit(%d, %d) = %v, want %v", tt.instanceLimit, tt.activatedLimit, got, tt.want)
+ }
+ })
+ }
+}
+```
+
+- [ ] **Step 2: Run the failing backend unit test**
+
+Run:
+
+```bash
+go test -v -count=1 ./backend/enterprise -run ^TestIsUnifiedInstanceLimit$
+```
+
+Expected: fail because `isUnifiedInstanceLimit` is undefined.
+
+- [ ] **Step 3: Implement the helper**
+
+In `backend/enterprise/license.go`, add:
+
+```go
+func isUnifiedInstanceLimit(instanceLimit, activatedInstanceLimit int) bool {
+ return instanceLimit <= activatedInstanceLimit
+}
+
+// IsUnifiedInstanceLicense returns whether every registrable instance is effectively activated.
+func (s *LicenseService) IsUnifiedInstanceLicense(ctx context.Context, workspaceID string) bool {
+ return isUnifiedInstanceLimit(
+ s.GetInstanceLimit(ctx, workspaceID),
+ s.GetActivatedInstanceLimit(ctx, workspaceID),
+ )
+}
+```
+
+- [ ] **Step 4: Run the helper test**
+
+Run:
+
+```bash
+go test -v -count=1 ./backend/enterprise -run ^TestIsUnifiedInstanceLimit$
+```
+
+Expected: pass.
+
+- [ ] **Step 5: Commit Task 1**
+
+```bash
+gofmt -w backend/enterprise/license.go backend/enterprise/license_test.go
+git add backend/enterprise/license.go backend/enterprise/license_test.go
+git commit -m "feat: add unified instance license helper"
+```
+
+## Task 2: Backend Effective Feature Activation
+
+**Files:**
+- Modify: `backend/enterprise/license.go`
+- Modify: `backend/enterprise/license_test.go`
+
+- [ ] **Step 1: Write failing tests for instance feature gating**
+
+Extend `backend/enterprise/license_test.go` with tests that construct a `LicenseService` with cached subscriptions. Use package `enterprise` so tests can seed the cache directly:
+
+```go
+import (
+ "context"
+ "time"
+
+ "github.com/hashicorp/golang-lru/v2/expirable"
+
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"
+ "github.com/bytebase/bytebase/backend/store"
+)
+
+func newTestLicenseService(sub *v1pb.Subscription) *LicenseService {
+ s := &LicenseService{
+ cache: expirable.NewLRU[string, *v1pb.Subscription](8, nil, time.Minute),
+ }
+ s.cache.Add(licenseCacheKey("test-workspace"), sub)
+ return s
+}
+
+func TestIsFeatureEnabledForInstanceUnifiedLicense(t *testing.T) {
+ ctx := context.Background()
+ instance := &store.InstanceMessage{
+ ResourceID: "prod",
+ Workspace: "test-workspace",
+ Metadata: &storepb.Instance{
+ Activation: false,
+ },
+ }
+ service := newTestLicenseService(&v1pb.Subscription{
+ Plan: v1pb.PlanType_ENTERPRISE,
+ Instances: 10,
+ ActiveInstances: 10,
+ })
+
+ if err := service.IsFeatureEnabledForInstance(ctx, "test-workspace", v1pb.PlanFeature_FEATURE_DATA_MASKING, instance); err != nil {
+ t.Fatalf("unified license should enable feature for inactive stored instance: %v", err)
+ }
+}
+
+func TestIsFeatureEnabledForInstanceSplitLicense(t *testing.T) {
+ ctx := context.Background()
+ instance := &store.InstanceMessage{
+ ResourceID: "prod",
+ Workspace: "test-workspace",
+ Metadata: &storepb.Instance{
+ Activation: false,
+ },
+ }
+ service := newTestLicenseService(&v1pb.Subscription{
+ Plan: v1pb.PlanType_ENTERPRISE,
+ Instances: 50,
+ ActiveInstances: 20,
+ })
+
+ if err := service.IsFeatureEnabledForInstance(ctx, "test-workspace", v1pb.PlanFeature_FEATURE_DATA_MASKING, instance); err == nil {
+ t.Fatal("split license should still require stored activation")
+ }
+}
+```
+
+- [ ] **Step 2: Run the failing feature-gate tests**
+
+Run:
+
+```bash
+go test -v -count=1 ./backend/enterprise -run '^(TestIsFeatureEnabledForInstanceUnifiedLicense|TestIsFeatureEnabledForInstanceSplitLicense)$'
+```
+
+Expected: unified-license test fails because the implementation still requires stored activation.
+
+- [ ] **Step 3: Implement effective activation in `IsFeatureEnabledForInstance`**
+
+In `backend/enterprise/license.go`, change the final activation check:
+
+```go
+ if s.IsUnifiedInstanceLicense(ctx, workspaceID) {
+ return nil
+ }
+ if !instance.Metadata.GetActivation() {
+ return errors.Errorf(`feature "%s" is not available for instance %s, please assign license to the instance to enable it`, f.String(), instance.ResourceID)
+ }
+ return nil
+```
+
+- [ ] **Step 4: Add and run `CreateLicense` equal-claim regression test**
+
+Extract the literal `Claims` construction in `CreateLicense` into:
+
+```go
+func newLicenseClaims(params *LicenseParams) *Claims {
+ return &Claims{
+ Plan: params.Plan,
+ Seats: params.Seats,
+ ActiveInstances: params.Instances,
+ Instances: params.Instances,
+ WorkspaceID: params.WorkspaceID,
+ }
+}
+```
+
+Then have `CreateLicense` call:
+
+```go
+c := newLicenseClaims(params)
+```
+
+Add this regression test:
+
+```go
+func TestCreateLicenseUsesEqualInstanceClaims(t *testing.T) {
+ claims := newLicenseClaims(&LicenseParams{
+ Plan: v1pb.PlanType_ENTERPRISE.String(),
+ Seats: 5,
+ Instances: 10,
+ WorkspaceID: "test-workspace",
+ })
+ if claims.Instances != 10 {
+ t.Fatalf("Instances = %d, want 10", claims.Instances)
+ }
+ if claims.ActiveInstances != 10 {
+ t.Fatalf("ActiveInstances = %d, want 10", claims.ActiveInstances)
+ }
+}
+```
+
+- [ ] **Step 5: Run backend enterprise tests**
+
+Run:
+
+```bash
+go test -v -count=1 ./backend/enterprise
+```
+
+Expected: pass.
+
+- [ ] **Step 6: Commit Task 2**
+
+```bash
+gofmt -w backend/enterprise/license.go backend/enterprise/license_test.go
+git add backend/enterprise/license.go backend/enterprise/license_test.go
+git commit -m "feat: treat unified instance licenses as activated"
+```
+
+## Task 3: Backend Instance And Actuator API Output
+
+**Files:**
+- Modify: `backend/api/v1/instance_service_converter.go`
+- Modify: `backend/api/v1/instance_service.go`
+- Modify: `backend/api/v1/actuator_service.go`
+
+- [ ] **Step 1: Add an effective activation converter helper**
+
+In `backend/api/v1/instance_service_converter.go`, add:
+
+```go
+func convertToV1InstanceWithEffectiveActivation(instance *store.InstanceMessage, effectiveActivation bool) *v1pb.Instance {
+ result := convertToV1Instance(instance)
+ result.Activation = effectiveActivation
+ return result
+}
+```
+
+- [ ] **Step 2: Add an `InstanceService` conversion method**
+
+In `backend/api/v1/instance_service.go`, near helper methods, add:
+
+```go
+func (s *InstanceService) convertToV1Instance(ctx context.Context, instance *store.InstanceMessage) *v1pb.Instance {
+ if s.licenseService.IsUnifiedInstanceLicense(ctx, common.GetWorkspaceIDFromContext(ctx)) {
+ return convertToV1InstanceWithEffectiveActivation(instance, true)
+ }
+ return convertToV1Instance(instance)
+}
+```
+
+- [ ] **Step 3: Replace instance service response conversions**
+
+In `backend/api/v1/instance_service.go`, replace response call sites such as:
+
+```go
+result := convertToV1Instance(instance)
+```
+
+with:
+
+```go
+result := s.convertToV1Instance(ctx, instance)
+```
+
+Also replace list appends:
+
+```go
+ins := convertToV1Instance(instance)
+```
+
+with:
+
+```go
+ins := s.convertToV1Instance(ctx, instance)
+```
+
+Do not change `convertToStoreInstance`; create/update requests should still preserve incoming stored activation.
+
+- [ ] **Step 4: Skip activation quota checks in unified mode**
+
+In create/update activation quota checks in `backend/api/v1/instance_service.go`, guard the check:
+
+```go
+if instanceMessage.Metadata.GetActivation() && !s.licenseService.IsUnifiedInstanceLicense(ctx, workspaceID) {
+ activatedInstanceLimit := s.licenseService.GetActivatedInstanceLimit(ctx, workspaceID)
+ count, err := s.store.GetActivatedInstanceCount(ctx, workspaceID)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, err)
+ }
+ if count >= activatedInstanceLimit {
+ return nil, connect.NewError(connect.CodeResourceExhausted, errors.Errorf(instanceExceededError, activatedInstanceLimit))
+ }
+}
+```
+
+For update:
+
+```go
+if updateActivation && !s.licenseService.IsUnifiedInstanceLicense(ctx, workspaceID) {
+ activatedInstanceLimit := s.licenseService.GetActivatedInstanceLimit(ctx, workspaceID)
+ count, err := s.store.GetActivatedInstanceCount(ctx, workspaceID)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, err)
+ }
+ if count >= activatedInstanceLimit {
+ return nil, connect.NewError(connect.CodeResourceExhausted, errors.Errorf(instanceExceededError, activatedInstanceLimit))
+ }
+}
+```
+
+Remove the existing unconditional `activatedInstanceLimit := ...` lines near these blocks after moving the assignment inside the guarded branch.
+
+- [ ] **Step 5: Update actuator stats**
+
+In `backend/api/v1/actuator_service.go`, after computing `activeInstanceCount`, set activation count by mode:
+
+```go
+activeInstanceCount, err := s.store.CountActiveInstances(ctx, workspaceID)
+if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to count total instance"))
+}
+serverInfo.TotalInstanceCount = int32(activeInstanceCount)
+
+if s.licenseService.IsUnifiedInstanceLicense(ctx, workspaceID) {
+ serverInfo.ActivatedInstanceCount = int32(activeInstanceCount)
+} else {
+ activatedInstanceCount, err := s.store.GetActivatedInstanceCount(ctx, workspaceID)
+ if err != nil {
+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to count activated instance"))
+ }
+ serverInfo.ActivatedInstanceCount = int32(activatedInstanceCount)
+}
+```
+
+Preserve nearby unrelated actuator fields.
+
+- [ ] **Step 6: Run targeted compile tests**
+
+Run:
+
+```bash
+go test -v -count=1 ./backend/api/v1 -run '^(TestNonExistent)$'
+```
+
+Expected: package compiles and reports no tests to run or passes existing package setup. If this package requires external services and cannot run cleanly, use:
+
+```bash
+go test -run '^$' ./backend/api/v1
+```
+
+Expected: compile succeeds.
+
+- [ ] **Step 7: Commit Task 3**
+
+```bash
+gofmt -w backend/api/v1/instance_service_converter.go backend/api/v1/instance_service.go backend/api/v1/actuator_service.go
+git add backend/api/v1/instance_service_converter.go backend/api/v1/instance_service.go backend/api/v1/actuator_service.go
+git commit -m "feat: expose effective activation for unified licenses"
+```
+
+## Task 4: Frontend Store Unified Mode
+
+**Files:**
+- Modify: `frontend/src/store/modules/v1/subscription.ts`
+
+- [ ] **Step 1: Add the computed mode**
+
+In `frontend/src/store/modules/v1/subscription.ts`, after `instanceLicenseCount`, add:
+
+```ts
+ const hasUnifiedInstanceLicense = computed(() => {
+ return instanceCountLimit.value <= instanceLicenseCount.value;
+ });
+```
+
+- [ ] **Step 2: Use unified mode in feature helpers**
+
+Update `hasInstanceFeature`:
+
+```ts
+ return checkInstanceFeature(
+ currentPlan.value,
+ feature,
+ hasUnifiedInstanceLicense.value || instance.activation
+ );
+```
+
+Update `instanceMissingLicense`:
+
+```ts
+ if (hasUnifiedInstanceLicense.value) {
+ return false;
+ }
+ return hasFeature(feature) && !instance.activation;
+```
+
+- [ ] **Step 3: Return the computed value from the store**
+
+Add `hasUnifiedInstanceLicense` to the returned getters:
+
+```ts
+ hasUnifiedInstanceLicense,
+```
+
+- [ ] **Step 4: Run frontend type check for the changed store**
+
+Run:
+
+```bash
+pnpm --dir frontend type-check
+```
+
+Expected: pass. If unrelated type errors already exist, capture the first unrelated error and continue only after confirming it is not caused by this change.
+
+- [ ] **Step 5: Commit Task 4**
+
+```bash
+git add frontend/src/store/modules/v1/subscription.ts
+git commit -m "feat(frontend): derive unified instance license mode"
+```
+
+## Task 5: Frontend Presentation Updates
+
+**Files:**
+- Modify: `frontend/src/react/pages/settings/SubscriptionPage.tsx`
+- Modify: `frontend/src/react/components/FeatureAttention.tsx`
+- Modify: `frontend/src/react/components/instance/InstanceFormBody.tsx`
+- Do not modify `frontend/src/components/WorkspaceInstanceLicenseStats.vue`; `rg "WorkspaceInstanceLicenseStats" frontend/src` shows no active references in this worktree.
+
+- [ ] **Step 1: Update subscription page stats**
+
+In `frontend/src/react/pages/settings/SubscriptionPage.tsx`, read the store mode:
+
+```ts
+ const hasUnifiedInstanceLicense = useVueState(
+ () => subscriptionStore.hasUnifiedInstanceLicense
+ );
+```
+
+Pass it into `InstanceLicenseStats`:
+
+```tsx
+ hasUnifiedInstanceLicense={hasUnifiedInstanceLicense}
+```
+
+Update props and render one-number stats when free or unified:
+
+```tsx
+function InstanceLicenseStats({
+ planType,
+ hasUnifiedInstanceLicense,
+ instanceCountLimit,
+ activatedCount,
+ totalLicenseCount,
+ onManageInstanceLicenses,
+}: {
+ planType: string;
+ hasUnifiedInstanceLicense: boolean;
+ instanceCountLimit: number;
+ activatedCount: number;
+ totalLicenseCount: string;
+ onManageInstanceLicenses: () => void;
+}) {
+ const { t } = useTranslation();
+
+ if (planType === "FREE" || hasUnifiedInstanceLicense) {
+ return (
+ <div className="flex flex-col text-left">
+ <dt className="text-main">{t("subscription.max-instance-count")}</dt>
+ <div className="mt-1 text-4xl">{instanceCountLimit}</div>
+ </div>
+ );
+ }
+```
+
+Only render `InstanceAssignmentSheet` when not unified:
+
+```tsx
+ {!hasUnifiedInstanceLicense && (
+ <InstanceAssignmentSheet
+ open={showInstanceAssignmentSheet}
+ onOpenChange={setShowInstanceAssignmentSheet}
+ />
+ )}
+```
+
+- [ ] **Step 2: Update feature attention assignment paths**
+
+In `frontend/src/react/components/FeatureAttention.tsx`, read the mode:
+
+```ts
+ const hasUnifiedInstanceLicense = useVueState(
+ () => subscriptionStore.hasUnifiedInstanceLicense
+ );
+```
+
+Update missing-license existence:
+
+```ts
+ const existInstanceWithoutLicense = useVueState(
+ () =>
+ !subscriptionStore.hasUnifiedInstanceLicense &&
+ actuatorStore.totalInstanceCount > actuatorStore.activatedInstanceCount &&
+ instanceLimitFeature.has(feature)
+ );
+```
+
+Only render the assignment sheet when not unified:
+
+```tsx
+ {!hasUnifiedInstanceLicense && (
+ <InstanceAssignmentSheet
+ open={showInstanceAssignment}
+ selectedInstanceList={instance ? [instance.name] : []}
+ onOpenChange={setShowInstanceAssignment}
+ />
+ )}
+```
+
+- [ ] **Step 3: Hide instance activation toggle in unified mode**
+
+In `frontend/src/react/components/instance/InstanceFormBody.tsx`, add a store mode read near existing subscription values:
+
+```ts
+ const hasUnifiedInstanceLicense = subscriptionStore.hasUnifiedInstanceLicense;
+```
+
+Update the activation toggle condition:
+
+```tsx
+ {subscriptionStore.currentPlan !== PlanType.FREE &&
+ !hasUnifiedInstanceLicense &&
+ allowEdit && (
+```
+
+- [ ] **Step 4: Run frontend checks**
+
+Run:
+
+```bash
+pnpm --dir frontend fix
+pnpm --dir frontend type-check
+pnpm --dir frontend test -- FeatureAttention
+```
+
+Expected: formatting succeeds, type-check passes, and the targeted FeatureAttention tests pass.
+
+- [ ] **Step 5: Commit Task 5**
+
+```bash
+git add frontend/src/store/modules/v1/subscription.ts frontend/src/react/pages/settings/SubscriptionPage.tsx frontend/src/react/components/FeatureAttention.tsx frontend/src/react/components/instance/InstanceFormBody.tsx
+git commit -m "feat(frontend): hide license assignment in unified mode"
+```
+
+## Task 6: Focused Regression Tests
+
+**Files:**
+- Modify: `frontend/src/react/components/FeatureAttention.test.tsx`
+- Add: `frontend/src/store/modules/v1/subscription.test.ts`
+
+- [ ] **Step 1: Add FeatureAttention unified-mode test**
+
+In `frontend/src/react/components/FeatureAttention.test.tsx`, extend the mocked subscription store with:
+
+```ts
+hasUnifiedInstanceLicense: false,
+```
+
+Add a test:
+
+```tsx
+test("does not show assignment attention in unified instance license mode", () => {
+ mocks.hasFeature.mockReturnValue(true);
+ mocks.instanceMissingLicense.mockReturnValue(false);
+ mocks.hasUnifiedInstanceLicense = true;
+ mocks.totalInstanceCount = 2;
+ mocks.activatedInstanceCount = 2;
+
+ render(<FeatureAttention feature={PlanFeature.FEATURE_DATA_MASKING} />);
+
+ expect(screen.queryByText("subscription.instance-assignment.assign-license")).not.toBeInTheDocument();
+});
+```
+
+Use the existing mock object in `FeatureAttention.test.tsx`; add the `hasUnifiedInstanceLicense` field beside the existing mocked subscription store methods and reset it to `false` in `beforeEach`.
+
+- [ ] **Step 2: Add store helper tests**
+
+Create `frontend/src/store/modules/v1/subscription.test.ts`:
+
+```ts
+import { create } from "@bufbuild/protobuf";
+import { createPinia, setActivePinia } from "pinia";
+import { beforeEach, describe, expect, test } from "vitest";
+import { useSubscriptionV1Store } from "./subscription";
+import { InstanceSchema } from "@/types/proto-es/v1/instance_service_pb";
+import {
+ PlanFeature,
+ PlanType,
+ SubscriptionSchema,
+} from "@/types/proto-es/v1/subscription_service_pb";
+
+describe("useSubscriptionV1Store unified instance license", () => {
+ beforeEach(() => {
+ setActivePinia(createPinia());
+ });
+
+ test("computes unified mode from effective limits", () => {
+ const store = useSubscriptionV1Store();
+ store.setSubscription(
+ create(SubscriptionSchema, {
+ plan: PlanType.ENTERPRISE,
+ instances: 10,
+ activeInstances: 10,
+ })
+ );
+
+ expect(store.hasUnifiedInstanceLicense).toBe(true);
+
+ store.setSubscription(
+ create(SubscriptionSchema, {
+ plan: PlanType.ENTERPRISE,
+ instances: 50,
+ activeInstances: 20,
+ })
+ );
+
+ expect(store.hasUnifiedInstanceLicense).toBe(false);
+ });
+
+ test("does not report missing instance license in unified mode", () => {
+ const store = useSubscriptionV1Store();
+ store.setSubscription(
+ create(SubscriptionSchema, {
+ plan: PlanType.ENTERPRISE,
+ instances: 10,
+ activeInstances: 10,
+ })
+ );
+
+ const inactiveInstance = create(InstanceSchema, {
+ name: "instances/prod",
+ title: "prod",
+ activation: false,
+ });
+
+ expect(
+ store.instanceMissingLicense(
+ PlanFeature.FEATURE_DATA_MASKING,
+ inactiveInstance
+ )
+ ).toBe(false);
+ });
+});
+```
+
+- [ ] **Step 3: Run targeted frontend tests**
+
+Run:
+
+```bash
+pnpm --dir frontend test -- FeatureAttention
+pnpm --dir frontend test -- subscription.test
+```
+
+Expected: targeted tests pass.
+
+- [ ] **Step 4: Commit Task 6**
+
+```bash
+git add frontend/src/react/components/FeatureAttention.test.tsx frontend/src/store/modules/v1/subscription.test.ts
+git commit -m "test: cover unified instance license presentation"
+```
+
+## Task 7: Final Verification
+
+**Files:**
+- No source edits expected.
+
+- [ ] **Step 1: Run Go formatting**
+
+Run:
+
+```bash
+gofmt -w backend/enterprise/license.go backend/enterprise/license_test.go backend/api/v1/instance_service_converter.go backend/api/v1/instance_service.go backend/api/v1/actuator_service.go
+```
+
+Expected: no output.
+
+- [ ] **Step 2: Run backend tests**
+
+Run:
+
+```bash
+go test -v -count=1 ./backend/enterprise
+go test -run '^$' ./backend/api/v1
+```
+
+Expected: pass or compile successfully for `backend/api/v1`.
+
+- [ ] **Step 3: Run linter repeatedly until clean**
+
+Run:
+
+```bash
+golangci-lint run --allow-parallel-runners
+```
+
+Expected: no issues. If issues are reported, run:
+
+```bash
+golangci-lint run --fix --allow-parallel-runners
+golangci-lint run --allow-parallel-runners
+```
+
+Repeat until no issues remain.
+
+- [ ] **Step 4: Run frontend validation**
+
+Run:
+
+```bash
+pnpm --dir frontend fix
+pnpm --dir frontend check
+pnpm --dir frontend type-check
+pnpm --dir frontend test
+```
+
+Expected: pass.
+
+- [ ] **Step 5: Run backend build**
+
+Run:
+
+```bash
+go build -ldflags "-w -s" -p=16 -o ./bytebase-build/bytebase ./backend/bin/server/main.go
+```
+
+Expected: build succeeds.
+
+- [ ] **Step 6: Final status check**
+
+Run:
+
+```bash
+git status --short
+git log --oneline -5
+```
+
+Expected: only intended source/test changes are present or committed. Unrelated pre-existing untracked files remain untouched.
diff --git a/docs/superpowers/specs/2026-04-28-unified-instance-license-design.md b/docs/superpowers/specs/2026-04-28-unified-instance-license-design.md
new file mode 100644
index 0000000000..cb8de52a28
--- /dev/null
+++ b/docs/superpowers/specs/2026-04-28-unified-instance-license-design.md
@@ -0,0 +1,194 @@
+# Unified Instance License Design
+
+## Goal
+
+Move new and equal-cap licenses to a one-number product experience while preserving the existing two-field license schema and legacy split-cap behavior.
+
+The immediate product contract is: when every registrable instance can receive paid instance-scoped features, Bytebase should not expose an assignment step and should treat every registered instance as activated. This delivers the sales and UX simplification without a database migration, proto change, or JWT schema change.
+
+## Context
+
+Bytebase licenses currently carry two instance fields:
+
+- `Claims.Instances` / JWT `instance`: registration cap.
+- `Claims.ActiveInstances` / JWT `instanceCount`: activated or paid-feature instance cap.
+
+Runtime code also stores per-instance activation in instance metadata. Several paid instance-scoped features, including data masking, read-only connections, custom sync time, and external secret manager, check this activation state.
+
+The long-term goal is a single instance number. The first phase should not collapse the schema or migrate customers. It should recognize licenses where the effective registration cap is less than or equal to the effective activated cap, then make those licenses behave like one-number licenses.
+
+## Product Contract
+
+Define unified instance license mode as:
+
+```text
+effective registration cap <= effective activated cap
+```
+
+The comparison must use existing effective limit semantics, not raw JWT values:
+
+- Backend registration cap: `LicenseService.GetInstanceLimit(ctx, workspaceID)`.
+- Backend activated cap: `LicenseService.GetActivatedInstanceLimit(ctx, workspaceID)`.
+- Frontend registration cap: `subscriptionStore.instanceCountLimit`.
+- Frontend activated cap: `subscriptionStore.instanceLicenseCount`.
+
+This handles zero and unlimited values consistently with existing plan and license fallback rules. For example, an unlimited registration cap and unlimited activated cap is unified; an unlimited registration cap with only 20 activated instances is legacy split-cap.
+
+In unified mode:
+
+- Every registered instance is effectively activated.
+- Stored instance metadata is not mutated.
+- Users should not see assignment-oriented entry points.
+- If a workspace later receives a legacy split-cap license, the stored activation state becomes effective again.
+
+In legacy split-cap mode:
+
+- Existing runtime behavior remains.
+- Existing UI and wording remain for this phase.
+- Customers can still choose which instances receive paid instance-scoped features.
+
+## Backend Behavior
+
+Add a centralized helper on `LicenseService`:
+
+```go
+func (s *LicenseService) IsUnifiedInstanceLicense(ctx context.Context, workspaceID string) bool
+```
+
+It should return:
+
+```text
+GetInstanceLimit(ctx, workspaceID) <= GetActivatedInstanceLimit(ctx, workspaceID)
+```
+
+Use this helper in activation-sensitive paths.
+
+Feature gates:
+
+- `IsFeatureEnabledForInstance` still checks plan entitlement first.
+- In unified mode, skip the stored `instance.Metadata.GetActivation()` check.
+- In legacy split-cap mode, keep the existing activation check and error behavior.
+
+Instance API responses:
+
+- Public v1 instance responses should return `activation=true` in unified mode.
+- The stored metadata remains unchanged.
+- In legacy split-cap mode, return the stored activation state.
+
+Actuator stats:
+
+- In unified mode, return `activatedInstanceCount = totalInstanceCount`.
+- In legacy split-cap mode, keep counting stored activated instances.
+
+Activation quota checks:
+
+- In unified mode, skip quota checks that specifically guard turning `activation` on.
+- Instance creation remains protected by the registration cap through `GetInstanceLimit`.
+- In legacy split-cap mode, keep current activation quota checks.
+
+This phase should not change database schema, migration files, proto definitions, JWT parsing, or uploaded-license compatibility.
+
+## Frontend Behavior
+
+Frontend should compute presentation mode from effective store values:
+
+```ts
+const hasUnifiedInstanceLicense = computed(() => {
+ return subscriptionStore.instanceCountLimit <= subscriptionStore.instanceLicenseCount;
+});
+```
+
+Do not compare raw `subscription.instances` and `subscription.activeInstances` for presentation mode.
+
+In unified mode:
+
+- Hide assignment-oriented entry points such as "Assign License" buttons, assignment sheet triggers, and missing-license CTAs.
+- Do not show "Assigned / Total Instance License" as the main subscription metric.
+- Show a single instance quota based on `instanceCountLimit`.
+- Omit or disable the activation toggle in instance forms because activation is effectively true.
+- Ensure local feature guard helpers do not show missing-license states when the plan has the feature and the license is unified.
+
+In legacy split-cap mode:
+
+- Keep existing UI and copy unchanged.
+- Assignment sheet, activation toggle, missing-license warnings, and activated/total metric remain available.
+- Do not rename or redesign legacy assignment workflows in this phase.
+
+Backend behavior remains authoritative. Frontend mode detection is for presentation and avoiding misleading assignment UI.
+
+## License Issuance And Legacy Handling
+
+Keep the license schema unchanged:
+
+```go
+ActiveInstances int `json:"instanceCount"`
+Instances int `json:"instance"`
+```
+
+New-license policy:
+
+- New SaaS licenses should issue equal caps.
+- `CreateLicense` should preserve the current behavior of setting both claims from the same `LicenseParams.Instances`.
+- Add regression coverage so SaaS license generation does not accidentally diverge the two claims later.
+- Manual and self-host license-generation tooling or process should issue equal caps for new licenses.
+
+Legacy handling:
+
+- Existing and uploaded unequal licenses remain valid.
+- If effective registration cap is greater than effective activated cap, Bytebase remains in legacy split-cap behavior.
+- Do not automatically mutate instance activation.
+- Do not automatically shrink customer entitlement.
+- Do not automatically expand customer entitlement.
+- Renewal or migration to equal-count licenses happens through normal commercial or account workflow.
+
+## Phases
+
+Phase 1: effective unified mode.
+
+- Add the normalized backend helper.
+- Apply effective activation behavior in feature gates, instance API responses, actuator stats, and activation quota checks.
+- Update frontend presentation to avoid assignment-oriented UI in unified mode.
+- Keep schema, stored metadata, uploaded licenses, and split-cap behavior compatible.
+
+Phase 2: issuance policy hardening.
+
+- Ensure every supported new-license issuing path produces equal registration and activated caps.
+- Document or update manual license-generation process for self-host licenses.
+- Keep legacy unequal licenses accepted.
+
+Phase 3: legacy drain.
+
+- Identify workspaces or accounts still using split-cap licenses.
+- Migrate them at renewal or through explicit account action.
+- Avoid silent entitlement shrink or silent free expansion.
+
+Phase 4: one-number cleanup.
+
+- After split-cap licenses are gone, collapse product and code concepts to one instance count.
+- Remove assignment UI and activation-based feature gating.
+- Deprecate or ignore the old JWT field after a compatibility window.
+
+This design covers Phase 1 and records the later direction. Phases 2 through 4 should be planned separately.
+
+## Testing
+
+Backend tests should cover:
+
+- `IsUnifiedInstanceLicense` returns true for equal caps, more activated than registered, and unlimited/unlimited.
+- `IsUnifiedInstanceLicense` returns false for split-cap licenses.
+- `IsFeatureEnabledForInstance` allows instance-scoped features for stored `activation=false` instances in unified mode.
+- The same feature check still fails in legacy split-cap mode when stored `activation=false`.
+- Instance API responses return `activation=true` in unified mode without mutating stored metadata.
+- Actuator info returns `activatedInstanceCount = totalInstanceCount` in unified mode.
+- Activation quota checks are skipped only for unified mode.
+- SaaS `CreateLicense` emits equal `instance` and `instanceCount` claims.
+
+Frontend tests should cover:
+
+- Unified mode is computed from effective values, not raw subscription fields.
+- Missing-license warnings do not appear in unified mode.
+- Assignment entry points are hidden in unified mode.
+- Instance forms do not expose an actionable activation toggle in unified mode.
+- Legacy split-cap mode keeps existing assignment UI.
+
+Final implementation verification should follow `AGENTS.md`: run relevant Go formatting, linting, tests, build, and frontend fix/check/type-check/test commands for modified files.
diff --git a/frontend/src/components/v2/Model/Instance/InstanceV1Table/InstanceOperations.vue b/frontend/src/components/v2/Model/Instance/InstanceV1Table/InstanceOperations.vue
index 27ec0fad96..79011bafff 100644
--- a/frontend/src/components/v2/Model/Instance/InstanceV1Table/InstanceOperations.vue
+++ b/frontend/src/components/v2/Model/Instance/InstanceV1Table/InstanceOperations.vue
@@ -62,7 +62,6 @@ import {
import type { Permission } from "@/types";
import type { Instance } from "@/types/proto-es/v1/instance_service_pb";
import { UpdateInstanceRequestSchema } from "@/types/proto-es/v1/instance_service_pb";
-import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";
interface Action {
icon?: VNode;
@@ -96,7 +95,7 @@ const state = reactive<LocalState>({
});
const canAssignLicense = computed(() => {
- return subscriptionStore.currentPlan !== PlanType.FREE;
+ return subscriptionStore.hasSplitInstanceLicense;
});
const actions = computed((): Action[] => {
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 91949e0e1a..8ae1754fe3 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2651,10 +2651,10 @@
"n-license-remain": "{n} remaining",
"require-license": "Require instance license",
"success-notification": "Successfully update license assignment",
+ "used-and-total-instance": "Active / Total Instance Limit",
"used-and-total-license": "Assigned / Total Instance License",
"used-and-total-user": "Active / Total User Limit"
},
- "max-instance-count": "Max Instance Count",
"overuse-modal": {
"description": "You are using features unavailable in the {plan}. Upgrade now to ensure continued access:"
},
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 6a2ad447d3..306f024fb3 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -2651,10 +2651,10 @@
"n-license-remain": "permanecer {n}",
"require-license": "Requerir licencia de instancia",
"success-notification": "Actualizar correctamente la asignación de licencia",
+ "used-and-total-instance": "Límite de instancias activas/totales",
"used-and-total-license": "Licencia asignada / total",
"used-and-total-user": "Límite de usuarios activos/totales"
},
- "max-instance-count": "Cantidad máxima de instancias",
"overuse-modal": {
"description": "Está utilizando una función que actualmente no está incluida en {plan}. Actualice ahora para evitar interrupciones:"
},
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 5671529beb..5fa8271d13 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -2651,10 +2651,10 @@
"n-license-remain": "残り {n}",
"require-license": "インスタンスライセンスが必要です",
"success-notification": "ライセンスの割り当てが正常に更新されました",
+ "used-and-total-instance": "アクティブ/合計インスタンス制限",
"used-and-total-license": "割り当てられた/合計インスタンスライセンス",
"used-and-total-user": "アクティブ/合計ユーザー制限"
},
- "max-instance-count": "最大インスタンス数",
"overuse-modal": {
"description": "現在「{plan}」に含まれていない機能を使用しています。使用に影響を与えないように、すぐにアップグレードしてください。"
},
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 4640d73a65..ebdd34adbc 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -2651,10 +2651,10 @@
"n-license-remain": "còn lại {n}",
"require-license": "Yêu cầu giấy phép phiên bản",
"success-notification": "Đã cập nhật thành công gán giấy phép",
+ "used-and-total-instance": "Giới hạn phiên bản đang hoạt động / Tổng số",
"used-and-total-license": "Giấy phép phiên bản đã gán / Tổng số",
"used-and-total-user": "Giới hạn người dùng đang hoạt động / Tổng số"
},
- "max-instance-count": "Số lượng phiên bản tối đa",
"overuse-modal": {
"description": "Bạn đang sử dụng các tính năng không có trong {plan}. Nâng cấp ngay để đảm bảo quyền truy cập liên tục:"
},
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index b0b740c9fc..f23e71a44b 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2651,10 +2651,10 @@
"n-license-remain": "剩余 {n} 个",
"require-license": "需要实例证书",
"success-notification": "证书分配更新成功",
+ "used-and-total-instance": "活跃/总实例限制",
"used-and-total-license": "已分配 / 总实例证书",
"used-and-total-user": "活跃/总用户限制"
},
- "max-instance-count": "最大实例数量",
"overuse-modal": {
"description": "您正在使用当前「{plan}」不包含的功能。立即升级避免影响使用。"
},
diff --git a/frontend/src/react/components/FeatureAttention.test.tsx b/frontend/src/react/components/FeatureAttention.test.tsx
index f46eca8e53..83cdb472c9 100644
--- a/frontend/src/react/components/FeatureAttention.test.tsx
+++ b/frontend/src/react/components/FeatureAttention.test.tsx
@@ -51,7 +51,9 @@ vi.mock("@/react/stores/app", () => ({
vi.mock("@/types", () => ({
ENTERPRISE_INQUIRE_LINK,
- instanceLimitFeature: new Set<PlanFeature>(),
+ instanceLimitFeature: new Set<PlanFeature>([
+ PlanFeature.FEATURE_DATA_MASKING,
+ ]),
}));
vi.mock("@/utils", () => ({
@@ -98,6 +100,7 @@ beforeEach(async () => {
selector({
hasInstanceFeature: () => false,
instanceMissingLicense: () => false,
+ hasUnifiedInstanceLicense: () => false,
getMinimumRequiredPlan: () => PlanType.TEAM,
hasFeature: () => false,
})
@@ -140,4 +143,41 @@ describe("FeatureAttention", () => {
openSpy.mockRestore();
unmount();
});
+
+ test("does not show assignment attention in unified instance license mode", () => {
+ mocks.useSubscriptionState.mockReturnValue({
+ isTrialing: false,
+ trialingDays: 14,
+ });
+ mocks.useServerState.mockReturnValue({
+ totalInstanceCount: 2,
+ activatedInstanceCount: 1,
+ });
+ mocks.useAppStore.mockImplementation(
+ (selector: (state: Record<string, unknown>) => unknown) =>
+ selector({
+ hasInstanceFeature: () => true,
+ instanceMissingLicense: () => false,
+ hasUnifiedInstanceLicense: () => true,
+ getMinimumRequiredPlan: () => PlanType.TEAM,
+ hasFeature: () => true,
+ })
+ );
+ const { container, render, unmount } = renderIntoContainer(
+ <FeatureAttention feature={PlanFeature.FEATURE_DATA_MASKING} />
+ );
+
+ render();
+
+ expect(container.querySelector('[role="alert"]')).toBeNull();
+ expect(
+ [...container.querySelectorAll("button")].some((button) =>
+ button.textContent?.includes(
+ "subscription.instance-assignment.assign-license"
+ )
+ )
+ ).toBe(false);
+
+ unmount();
+ });
});
diff --git a/frontend/src/react/components/FeatureAttention.tsx b/frontend/src/react/components/FeatureAttention.tsx
index 60e433a83b..7fe2f85c99 100644
--- a/frontend/src/react/components/FeatureAttention.tsx
+++ b/frontend/src/react/components/FeatureAttention.tsx
@@ -43,6 +43,9 @@ export function FeatureAttention({
const instanceMissingLicense = useAppStore((state) =>
state.instanceMissingLicense(feature, instance)
);
+ const hasUnifiedInstanceLicense = useAppStore((state) =>
+ state.hasUnifiedInstanceLicense()
+ );
const requiredPlan = useAppStore((state) =>
state.getMinimumRequiredPlan(feature)
);
@@ -50,6 +53,7 @@ export function FeatureAttention({
state.hasFeature(feature)
);
const existInstanceWithoutLicense =
+ !hasUnifiedInstanceLicense &&
totalInstanceCount > activatedInstanceCount &&
instanceLimitFeature.has(feature);
@@ -100,7 +104,10 @@ export function FeatureAttention({
actionText = t("subscription.request-n-days-trial", {
days: trialingDays,
});
- } else if (hasWorkspacePermissionV2("bb.instances.update")) {
+ } else if (
+ !hasUnifiedInstanceLicense &&
+ hasWorkspacePermissionV2("bb.instances.update")
+ ) {
actionText = t("subscription.instance-assignment.assign-license");
}
}
@@ -144,11 +151,13 @@ export function FeatureAttention({
)}
</div>
</Alert>
- <InstanceAssignmentSheet
- open={showInstanceAssignment}
- selectedInstanceList={instance ? [instance.name] : []}
- onOpenChange={setShowInstanceAssignment}
- />
+ {!hasUnifiedInstanceLicense && (
+ <InstanceAssignmentSheet
+ open={showInstanceAssignment}
+ selectedInstanceList={instance ? [instance.name] : []}
+ onOpenChange={setShowInstanceAssignment}
+ />
+ )}
</>
);
}
diff --git a/frontend/src/react/components/instance/InstanceFormBody.tsx b/frontend/src/react/components/instance/InstanceFormBody.tsx
index b08e6190f2..4e58b7439c 100644
--- a/frontend/src/react/components/instance/InstanceFormBody.tsx
+++ b/frontend/src/react/components/instance/InstanceFormBody.tsx
@@ -18,6 +18,7 @@ import { LearnMoreLink } from "@/react/components/LearnMoreLink";
import { Alert } from "@/react/components/ui/alert";
import { Button } from "@/react/components/ui/button";
import { Input } from "@/react/components/ui/input";
+import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
import {
pushNotification,
@@ -838,6 +839,9 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
const instanceV1Store = useInstanceV1Store();
const actuatorStore = useActuatorV1Store();
const subscriptionStore = useSubscriptionV1Store();
+ const hasUnifiedInstanceLicense = useVueState(
+ () => subscriptionStore.hasUnifiedInstanceLicense
+ );
const [isEngineSelectorCollapsed, setIsEngineSelectorCollapsed] =
useState(false);
@@ -1359,35 +1363,37 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
</div>
{/* Activation toggle */}
- {subscriptionStore.currentPlan !== PlanType.FREE && allowEdit && (
- <div className="sm:col-span-2 ml-0 sm:ml-3">
- <label htmlFor="activation" className="textlabel block">
- {t("subscription.instance-assignment.assign-license")} (
- <a href="/setting/subscription" className="accent-link">
- {t("subscription.instance-assignment.n-license-remain", {
- n: availableLicenseCountText,
- })}
- </a>
- )
- </label>
- <div className="h-8.5 flex flex-row items-center mt-1">
- <label className="relative inline-flex items-center cursor-pointer">
- <input
- type="checkbox"
- className="sr-only peer"
- checked={basicInfo.activation}
- disabled={
- !basicInfo.activation && availableLicenseCount === 0
- }
- onChange={(e) =>
- changeInstanceActivation(e.target.checked)
- }
- />
- <div className="w-9 h-5 bg-control-border peer-focus:outline-none rounded-full peer peer-checked:bg-accent transition-colors after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:bg-background after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:after:translate-x-4" />
+ {subscriptionStore.currentPlan !== PlanType.FREE &&
+ !hasUnifiedInstanceLicense &&
+ allowEdit && (
+ <div className="sm:col-span-2 ml-0 sm:ml-3">
+ <label htmlFor="activation" className="textlabel block">
+ {t("subscription.instance-assignment.assign-license")} (
+ <a href="/setting/subscription" className="accent-link">
+ {t("subscription.instance-assignment.n-license-remain", {
+ n: availableLicenseCountText,
+ })}
+ </a>
+ )
</label>
+ <div className="h-8.5 flex flex-row items-center mt-1">
+ <label className="relative inline-flex items-center cursor-pointer">
+ <input
+ type="checkbox"
+ className="sr-only peer"
+ checked={basicInfo.activation}
+ disabled={
+ !basicInfo.activation && availableLicenseCount === 0
+ }
+ onChange={(e) =>
+ changeInstanceActivation(e.target.checked)
+ }
+ />
+ <div className="w-9 h-5 bg-control-border peer-focus:outline-none rounded-full peer peer-checked:bg-accent transition-colors after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:bg-background after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:after:translate-x-4" />
+ </label>
+ </div>
</div>
- </div>
- )}
+ )}
{/* Resource ID */}
<div className="sm:col-span-3 sm:col-start-1 -mt-4">
diff --git a/frontend/src/react/hooks/useAppState.ts b/frontend/src/react/hooks/useAppState.ts
index 0a74ff1fdb..7a137b3514 100644
--- a/frontend/src/react/hooks/useAppState.ts
+++ b/frontend/src/react/hooks/useAppState.ts
@@ -64,6 +64,9 @@ export function useSubscriptionState() {
const instanceLicenseCount = useAppStore((state) =>
state.instanceLicenseCount()
);
+ const hasUnifiedInstanceLicense = useAppStore((state) =>
+ state.hasUnifiedInstanceLicense()
+ );
useEffect(() => {
void loadSubscription();
}, [loadSubscription]);
@@ -81,6 +84,7 @@ export function useSubscriptionState() {
instanceCountLimit,
userCountLimit,
instanceLicenseCount,
+ hasUnifiedInstanceLicense,
};
}
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index 1451c02135..4ed211bc84 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -3500,10 +3500,10 @@
"n-license-remain": "{{n}} remaining",
"require-license": "Require instance license",
"success-notification": "Successfully update license assignment",
+ "used-and-total-instance": "Active / Total Instance Limit",
"used-and-total-license": "Assigned / Total Instance License",
"used-and-total-user": "Active / Total User Limit"
},
- "max-instance-count": "Max instance count",
"overuse-modal": {
"description": "You are using features unavailable in the {{plan}}. Upgrade now to ensure continued access:"
},
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index e6f34d8a4f..7aa6b8b660 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -3486,10 +3486,10 @@
"n-license-remain": "permanecer {{n}}",
"require-license": "Requerir licencia de instancia",
"success-notification": "Actualizar correctamente la asignación de licencia",
+ "used-and-total-instance": "Límite de instancias activas/totales",
"used-and-total-license": "Licencia asignada / total",
"used-and-total-user": "Límite de usuarios activos/totales"
},
- "max-instance-count": "Recuento máximo de instancias",
"overuse-modal": {
"description": "Está utilizando funciones no disponibles en {{plan}}. Actualice ahora para garantizar el acceso continuo:"
},
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index fe49fdf9a2..765f999ad0 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -3486,10 +3486,10 @@
"n-license-remain": "残り {{n}}",
"require-license": "インスタンスライセンスが必要です",
"success-notification": "ライセンスの割り当てが正常に更新されました",
+ "used-and-total-instance": "アクティブ/合計インスタンス制限",
"used-and-total-license": "割り当てられた/合計インスタンスライセンス",
"used-and-total-user": "アクティブ/合計ユーザー制限"
},
- "max-instance-count": "最大インスタンス数",
"overuse-modal": {
"description": "{{plan}} では使用できない機能を使用しています。通常どおり使用できるように、できるだけ早くアップグレードしてください:"
},
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index 41d97bb068..3ce68e82b3 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -3486,10 +3486,10 @@
"n-license-remain": "còn lại {{n}}",
"require-license": "Yêu cầu giấy phép phiên bản",
"success-notification": "Đã cập nhật thành công gán giấy phép",
+ "used-and-total-instance": "Giới hạn phiên bản đang hoạt động / Tổng số",
"used-and-total-license": "Giấy phép phiên bản đã gán / Tổng số",
"used-and-total-user": "Giới hạn người dùng đang hoạt động / Tổng số"
},
- "max-instance-count": "Số lượng phiên bản tối đa",
"overuse-modal": {
"description": "Bạn đang sử dụng các tính năng không có trong {{plan}}. Nâng cấp ngay để đảm bảo quyền truy cập liên tục:"
},
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index 79a0dc7000..5ca9f3d40a 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -3486,10 +3486,10 @@
"n-license-remain": "剩余 {{n}} 个",
"require-license": "需要实例证书",
"success-notification": "证书分配更新成功",
+ "used-and-total-instance": "活跃/总实例限制",
"used-and-total-license": "已分配 / 总实例证书",
"used-and-total-user": "活跃/总用户限制"
},
- "max-instance-count": "最多实例数",
"overuse-modal": {
"description": "您正在使用{{plan}}不可用的功能。请尽快升级以确保正常使用:"
},
diff --git a/frontend/src/react/pages/settings/InstancesPage.tsx b/frontend/src/react/pages/settings/InstancesPage.tsx
index 7a6176b5b4..7491f5bdab 100644
--- a/frontend/src/react/pages/settings/InstancesPage.tsx
+++ b/frontend/src/react/pages/settings/InstancesPage.tsx
@@ -80,10 +80,7 @@ import {
import { Engine, State } from "@/types/proto-es/v1/common_pb";
import type { Instance } from "@/types/proto-es/v1/instance_service_pb";
import { UpdateInstanceRequestSchema } from "@/types/proto-es/v1/instance_service_pb";
-import {
- PlanFeature,
- PlanType,
-} from "@/types/proto-es/v1/subscription_service_pb";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import {
engineNameV1,
hasWorkspacePermissionV2,
@@ -840,6 +837,9 @@ export function InstancesPage() {
const totalInstanceCount = useVueState(
() => actuatorStore.totalInstanceCount
);
+ const hasSplitInstanceLicense = useVueState(
+ () => subscriptionStore.hasSplitInstanceLicense
+ );
const quotaExhausted = totalInstanceCount >= instanceCountLimit;
// Data fetching
@@ -1040,10 +1040,16 @@ export function InstancesPage() {
setSelectedNames(new Set());
}, [fetchInstances]);
- const handleAssignLicense = useCallback((names: string[]) => {
- setAssignLicenseNames(names);
- setShowAssignLicenseSheet(true);
- }, []);
+ const handleAssignLicense = useCallback(
+ (names: string[]) => {
+ if (!hasSplitInstanceLicense) {
+ return;
+ }
+ setAssignLicenseNames(names);
+ setShowAssignLicenseSheet(true);
+ },
+ [hasSplitInstanceLicense]
+ );
useEffect(() => {
const query = router.currentRoute.value.query;
@@ -1292,7 +1298,7 @@ export function InstancesPage() {
selectedInstanceList.map((instance) => instance.name)
)
}
- showAssignLicense={subscriptionStore.currentPlan !== PlanType.FREE}
+ showAssignLicense={hasSplitInstanceLicense}
/>
<EditEnvironmentSheet
@@ -1300,12 +1306,14 @@ export function InstancesPage() {
onClose={() => setShowEditEnvDrawer(false)}
onUpdate={handleEnvironmentUpdate}
/>
- <InstanceAssignmentSheet
- open={showAssignLicenseSheet}
- selectedInstanceList={assignLicenseNames}
- onOpenChange={setShowAssignLicenseSheet}
- onUpdated={handleRowAction}
- />
+ {hasSplitInstanceLicense && (
+ <InstanceAssignmentSheet
+ open={showAssignLicenseSheet}
+ selectedInstanceList={assignLicenseNames}
+ onOpenChange={setShowAssignLicenseSheet}
+ onUpdated={handleRowAction}
+ />
+ )}
{/* Table */}
<div className="border rounded-sm">
diff --git a/frontend/src/react/pages/settings/SubscriptionPage.test.tsx b/frontend/src/react/pages/settings/SubscriptionPage.test.tsx
new file mode 100644
index 0000000000..a809291776
--- /dev/null
+++ b/frontend/src/react/pages/settings/SubscriptionPage.test.tsx
@@ -0,0 +1,116 @@
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock("@/react/components/InstanceAssignmentSheet", () => ({
+ InstanceAssignmentSheet: () => null,
+}));
+
+vi.mock("@/react/components/ui/badge", () => ({
+ Badge: ({ children }: { children: React.ReactNode }) => (
+ <span>{children}</span>
+ ),
+}));
+
+vi.mock("@/react/components/ui/button", () => ({
+ Button: ({
+ children,
+ ...props
+ }: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
+ <button type="button" {...props}>
+ {children}
+ </button>
+ ),
+}));
+
+vi.mock("@/react/components/ui/input", () => ({
+ Input: (props: React.InputHTMLAttributes<HTMLInputElement>) => (
+ <input {...props} />
+ ),
+}));
+
+vi.mock("@/react/components/ui/textarea", () => ({
+ Textarea: (props: React.TextareaHTMLAttributes<HTMLTextAreaElement>) => (
+ <textarea {...props} />
+ ),
+}));
+
+vi.mock("@/react/hooks/useAppState", () => ({
+ useNotify: () => vi.fn(),
+ useServerState: () => ({
+ activatedInstanceCount: 2,
+ isSaaSMode: false,
+ totalInstanceCount: 3,
+ userCountInIam: 4,
+ workspaceResourceName: "workspaces/workspace-id",
+ }),
+ useSubscriptionState: () => ({
+ currentPlan: PlanType.ENTERPRISE,
+ expireAt: "",
+ hasUnifiedInstanceLicense: true,
+ instanceCountLimit: 10,
+ instanceLicenseCount: 10,
+ isExpired: false,
+ isFreePlan: false,
+ isSelfHostLicense: true,
+ isTrialing: false,
+ showTrial: false,
+ trialingDays: 14,
+ uploadLicense: vi.fn(),
+ userCountLimit: 20,
+ }),
+}));
+
+vi.mock("@/types", () => ({
+ ENTERPRISE_INQUIRE_LINK: "https://example.com",
+}));
+
+vi.mock("@/utils", () => ({
+ hasWorkspacePermissionV2: () => true,
+}));
+
+vi.mock("./PurchaseSection", () => ({
+ PurchaseSection: () => null,
+}));
+
+let SubscriptionPage: typeof import("./SubscriptionPage").SubscriptionPage;
+
+describe("SubscriptionPage", () => {
+ let container: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ ({ SubscriptionPage } = await import("./SubscriptionPage"));
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ });
+
+ test("displays unified instance usage as current count over limit", () => {
+ act(() => {
+ root.render(<SubscriptionPage />);
+ });
+
+ expect(
+ container.textContent?.includes(
+ "subscription.instance-assignment.used-and-total-instance"
+ )
+ ).toBe(true);
+ expect(container.textContent?.includes("3/10")).toBe(true);
+
+ act(() => root.unmount());
+ container.remove();
+ });
+});
diff --git a/frontend/src/react/pages/settings/SubscriptionPage.tsx b/frontend/src/react/pages/settings/SubscriptionPage.tsx
index 0d113f95b6..b96afd38b0 100644
--- a/frontend/src/react/pages/settings/SubscriptionPage.tsx
+++ b/frontend/src/react/pages/settings/SubscriptionPage.tsx
@@ -44,11 +44,13 @@ export function SubscriptionPage({
expireAt,
instanceCountLimit,
instanceLicenseCount,
+ hasUnifiedInstanceLicense,
userCountLimit,
} = useSubscriptionState();
const {
isSaaSMode,
userCountInIam,
+ totalInstanceCount,
activatedInstanceCount,
workspaceResourceName,
} = useServerState();
@@ -189,6 +191,8 @@ export function SubscriptionPage({
<InstanceLicenseStats
planType={planType}
instanceCountLimit={instanceCountLimit}
+ totalInstanceCount={totalInstanceCount}
+ hasUnifiedInstanceLicense={hasUnifiedInstanceLicense}
activatedCount={activatedInstanceCount}
totalLicenseCount={totalLicenseCount}
onManageInstanceLicenses={onManageInstanceLicenses}
@@ -301,10 +305,12 @@ export function SubscriptionPage({
</div>
</div>
)}
- <InstanceAssignmentSheet
- open={showInstanceAssignmentSheet}
- onOpenChange={setShowInstanceAssignmentSheet}
- />
+ {!hasUnifiedInstanceLicense && (
+ <InstanceAssignmentSheet
+ open={showInstanceAssignmentSheet}
+ onOpenChange={setShowInstanceAssignmentSheet}
+ />
+ )}
</div>
);
}
@@ -312,23 +318,37 @@ export function SubscriptionPage({
function InstanceLicenseStats({
planType,
instanceCountLimit,
+ totalInstanceCount,
+ hasUnifiedInstanceLicense,
activatedCount,
totalLicenseCount,
onManageInstanceLicenses,
}: {
planType: string;
instanceCountLimit: number;
+ totalInstanceCount: number;
+ hasUnifiedInstanceLicense: boolean;
activatedCount: number;
totalLicenseCount: string;
onManageInstanceLicenses: () => void;
}) {
const { t } = useTranslation();
+ const instanceLimit =
+ instanceCountLimit === Number.MAX_VALUE
+ ? t("common.unlimited")
+ : `${instanceCountLimit}`;
- if (planType === "FREE") {
+ if (planType === "FREE" || hasUnifiedInstanceLicense) {
return (
<div className="flex flex-col text-left">
- <dt className="text-main">{t("subscription.max-instance-count")}</dt>
- <div className="mt-1 text-4xl">{instanceCountLimit}</div>
+ <dt className="text-main">
+ {t("subscription.instance-assignment.used-and-total-instance")}
+ </dt>
+ <div className="mt-1 text-4xl flex items-center gap-2">
+ {totalInstanceCount}
+ <span className="font-mono text-control-light">/</span>
+ {instanceLimit}
+ </div>
</div>
);
}
diff --git a/frontend/src/react/stores/app/index.test.ts b/frontend/src/react/stores/app/index.test.ts
index 534f12dcd9..54a3e887f0 100644
--- a/frontend/src/react/stores/app/index.test.ts
+++ b/frontend/src/react/stores/app/index.test.ts
@@ -329,9 +329,40 @@ describe("useAppStore", () => {
expect(store.getState().instanceCountLimit()).toBe(Number.MAX_VALUE);
expect(store.getState().userCountLimit()).toBe(Number.MAX_VALUE);
expect(store.getState().instanceLicenseCount()).toBe(Number.MAX_VALUE);
+ expect(store.getState().hasUnifiedInstanceLicense()).toBe(true);
expect(store.getState().hasFeature(PlanFeature.FEATURE_DATA_MASKING)).toBe(
true
);
+ expect(
+ store.getState().hasInstanceFeature(
+ PlanFeature.FEATURE_DATA_MASKING,
+ createProto(InstanceSchema, {
+ name: "instances/prod",
+ activation: false,
+ })
+ )
+ ).toBe(true);
+ expect(
+ store.getState().instanceMissingLicense(
+ PlanFeature.FEATURE_DATA_MASKING,
+ createProto(InstanceSchema, {
+ name: "instances/prod",
+ activation: false,
+ })
+ )
+ ).toBe(false);
+
+ store.setState({
+ subscription: createProto(SubscriptionSchema, {
+ plan: PlanType.ENTERPRISE,
+ instances: 50,
+ activeInstances: 20,
+ expiresTime: timestampSeconds(
+ Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 30
+ ),
+ }),
+ });
+ expect(store.getState().hasUnifiedInstanceLicense()).toBe(false);
expect(
store.getState().hasInstanceFeature(
PlanFeature.FEATURE_DATA_MASKING,
diff --git a/frontend/src/react/stores/app/types.ts b/frontend/src/react/stores/app/types.ts
index 1a2eaf7ed1..4ec9563415 100644
--- a/frontend/src/react/stores/app/types.ts
+++ b/frontend/src/react/stores/app/types.ts
@@ -66,6 +66,7 @@ export type WorkspaceSlice = {
instanceCountLimit: () => number;
userCountLimit: () => number;
instanceLicenseCount: () => number;
+ hasUnifiedInstanceLicense: () => boolean;
hasFeature: (feature: PlanFeature) => boolean;
hasInstanceFeature: (
feature: PlanFeature,
diff --git a/frontend/src/react/stores/app/workspace.ts b/frontend/src/react/stores/app/workspace.ts
index f9eafed68d..e3269c2828 100644
--- a/frontend/src/react/stores/app/workspace.ts
+++ b/frontend/src/react/stores/app/workspace.ts
@@ -345,6 +345,10 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (
return count < 0 ? Number.MAX_VALUE : count;
},
+ hasUnifiedInstanceLicense: () => {
+ return get().instanceCountLimit() <= get().instanceLicenseCount();
+ },
+
hasFeature: (feature) => {
if (get().isExpired()) {
return false;
@@ -360,13 +364,20 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (
if (!instance || !instanceLimitFeature.has(feature)) {
return get().hasFeature(feature);
}
- return checkInstanceFeature(plan, feature, instance.activation);
+ return checkInstanceFeature(
+ plan,
+ feature,
+ get().hasUnifiedInstanceLicense() || instance.activation
+ );
},
instanceMissingLicense: (feature, instance) => {
if (!instanceLimitFeature.has(feature) || !instance) {
return false;
}
+ if (get().hasUnifiedInstanceLicense()) {
+ return false;
+ }
return get().hasFeature(feature) && !instance.activation;
},
diff --git a/frontend/src/store/modules/v1/subscription.test.ts b/frontend/src/store/modules/v1/subscription.test.ts
new file mode 100644
index 0000000000..634e254f11
--- /dev/null
+++ b/frontend/src/store/modules/v1/subscription.test.ts
@@ -0,0 +1,127 @@
+import { create } from "@bufbuild/protobuf";
+import { createPinia, setActivePinia } from "pinia";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { InstanceSchema } from "@/types/proto-es/v1/instance_service_pb";
+import {
+ PlanFeature,
+ PlanType,
+ SubscriptionSchema,
+} from "@/types/proto-es/v1/subscription_service_pb";
+
+vi.mock("@/connect", () => ({
+ subscriptionServiceClientConnect: {},
+}));
+
+vi.mock("@/types", () => ({
+ hasFeature: vi.fn(() => true),
+ hasInstanceFeature: vi.fn(
+ (_plan: PlanType, _feature: PlanFeature, activated: boolean) => activated
+ ),
+ getDateForPbTimestampProtoEs: vi.fn(() => new Date()),
+ getMinimumRequiredPlan: vi.fn(() => PlanType.TEAM),
+ getTimeForPbTimestampProtoEs: vi.fn(() => Date.now()),
+ instanceLimitFeature: new Set<PlanFeature>([
+ PlanFeature.FEATURE_DATA_MASKING,
+ ]),
+ PLANS: [
+ {
+ type: PlanType.ENTERPRISE,
+ maximumInstanceCount: -1,
+ maximumSeatCount: -1,
+ },
+ ],
+}));
+
+vi.mock("@/utils/datetime", () => ({
+ formatAbsoluteDateTime: vi.fn(() => ""),
+}));
+
+let useSubscriptionV1Store: typeof import("./subscription").useSubscriptionV1Store;
+
+describe("useSubscriptionV1Store unified instance license", () => {
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ setActivePinia(createPinia());
+ ({ useSubscriptionV1Store } = await import("./subscription"));
+ });
+
+ test("computes unified mode from effective limits", () => {
+ const store = useSubscriptionV1Store();
+ store.setSubscription(
+ create(SubscriptionSchema, {
+ plan: PlanType.ENTERPRISE,
+ instances: 10,
+ activeInstances: 10,
+ })
+ );
+
+ expect(store.hasUnifiedInstanceLicense).toBe(true);
+
+ store.setSubscription(
+ create(SubscriptionSchema, {
+ plan: PlanType.ENTERPRISE,
+ instances: 50,
+ activeInstances: 20,
+ })
+ );
+
+ expect(store.hasUnifiedInstanceLicense).toBe(false);
+ });
+
+ test("computes legacy split instance license mode", () => {
+ const store = useSubscriptionV1Store();
+ store.setSubscription(
+ create(SubscriptionSchema, {
+ plan: PlanType.ENTERPRISE,
+ instances: 50,
+ activeInstances: 20,
+ })
+ );
+
+ expect(store.hasSplitInstanceLicense).toBe(true);
+
+ store.setSubscription(
+ create(SubscriptionSchema, {
+ plan: PlanType.ENTERPRISE,
+ instances: 10,
+ activeInstances: 10,
+ })
+ );
+
+ expect(store.hasSplitInstanceLicense).toBe(false);
+
+ store.setSubscription(
+ create(SubscriptionSchema, {
+ plan: PlanType.FREE,
+ instances: 0,
+ activeInstances: 0,
+ })
+ );
+
+ expect(store.hasSplitInstanceLicense).toBe(false);
+ });
+
+ test("does not report missing instance license in unified mode", () => {
+ const store = useSubscriptionV1Store();
+ store.setSubscription(
+ create(SubscriptionSchema, {
+ plan: PlanType.ENTERPRISE,
+ instances: 10,
+ activeInstances: 10,
+ })
+ );
+
+ const inactiveInstance = create(InstanceSchema, {
+ name: "instances/prod",
+ title: "prod",
+ activation: false,
+ });
+
+ expect(
+ store.instanceMissingLicense(
+ PlanFeature.FEATURE_DATA_MASKING,
+ inactiveInstance
+ )
+ ).toBe(false);
+ });
+});
diff --git a/frontend/src/store/modules/v1/subscription.ts b/frontend/src/store/modules/v1/subscription.ts
index a48315cdab..87c74785ef 100644
--- a/frontend/src/store/modules/v1/subscription.ts
+++ b/frontend/src/store/modules/v1/subscription.ts
@@ -103,6 +103,14 @@ export const useSubscriptionV1Store = defineStore("subscription_v1", () => {
return count;
});
+ const hasUnifiedInstanceLicense = computed(() => {
+ return instanceCountLimit.value <= instanceLicenseCount.value;
+ });
+
+ const hasSplitInstanceLicense = computed(() => {
+ return !isFreePlan.value && !hasUnifiedInstanceLicense.value;
+ });
+
const expireAt = computed(() => {
if (
!subscription.value ||
@@ -196,7 +204,7 @@ export const useSubscriptionV1Store = defineStore("subscription_v1", () => {
return checkInstanceFeature(
currentPlan.value,
feature,
- instance.activation
+ hasUnifiedInstanceLicense.value || instance.activation
);
};
@@ -211,6 +219,9 @@ export const useSubscriptionV1Store = defineStore("subscription_v1", () => {
if (!instance) {
return false;
}
+ if (hasUnifiedInstanceLicense.value) {
+ return false;
+ }
// Feature is available in plan but instance is not activated
return hasFeature(feature) && !instance.activation;
};
@@ -352,6 +363,8 @@ export const useSubscriptionV1Store = defineStore("subscription_v1", () => {
instanceCountLimit,
userCountLimit,
instanceLicenseCount,
+ hasUnifiedInstanceLicense,
+ hasSplitInstanceLicense,
expireAt,
isTrialing,
isExpired,