Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: unified setup flow (#21253)
ecmadao431bf2f31964
diff --git a/action/command/root_test.go b/action/command/root_test.goindex 153cc24b48..67524129d1 100644--- a/action/command/root_test.go+++ b/action/command/root_test.go@@ -11,7 +11,6 @@ import ("connectrpc.com/connect""github.com/stretchr/testify/require"- "google.golang.org/protobuf/types/known/emptypb""github.com/bytebase/bytebase/action/world"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"@@ -215,7 +214,3 @@ type actuatorInfoTestService struct {func (s *actuatorInfoTestService) GetActuatorInfo(context.Context, *connect.Request[v1pb.GetActuatorInfoRequest]) (*connect.Response[v1pb.ActuatorInfo], error) {return connect.NewResponse(&v1pb.ActuatorInfo{Version: s.version}), nil}--func (*actuatorInfoTestService) SetupSample(context.Context, *connect.Request[v1pb.SetupSampleRequest]) (*connect.Response[emptypb.Empty], error) {- return connect.NewResponse(&emptypb.Empty{}), nil-}diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yamlindex a88b8a6a8e..974f250140 100644--- a/backend/api/mcp/gen/openapi.yaml+++ b/backend/api/mcp/gen/openapi.yaml@@ -294,44 +294,6 @@ paths:application/json:schema:$ref: '#/components/schemas/bytebase.v1.ActuatorInfo'- /bytebase.v1.ActuatorService/SetupSample:- post:- tags:- - bytebase.v1.ActuatorService- summary: SetupSample- description: |-- Sets up sample data for demonstration and testing purposes.- Permissions required: bb.projects.create- operationId: bytebase.v1.ActuatorService.SetupSample- parameters:- - name: Connect-Protocol-Version- in: header- required: true- schema:- $ref: '#/components/schemas/connect-protocol-version'- - name: Connect-Timeout-Ms- in: header- schema:- $ref: '#/components/schemas/connect-timeout-header'- requestBody:- content:- application/json:- schema:- $ref: '#/components/schemas/bytebase.v1.SetupSampleRequest'- required: true- responses:- default:- description: Error- content:- application/json:- schema:- $ref: '#/components/schemas/connect.error'- "200":- description: Success- content:- application/json:- schema:- $ref: '#/components/schemas/google.protobuf.Empty'/bytebase.v1.AuditLogService/ExportAuditLogs:post:tags:@@ -19540,11 +19502,6 @@ components:title: SettingValueadditionalProperties: falsedescription: The data in setting value.- bytebase.v1.SetupSampleRequest:- type: object- title: SetupSampleRequest- additionalProperties: false- description: Request message for setting up sample data.bytebase.v1.Sheet:type: objectproperties:diff --git a/backend/api/v1/actuator_service.go b/backend/api/v1/actuator_service.goindex 5d21ebb7f5..67346d842c 100644--- a/backend/api/v1/actuator_service.go+++ b/backend/api/v1/actuator_service.go@@ -7,7 +7,6 @@ import ("connectrpc.com/connect""github.com/hashicorp/golang-lru/v2/expirable"- "google.golang.org/protobuf/types/known/emptypb""google.golang.org/protobuf/types/known/timestamppb""github.com/pkg/errors"@@ -80,46 +79,6 @@ func (s *ActuatorService) GetActuatorInfo(return connect.NewResponse(info), nil}-// SetupSample sets up the sample project and instance.-func (s *ActuatorService) SetupSample(- ctx context.Context,- _ *connect.Request[v1pb.SetupSampleRequest],-) (*connect.Response[emptypb.Empty], error) {- if s.profile.SaaS {- // skip sample setup in SaaS- slog.Debug("sample is not available for SaaS")- return connect.NewResponse(&emptypb.Empty{}), nil- }- user, ok := GetUserFromContext(ctx)- if !ok || user == nil {- return nil, connect.NewError(connect.CodeInternal, errors.New("user not found"))- }-- if s.sampleManager != nil {- workspaceID := common.GetWorkspaceIDFromContext(ctx)- projectID := "project-sample"- project, err := s.store.GetProject(ctx, &store.FindProjectMessage{Workspace: workspaceID, ResourceID: &projectID})- if err == nil && project == nil {- project, err = s.store.CreateProject(ctx, &store.ProjectMessage{- Workspace: workspaceID,- ResourceID: projectID,- Title: "Sample Project",- Setting: &storepb.Project{},- }, user)- }- if err == nil {- _, err = s.sampleManager.SetupSample(ctx, sample.SetupRequest{WorkspaceID: workspaceID, ProjectID: project.ResourceID})- }- if err != nil {- // When running inside docker on mac, we sometimes get database does not exist error.- // This is due to the docker overlay storage incompatibility with mac OS file system.- // Onboarding error is not critical, so we just emit an error log.- slog.Error("failed to prepare onboarding data", log.BBError(err))- }- }- return connect.NewResponse(&emptypb.Empty{}), nil-}-func (s *ActuatorService) getServerInfo(ctx context.Context, workspaceID string) (*v1pb.ActuatorInfo, error) {serverInfo := v1pb.ActuatorInfo{Version: s.profile.Version,@@ -135,13 +94,14 @@ func (s *ActuatorService) getServerInfo(ctx context.Context, workspaceID string)if workspaceID != "" {serverInfo.Workspace = common.FormatWorkspace(workspaceID)if s.sampleManager != nil {- sampleInfo, err := s.sampleManager.Info(ctx, workspaceID)+ serverInfo.Sample.Available = s.sampleManager.CheckAvailable(ctx) == nil+ instances, err := s.sampleManager.ListInstances(ctx, workspaceID)if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to get sample information"))+ slog.Error("failed to list sample instances", log.BBError(err), slog.String("workspace", workspaceID))+ instances = nil}- serverInfo.Sample.Available = sampleInfo.Available- for _, instance := range sampleInfo.Instances {- item := &v1pb.SampleInfo_Instance{Instance: instance.Instance}+ for _, instance := range instances {+ item := &v1pb.SampleInfo_Instance{Instance: instance.Name}if instance.ExpireTime != nil {item.ExpireTime = timestamppb.New(*instance.ExpireTime)}diff --git a/backend/api/v1/actuator_service_test.go b/backend/api/v1/actuator_service_test.goindex 245745d2c1..e804b4211d 100644--- a/backend/api/v1/actuator_service_test.go+++ b/backend/api/v1/actuator_service_test.go@@ -2,6 +2,7 @@ package v1import ("context"+ "errors""fmt""slices""testing"@@ -17,6 +18,7 @@ import ("github.com/bytebase/bytebase/backend/component/config""github.com/bytebase/bytebase/backend/component/sample""github.com/bytebase/bytebase/backend/component/sample/saas"+ "github.com/bytebase/bytebase/backend/component/sample/selfhost""github.com/bytebase/bytebase/backend/enterprise"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"@@ -106,6 +108,23 @@ func TestAuthenticationInfoAndActuatorBoundary(t *testing.T) {require.NoError(t, err)require.False(t, nonSaaSResponse.Msg.Sample.Available)+ selfHostManager := selfhost.NewManager(stores, profile, nil, sample.ManagerOptions{ReplicaID: "replica-a"})+ actuatorService.sampleManager = selfHostManager+ profile.PgURL = pgURL+ externalMetadataResponse, err := actuatorService.GetActuatorInfo(authenticatedCtx, connect.NewRequest(&v1pb.GetActuatorInfoRequest{}))+ require.NoError(t, err)+ require.False(t, externalMetadataResponse.Msg.Sample.Available)+ profile.PgURL = ""+ embeddedMetadataResponse, err := actuatorService.GetActuatorInfo(authenticatedCtx, connect.NewRequest(&v1pb.GetActuatorInfoRequest{}))+ require.NoError(t, err)+ require.True(t, embeddedMetadataResponse.Msg.Sample.Available)++ actuatorService.sampleManager = &sampleManagerStub{listInstancesErr: errors.New("failed to decode sample setup")}+ degradedSampleResponse, err := actuatorService.GetActuatorInfo(authenticatedCtx, connect.NewRequest(&v1pb.GetActuatorInfoRequest{}))+ require.NoError(t, err)+ require.True(t, degradedSampleResponse.Msg.Sample.Available)+ require.Empty(t, degradedSampleResponse.Msg.Sample.Instances)+profile.SaaS = trueactuatorService.sampleManager = sampleManager@@ -166,72 +185,3 @@ func TestAuthenticationInfoAndActuatorBoundary(t *testing.T) {require.Equal(t, common.FormatProjectInstance(projectID, "sample-instance"), deletedResponse.Msg.Sample.Instances[0].Instance)require.Nil(t, deletedResponse.Msg.Sample.Instances[0].ExpireTime)}--func TestSetupSampleUsesUnifiedManagerAndAcceptsPair(t *testing.T) {- ctx := context.Background()- container := testcontainer.GetTestPgContainer(ctx, t)- t.Cleanup(func() { container.Close(ctx) })- require.NoError(t, migrator.MigrateSchema(ctx, container.GetDB()))-- stores, err := store.New(ctx, fmt.Sprintf(- "host=%s port=%s user=postgres password=root-password database=postgres",- container.GetHost(), container.GetPort(),- ), false)- require.NoError(t, err)- t.Cleanup(func() { require.NoError(t, stores.Close()) })- const workspaceID = "setup-sample"- _, err = stores.CreateWorkspace(ctx, &store.WorkspaceMessage{- ResourceID: workspaceID,- Payload: &storepb.WorkspacePayload{Title: "Setup sample"},- }, "[email protected]")- require.NoError(t, err)- user, err := stores.CreateUser(ctx, &store.UserMessage{- Email: "[email protected]",- Name: "Admin",- Profile: &storepb.UserProfile{},- })- require.NoError(t, err)-- manager := &actuatorSampleManagerStub{}- service := &ActuatorService{- store: stores,- profile: &config.Profile{},- sampleManager: manager,- }- requestCtx := context.WithValue(ctx, common.WorkspaceIDContextKey, workspaceID)- requestCtx = context.WithValue(requestCtx, common.UserContextKey, user)- _, err = service.SetupSample(requestCtx, connect.NewRequest(&v1pb.SetupSampleRequest{}))- require.NoError(t, err)- require.Equal(t, []sample.SetupRequest{{WorkspaceID: workspaceID, ProjectID: "project-sample"}}, manager.requests)- projectID := "project-sample"- project, err := stores.GetProject(ctx, &store.FindProjectMessage{Workspace: workspaceID, ResourceID: &projectID})- require.NoError(t, err)- require.NotNil(t, project)-}--type actuatorSampleManagerStub struct {- requests []sample.SetupRequest-}--func (s *actuatorSampleManagerStub) SetupSample(_ context.Context, request sample.SetupRequest) (*sample.SetupResult, error) {- s.requests = append(s.requests, request)- return &sample.SetupResult{Instances: []*store.InstanceMessage{{ResourceID: "sample-one"}, {ResourceID: "sample-two"}}}, nil-}--func (*actuatorSampleManagerStub) Info(context.Context, string) (*sample.Info, error) {- return &sample.Info{}, nil-}--func (*actuatorSampleManagerStub) Start(context.Context, string) error { return nil }--func (*actuatorSampleManagerStub) Cleanup(context.Context) error { return nil }--func (*actuatorSampleManagerStub) ValidateInstanceRestore(context.Context, string, string) error {- return nil-}--func (*actuatorSampleManagerStub) HandleInstanceLifecycle(context.Context, string, string, bool) error {- return nil-}--func (*actuatorSampleManagerStub) Stop() {}diff --git a/backend/api/v1/instance_service.go b/backend/api/v1/instance_service.goindex b6f5c1eee2..8d2e809284 100644--- a/backend/api/v1/instance_service.go+++ b/backend/api/v1/instance_service.go@@ -40,24 +40,10 @@ type InstanceService struct {v1connect.UnimplementedInstanceServiceHandlerstore *store.Storeprofile *config.Profile- licenseService instanceLicenseService+ licenseService *enterprise.LicenseServicedbFactory *dbfactory.DBFactoryschemaSyncer *schemasync.Syncer- sampleManager instanceSampleManager-}--type instanceSampleManager interface {- SetupSample(context.Context, sample.SetupRequest) (*sample.SetupResult, error)- ValidateInstanceRestore(context.Context, string, string) error- HandleInstanceLifecycle(context.Context, string, string, bool) error-}--type instanceLicenseService interface {- GetActivatedInstanceLimit(context.Context, string) int- GetInstanceLimit(context.Context, string) int- IsFeatureEnabledForInstance(context.Context, string, v1pb.PlanFeature, *store.InstanceMessage) error- IsInstanceEffectivelyActivated(context.Context, string, *store.InstanceMessage) bool- IsUnifiedInstanceLicense(context.Context, string) bool+ sampleManager sample.Manager}const (@@ -203,7 +189,7 @@ func (s *InstanceService) checkAndLogInstanceConnection(ctx context.Context, met}// NewInstanceService creates a new InstanceService.-func NewInstanceService(store *store.Store, profile *config.Profile, licenseService *enterprise.LicenseService, dbFactory *dbfactory.DBFactory, schemaSyncer *schemasync.Syncer, sampleManager instanceSampleManager) *InstanceService {+func NewInstanceService(store *store.Store, profile *config.Profile, licenseService *enterprise.LicenseService, dbFactory *dbfactory.DBFactory, schemaSyncer *schemasync.Syncer, sampleManager sample.Manager) *InstanceService {return &InstanceService{store: store,profile: profile,@@ -471,8 +457,8 @@ func (s *InstanceService) CreateInstance(ctx context.Context, req *connect.Requereturn connect.NewResponse(result), nil}-// PrepareSampleProjectInstance provisions a Cloud Sample Project Instance for-// the requested project. The lifetime entitlement itself is enforced by the+// PrepareSampleProjectInstance provisions a Sample Project Instance for the+// requested project. The lifetime entitlement itself is enforced by the// lifecycle manager under a workspace row lock.func (s *InstanceService) PrepareSampleProjectInstance(ctx context.Context, req *connect.Request[v1pb.PrepareSampleProjectInstanceRequest]) (*connect.Response[v1pb.Instance], error) {projectID, err := s.getSampleProjectInstanceParent(ctx, &req.Msg.Parent)@@ -482,24 +468,24 @@ func (s *InstanceService) PrepareSampleProjectInstance(ctx context.Context, reqif projectID == nil {return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("Sample Project Instance parent is required"))}- if s.profile == nil || !s.profile.SaaS || s.sampleManager == nil {- return nil, connect.NewError(connect.CodeFailedPrecondition, errors.New("Sample Project Instance is available only in SaaS deployments with a configured target"))+ if s.sampleManager == nil {+ return nil, connect.NewError(connect.CodeFailedPrecondition, errors.New("Sample Project Instance is not configured"))+ }+ if err := s.sampleManager.CheckAvailable(ctx); err != nil {+ return nil, sampleProjectInstanceConnectError(err)}workspaceID := common.GetWorkspaceIDFromContext(ctx)if err := s.instanceCountGuard(ctx); err != nil {return nil, err}- result, err := s.sampleManager.SetupSample(ctx, sample.SetupRequest{+ instance, err := s.sampleManager.PrepareSampleProjectInstance(ctx, sample.PrepareRequest{WorkspaceID: workspaceID,ProjectID: *projectID,})if err != nil {return nil, sampleProjectInstanceConnectError(err)}- if len(result.Instances) != 1 {- return nil, connect.NewError(connect.CodeInternal, errors.New("Sample Project Instance preparation must return exactly one instance"))- }- return connect.NewResponse(s.convertToV1Instance(ctx, result.Instances[0])), nil+ return connect.NewResponse(s.convertToV1Instance(ctx, instance)), nil}func sampleProjectInstanceConnectError(err error) error {diff --git a/backend/api/v1/instance_service_test.go b/backend/api/v1/instance_service_test.goindex ebc8ecb6f1..00a2c18a21 100644--- a/backend/api/v1/instance_service_test.go+++ b/backend/api/v1/instance_service_test.go@@ -3,6 +3,7 @@ package v1import ("context""errors"+ "fmt""log/slog""testing""time"@@ -20,55 +21,79 @@ import ("github.com/bytebase/bytebase/backend/store")-func TestPrepareSampleProjectInstanceValidatesParentAndDeployment(t *testing.T) {- service := &InstanceService{profile: &config.Profile{SaaS: true}}+func TestPrepareSampleProjectInstanceValidatesParentAndManager(t *testing.T) {+ service := &InstanceService{}_, err := service.PrepareSampleProjectInstance(context.Background(), connect.NewRequest(&v1pb.PrepareSampleProjectInstanceRequest{}))require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))ctx, stores, projectID, _, _ := setupProjectInstanceLifecycleAPITest(t)service = &InstanceService{store: stores,- profile: &config.Profile{},- licenseService: &instanceLicenseServiceStub{instanceLimit: 10, activatedInstanceLimit: 10},- sampleManager: &instanceSampleManagerStub{},+ licenseService: newInstanceServiceTestLicenseService(t, stores),}_, err = service.PrepareSampleProjectInstance(ctx, connect.NewRequest(&v1pb.PrepareSampleProjectInstanceRequest{Parent: common.FormatProject(projectID),}))require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))+}- service.profile = nil- _, err = service.PrepareSampleProjectInstance(ctx, connect.NewRequest(&v1pb.PrepareSampleProjectInstanceRequest{- Parent: common.FormatProject(projectID),- }))- require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))+func TestPrepareSampleProjectInstanceUsesConfiguredManagerInBothDeployments(t *testing.T) {+ ctx, stores, projectID, _, _ := setupProjectInstanceLifecycleAPITest(t)+ for _, saas := range []bool{false, true} {+ t.Run(fmt.Sprintf("saas=%t", saas), func(t *testing.T) {+ manager := &sampleManagerStub{instance: &store.InstanceMessage{+ ResourceID: "sample-one",+ ProjectID: &projectID,+ Metadata: &storepb.Instance{Title: "Sample Project Instance"},+ }}+ service := &InstanceService{+ store: stores,+ profile: &config.Profile{SaaS: saas},+ licenseService: newInstanceServiceTestLicenseService(t, stores),+ sampleManager: manager,+ }++ response, err := service.PrepareSampleProjectInstance(ctx, connect.NewRequest(&v1pb.PrepareSampleProjectInstanceRequest{+ Parent: common.FormatProject(projectID),+ }))+ require.NoError(t, err)+ require.Equal(t, common.FormatProjectInstance(projectID, "sample-one"), response.Msg.Name)+ require.Equal(t, 1, manager.checkAvailableCalls)+ require.Equal(t, []sample.PrepareRequest{{WorkspaceID: "default", ProjectID: projectID}}, manager.prepareRequests)+ })+ }}-func TestPrepareSampleProjectInstanceRequiresSingleManagerResult(t *testing.T) {+func TestPrepareSampleProjectInstanceChecksManagerAvailability(t *testing.T) {ctx, stores, projectID, _, _ := setupProjectInstanceLifecycleAPITest(t)- manager := &instanceSampleManagerStub{- setupResult: &sample.SetupResult{Instances: []*store.InstanceMessage{- {ResourceID: "sample-one"},- {ResourceID: "sample-two"},- }},+ manager := &sampleManagerStub{+ checkAvailableErr: sample.NewFailure(sample.FailureUnavailable, errors.New("sample target unavailable")),}service := &InstanceService{store: stores,- profile: &config.Profile{SaaS: true},- licenseService: &instanceLicenseServiceStub{instanceLimit: 10, activatedInstanceLimit: 10},+ licenseService: newInstanceServiceTestLicenseService(t, stores),sampleManager: manager,}_, err := service.PrepareSampleProjectInstance(ctx, connect.NewRequest(&v1pb.PrepareSampleProjectInstanceRequest{Parent: common.FormatProject(projectID),}))- require.Equal(t, connect.CodeInternal, connect.CodeOf(err))- require.Len(t, manager.setupRequests, 1)+ require.Equal(t, connect.CodeUnavailable, connect.CodeOf(err))+ require.Equal(t, 1, manager.checkAvailableCalls)+ require.Empty(t, manager.prepareRequests)}func TestSampleInstanceLifecycleHooksWrapMetadataUpdate(t *testing.T) {ctx, stores, projectID, instanceID, _ := setupProjectInstanceLifecycleAPITest(t)- manager := &instanceSampleManagerStub{}+ _, err := stores.UpdateInstance(ctx, &store.UpdateInstanceMessage{+ ResourceID: &instanceID,+ Workspace: "default",+ Metadata: &storepb.Instance{+ DataSources: []*storepb.DataSource{{Id: "admin", Type: storepb.DataSourceType_ADMIN}},+ },+ })+ require.NoError(t, err)+ manager := &sampleManagerStub{}manager.validate = func(ctx context.Context, workspaceID, gotInstanceID string) error {require.Equal(t, "default", workspaceID)require.Equal(t, instanceID, gotInstanceID)@@ -85,12 +110,12 @@ func TestSampleInstanceLifecycleHooksWrapMetadataUpdate(t *testing.T) {}service := &InstanceService{store: stores,- licenseService: &instanceLicenseServiceStub{instanceLimit: 10, activatedInstanceLimit: 10},+ licenseService: newInstanceServiceTestLicenseService(t, stores),sampleManager: manager,}instanceName := common.FormatProjectInstance(projectID, instanceID)- _, err := service.DeleteInstance(ctx, connect.NewRequest(&v1pb.DeleteInstanceRequest{Name: instanceName}))+ _, err = service.DeleteInstance(ctx, connect.NewRequest(&v1pb.DeleteInstanceRequest{Name: instanceName}))require.NoError(t, err)require.Equal(t, []bool{true}, manager.lifecycleCalls)@@ -126,8 +151,8 @@ func TestPrepareSampleProjectInstanceRejectsConsumedEntitlementAfterProjectDeletservice := &InstanceService{store: stores,profile: &config.Profile{SaaS: true},- licenseService: &instanceLicenseServiceStub{instanceLimit: 10, activatedInstanceLimit: 10},- sampleManager: &instanceSampleManagerStub{},+ licenseService: newInstanceServiceTestLicenseService(t, stores),+ sampleManager: &sampleManagerStub{},}_, err = service.PrepareSampleProjectInstance(ctx, connect.NewRequest(&v1pb.PrepareSampleProjectInstanceRequest{@@ -142,11 +167,22 @@ func TestSampleProjectInstanceConnectErrorMapsUnknownFailure(t *testing.T) {}func TestSampleProjectInstanceCapacityGuardMapsCapacityDenial(t *testing.T) {- ctx, stores, _, _, _ := setupProjectInstanceLifecycleAPITest(t)+ ctx, stores, projectID, _, _ := setupProjectInstanceLifecycleAPITest(t)+ for i := 0; i < 9; i++ {+ _, err := stores.CreateInstance(ctx, &store.InstanceMessage{+ ResourceID: fmt.Sprintf("capacity-instance-%d", i),+ Workspace: "default",+ ProjectID: &projectID,+ Metadata: &storepb.Instance{+ DataSources: []*storepb.DataSource{{Id: "admin", Type: storepb.DataSourceType_ADMIN}},+ },+ })+ require.NoError(t, err)+ }service := &InstanceService{store: stores,profile: &config.Profile{SaaS: true},- licenseService: &instanceLicenseServiceStub{instanceLimit: 1, activatedInstanceLimit: 10},+ licenseService: newInstanceServiceTestLicenseService(t, stores),}err := service.instanceCountGuard(ctx)require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(err))@@ -157,27 +193,55 @@ func TestSampleProjectInstanceCapacityGuardDoesNotConsumeActivationQuota(t *testservice := &InstanceService{store: stores,profile: &config.Profile{SaaS: true},- licenseService: &instanceLicenseServiceStub{instanceLimit: 10, activatedInstanceLimit: 0},+ licenseService: newInstanceServiceTestLicenseService(t, stores),}require.NoError(t, service.instanceCountGuard(ctx))}-type instanceSampleManagerStub struct {- setupResult *sample.SetupResult- setupErr error- setupRequests []sample.SetupRequest- validate func(context.Context, string, string) error- lifecycle func(context.Context, string, string, bool) error- validateCalls int- lifecycleCalls []bool+type sampleManagerStub struct {+ instance *store.InstanceMessage+ prepareErr error+ prepareRequests []sample.PrepareRequest+ checkAvailableErr error+ checkAvailableCalls int+ listInstancesErr error+ projectPurge func(context.Context, string, string) error+ projectPurgeCalls []string+ validate func(context.Context, string, string) error+ lifecycle func(context.Context, string, string, bool) error+ validateCalls int+ lifecycleCalls []bool+}++func (s *sampleManagerStub) CheckAvailable(context.Context) error {+ s.checkAvailableCalls+++ return s.checkAvailableErr}-func (s *instanceSampleManagerStub) SetupSample(_ context.Context, request sample.SetupRequest) (*sample.SetupResult, error) {- s.setupRequests = append(s.setupRequests, request)- return s.setupResult, s.setupErr+func (s *sampleManagerStub) ListInstances(context.Context, string) ([]*sample.Instance, error) {+ return nil, s.listInstancesErr+}++func (s *sampleManagerStub) HandleProjectPurge(ctx context.Context, workspaceID, projectID string) error {+ s.projectPurgeCalls = append(s.projectPurgeCalls, projectID)+ if s.projectPurge != nil {+ return s.projectPurge(ctx, workspaceID, projectID)+ }+ return nil+}++func (*sampleManagerStub) Start(context.Context, string) error { return nil }++func (*sampleManagerStub) Cleanup(context.Context) error { return nil }++func (*sampleManagerStub) Stop() {}++func (s *sampleManagerStub) PrepareSampleProjectInstance(_ context.Context, request sample.PrepareRequest) (*store.InstanceMessage, error) {+ s.prepareRequests = append(s.prepareRequests, request)+ return s.instance, s.prepareErr}-func (s *instanceSampleManagerStub) ValidateInstanceRestore(ctx context.Context, workspaceID, instanceID string) error {+func (s *sampleManagerStub) ValidateInstanceRestore(ctx context.Context, workspaceID, instanceID string) error {s.validateCalls++if s.validate != nil {return s.validate(ctx, workspaceID, instanceID)@@ -185,7 +249,7 @@ func (s *instanceSampleManagerStub) ValidateInstanceRestore(ctx context.Context,return nil}-func (s *instanceSampleManagerStub) HandleInstanceLifecycle(ctx context.Context, workspaceID, instanceID string, deleted bool) error {+func (s *sampleManagerStub) HandleInstanceLifecycle(ctx context.Context, workspaceID, instanceID string, deleted bool) error {s.lifecycleCalls = append(s.lifecycleCalls, deleted)if s.lifecycle != nil {return s.lifecycle(ctx, workspaceID, instanceID, deleted)diff --git a/backend/api/v1/project_instance_lifecycle_api_test.go b/backend/api/v1/project_instance_lifecycle_api_test.goindex b6942c1175..2156059d7b 100644--- a/backend/api/v1/project_instance_lifecycle_api_test.go+++ b/backend/api/v1/project_instance_lifecycle_api_test.go@@ -2,14 +2,22 @@ package v1import ("context"+ "errors""fmt"+ "os"+ "path/filepath""testing"+ "time""connectrpc.com/connect""github.com/stretchr/testify/require"+ "google.golang.org/protobuf/encoding/protojson""github.com/bytebase/bytebase/backend/common""github.com/bytebase/bytebase/backend/common/testcontainer"+ "github.com/bytebase/bytebase/backend/component/config"+ "github.com/bytebase/bytebase/backend/component/sample"+ "github.com/bytebase/bytebase/backend/component/sample/selfhost""github.com/bytebase/bytebase/backend/enterprise"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"@@ -20,10 +28,18 @@ import (func TestProjectInstanceLifecycleAPIGatesArchivedProjectDescendants(t *testing.T) {ctx, stores, projectID, instanceID, databaseName := setupProjectInstanceLifecycleAPITest(t)- licenseService := &instanceLicenseServiceStub{instanceLimit: 10, activatedInstanceLimit: 10}+ _, err := stores.UpdateInstance(ctx, &store.UpdateInstanceMessage{+ ResourceID: &instanceID,+ Workspace: "default",+ Metadata: &storepb.Instance{+ DataSources: []*storepb.DataSource{{Id: "admin", Type: storepb.DataSourceType_ADMIN}},+ },+ })+ require.NoError(t, err)+ licenseService := newInstanceServiceTestLicenseService(t, stores)databaseLicenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, stores, false, "")require.NoError(t, err)- projectService := NewProjectService(stores, nil, nil)+ projectService := NewProjectService(stores, nil, nil, nil)instanceService := &InstanceService{store: stores, licenseService: licenseService}databaseService := NewDatabaseService(stores, nil, nil, nil, databaseLicenseService)instanceName := common.FormatProjectInstance(projectID, instanceID)@@ -40,7 +56,7 @@ func TestProjectInstanceLifecycleAPIGatesArchivedProjectDescendants(t *testing.Trequire.NoError(t, err)undeleted, err := instanceService.UndeleteInstance(ctx, connect.NewRequest(&v1pb.UndeleteInstanceRequest{Name: instanceName}))require.NoError(t, err)- require.True(t, undeleted.Msg.Activation)+ require.False(t, undeleted.Msg.Activation)_, err = instanceService.DeleteInstance(ctx, connect.NewRequest(&v1pb.DeleteInstanceRequest{Name: instanceName, Force: true}))require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))@@ -65,46 +81,116 @@ func TestProjectInstanceLifecycleAPIGatesArchivedProjectDescendants(t *testing.Trequire.NoError(t, err)undeleted, err = instanceService.UndeleteInstance(ctx, connect.NewRequest(&v1pb.UndeleteInstanceRequest{Name: instanceName}))require.NoError(t, err)- require.True(t, undeleted.Msg.Activation)+ require.False(t, undeleted.Msg.Activation)_, err = projectService.UndeleteProject(ctx, connect.NewRequest(&v1pb.UndeleteProjectRequest{Name: projectName}))require.NoError(t, err)got, err := instanceService.GetInstance(ctx, connect.NewRequest(&v1pb.GetInstanceRequest{Name: instanceName}))require.NoError(t, err)- require.True(t, got.Msg.Activation)+ require.False(t, got.Msg.Activation)}-func TestUndeleteProjectInstanceChecksActivationLimit(t *testing.T) {+func TestProjectPurgeCleansSampleBeforeDeletingMetadata(t *testing.T) {ctx, stores, projectID, instanceID, _ := setupProjectInstanceLifecycleAPITest(t)- licenseService := &instanceLicenseServiceStub{instanceLimit: 10, activatedInstanceLimit: 1}- instanceService := &InstanceService{store: stores, licenseService: licenseService}- instanceName := common.FormatProjectInstance(projectID, instanceID)+ manager := &sampleManagerStub{}+ cleanupErr := errors.New("sample cleanup failed")+ manager.projectPurge = func(ctx context.Context, workspaceID, gotProjectID string) error {+ require.Equal(t, "default", workspaceID)+ require.Equal(t, projectID, gotProjectID)+ instance, err := stores.GetInstance(ctx, &store.FindInstanceMessage{+ Workspace: workspaceID,+ ProjectID: &gotProjectID,+ ResourceID: &instanceID,+ })+ require.NoError(t, err)+ require.NotNil(t, instance)+ if cleanupErr != nil {+ return cleanupErr+ }+ return nil+ }+ projectService := NewProjectService(stores, nil, nil, manager)+ projectName := common.FormatProject(projectID)- _, err := instanceService.DeleteInstance(ctx, connect.NewRequest(&v1pb.DeleteInstanceRequest{Name: instanceName}))+ _, err := projectService.DeleteProject(ctx, connect.NewRequest(&v1pb.DeleteProjectRequest{Name: projectName}))+ require.NoError(t, err)+ _, err = projectService.DeleteProject(ctx, connect.NewRequest(&v1pb.DeleteProjectRequest{Name: projectName, Purge: true}))+ require.Equal(t, connect.CodeInternal, connect.CodeOf(err))+ project, err := stores.GetProject(ctx, &store.FindProjectMessage{+ Workspace: "default",+ ResourceID: &projectID,+ ShowDeleted: true,+ })require.NoError(t, err)+ require.NotNil(t, project)- otherProjectID := "project-b"- _, err = stores.CreateInstance(ctx, &store.InstanceMessage{- ResourceID: "other-project-instance",- Workspace: "default",- ProjectID: &otherProjectID,- Metadata: &storepb.Instance{- Activation: true,- DataSources: []*storepb.DataSource{{- Id: "admin",- Type: storepb.DataSourceType_ADMIN,- }},- },+ cleanupErr = nil+ _, err = projectService.DeleteProject(ctx, connect.NewRequest(&v1pb.DeleteProjectRequest{Name: projectName, Purge: true}))+ require.NoError(t, err)+ require.Equal(t, []string{projectID, projectID}, manager.projectPurgeCalls)++ project, err = stores.GetProject(ctx, &store.FindProjectMessage{+ Workspace: "default",+ ResourceID: &projectID,+ ShowDeleted: true,})require.NoError(t, err)+ require.Nil(t, project)+}- _, err = instanceService.UndeleteInstance(ctx, connect.NewRequest(&v1pb.UndeleteInstanceRequest{Name: instanceName}))- require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(err))+func TestProjectPurgeRemovesSelfHostSample(t *testing.T) {+ ctx, stores, projectID, instanceID, databaseName := setupProjectInstanceLifecycleAPITest(t)+ payload, err := protojson.Marshal(&storepb.SelfHostSampleInstanceSetupPayload{+ Instances: []*storepb.SelfHostSampleInstanceSetupPayload_Instance{{+ InstanceId: instanceID,+ ProjectId: &projectID,+ Title: "Sample Project Instance",+ DatabaseName: databaseName,+ RoleName: "sample-role",+ }},+ })+ require.NoError(t, err)+ const replicaID = "replica-a"+ _, created, err := stores.ReserveSampleInstanceSetup(ctx, &store.SampleInstanceSetupMessage{+ WorkspaceID: "default",+ ReplicaID: replicaID,+ Payload: payload,+ })+ require.NoError(t, err)+ require.True(t, created)+ activated, err := stores.ActivateSampleInstanceSetup(ctx, "default", replicaID, []string{projectID}, time.Now(), nil)+ require.NoError(t, err)+ require.True(t, activated)- instance, err := getInstanceMessageForLifecycle(ctx, stores, instanceName)+ dataRoot := t.TempDir()+ dataDir := filepath.Join(dataRoot, "pgdata-sample-managed", instanceID)+ require.NoError(t, os.MkdirAll(dataDir, 0o755))+ require.NoError(t, os.WriteFile(filepath.Join(dataDir, "sample-data"), []byte("sample"), 0o644))+ manager := selfhost.NewManager(+ stores,+ &config.Profile{DataDir: dataRoot, Port: 8080},+ nil,+ sample.ManagerOptions{ReplicaID: replicaID},+ )+ projectService := NewProjectService(stores, nil, nil, manager)+ projectName := common.FormatProject(projectID)++ _, err = projectService.DeleteProject(ctx, connect.NewRequest(&v1pb.DeleteProjectRequest{Name: projectName}))require.NoError(t, err)- require.True(t, instance.Deleted)- require.True(t, instance.Metadata.GetActivation())+ _, err = projectService.DeleteProject(ctx, connect.NewRequest(&v1pb.DeleteProjectRequest{Name: projectName, Purge: true}))+ require.NoError(t, err)++ _, err = os.Stat(dataDir)+ require.ErrorIs(t, err, os.ErrNotExist)+ setup, err := stores.GetSampleInstanceSetup(ctx, "default")+ require.NoError(t, err)+ require.NotNil(t, setup)+ require.NotNil(t, setup.DeletedAt)+ instances, err := manager.ListInstances(ctx, "default")+ require.NoError(t, err)+ require.Len(t, instances, 1)+ require.Equal(t, common.FormatProjectInstance(projectID, instanceID), instances[0].Name)+ require.Nil(t, instances[0].ExpireTime)}func TestBatchSyncDatabasesValidatesAllTargetsBeforeScheduling(t *testing.T) {@@ -123,29 +209,29 @@ func TestBatchSyncDatabasesValidatesAllTargetsBeforeScheduling(t *testing.T) {require.Equal(t, connect.CodeInvalidArgument, connect.CodeOf(err))}-type instanceLicenseServiceStub struct {- instanceLimit int- activatedInstanceLimit int-}--func (s *instanceLicenseServiceStub) GetActivatedInstanceLimit(context.Context, string) int {- return s.activatedInstanceLimit-}+func TestUndeleteProjectInstanceChecksActivationLimit(t *testing.T) {+ ctx, stores, projectID, instanceID, _ := setupProjectInstanceLifecycleAPITest(t)+ licenseService := newInstanceServiceTestLicenseService(t, stores)+ instanceService := &InstanceService{store: stores, licenseService: licenseService}+ instanceName := common.FormatProjectInstance(projectID, instanceID)-func (s *instanceLicenseServiceStub) GetInstanceLimit(context.Context, string) int {- return s.instanceLimit-}+ _, err := instanceService.DeleteInstance(ctx, connect.NewRequest(&v1pb.DeleteInstanceRequest{Name: instanceName}))+ require.NoError(t, err)-func (*instanceLicenseServiceStub) IsFeatureEnabledForInstance(context.Context, string, v1pb.PlanFeature, *store.InstanceMessage) error {- return nil-}+ _, err = instanceService.UndeleteInstance(ctx, connect.NewRequest(&v1pb.UndeleteInstanceRequest{Name: instanceName}))+ require.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(err))-func (s *instanceLicenseServiceStub) IsInstanceEffectivelyActivated(_ context.Context, _ string, instance *store.InstanceMessage) bool {- return instance.Metadata.GetActivation() || s.instanceLimit <= s.activatedInstanceLimit+ instance, err := getInstanceMessageForLifecycle(ctx, stores, instanceName)+ require.NoError(t, err)+ require.True(t, instance.Deleted)+ require.True(t, instance.Metadata.GetActivation())}-func (s *instanceLicenseServiceStub) IsUnifiedInstanceLicense(context.Context, string) bool {- return s.instanceLimit <= s.activatedInstanceLimit+func newInstanceServiceTestLicenseService(t *testing.T, stores *store.Store) *enterprise.LicenseService {+ t.Helper()+ licenseService, err := enterprise.NewLicenseService(common.ReleaseModeDev, stores, false, "")+ require.NoError(t, err)+ return licenseService}func setupProjectInstanceLifecycleAPITest(t *testing.T) (context.Context, *store.Store, string, string, string) {diff --git a/backend/api/v1/project_service.go b/backend/api/v1/project_service.goindex 9bcc5a4f0f..51e1e91901 100644--- a/backend/api/v1/project_service.go+++ b/backend/api/v1/project_service.go@@ -23,6 +23,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/component/sample""github.com/bytebase/bytebase/backend/utils"storepb "github.com/bytebase/bytebase/backend/generated-go/store"@@ -35,9 +36,10 @@ import (// ProjectService implements the project service.type ProjectService struct {v1connect.UnimplementedProjectServiceHandler- store *store.Store- profile *config.Profile- iamManager *iam.Manager+ store *store.Store+ profile *config.Profile+ iamManager *iam.Manager+ sampleManager sample.Manager}// NewProjectService creates a new ProjectService.@@ -45,11 +47,13 @@ func NewProjectService(store *store.Store,profile *config.Profile,iamManager *iam.Manager,+ sampleManager sample.Manager,) *ProjectService {return &ProjectService{- store: store,- profile: profile,- iamManager: iamManager,+ store: store,+ profile: profile,+ iamManager: iamManager,+ sampleManager: sampleManager,}}@@ -401,6 +405,12 @@ func (s *ProjectService) DeleteProject(ctx context.Context, req *connect.Requestreturn nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("project %q must be archived before it can be deleted", req.Msg.Name))}+ if s.sampleManager != nil {+ if err := s.sampleManager.HandleProjectPurge(ctx, project.Workspace, project.ResourceID); err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to clean up sample project"))+ }+ }+// Permanently delete the project and all related resources (moves databases to default project)if err := s.store.DeleteProject(ctx, project.Workspace, project.ResourceID); err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to purge project"))@@ -483,6 +493,11 @@ func (s *ProjectService) BatchDeleteProjects(ctx context.Context, request *conne// Permanently delete all projects (moves databases to default project)for _, project := range projectsToPurge {+ if s.sampleManager != nil {+ if err := s.sampleManager.HandleProjectPurge(ctx, project.Workspace, project.ResourceID); err != nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to clean up sample project %q", project.Title))+ }+ }if err := s.store.DeleteProject(ctx, project.Workspace, project.ResourceID); err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to purge project %q", project.Title))}diff --git a/backend/api/v1/sample_project_instance_integration_test.go b/backend/api/v1/sample_project_instance_integration_test.goindex 7b3a79850a..1073be1873 100644--- a/backend/api/v1/sample_project_instance_integration_test.go+++ b/backend/api/v1/sample_project_instance_integration_test.go@@ -148,6 +148,35 @@ func TestPrepareSampleProjectInstanceLifecycle(t *testing.T) {require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))}+func TestSampleProjectPurgeRejectsPendingReservation(t *testing.T) {+ ctx, fixture := newSampleProjectInstanceFixture(t, time.Now)+ payload := &storepb.SaaSSampleInstanceSetupPayload{+ ProjectId: fixture.projectID,+ InstanceId: "pending-sample",+ Title: "Sample Project Instance",+ DatabaseName: "pending-database",+ RoleName: "pending-role",+ }+ encoded, err := protojson.Marshal(payload)+ require.NoError(t, err)+ _, created, err := fixture.store.ReserveSampleInstanceSetup(ctx, &store.SampleInstanceSetupMessage{+ WorkspaceID: fixture.workspaceID,+ ReplicaID: "replica-a",+ Payload: encoded,+ })+ require.NoError(t, err)+ require.True(t, created)++ err = fixture.manager.HandleProjectPurge(ctx, fixture.workspaceID, fixture.projectID)+ require.ErrorContains(t, err, "sample provisioning is still in progress")++ setup, err := fixture.store.GetSampleInstanceSetup(ctx, fixture.workspaceID)+ require.NoError(t, err)+ require.NotNil(t, setup)+ require.Nil(t, setup.ActivatedAt)+ require.Nil(t, setup.DeletedAt)+}+func TestPrepareSampleProjectInstanceAdditionalLifecycleCoverage(t *testing.T) {now := time.Date(2026, time.August, 17, 12, 0, 0, 0, time.UTC)ctx, fixture := newSampleProjectInstanceFixture(t, func() time.Time { return now })@@ -180,15 +209,6 @@ func TestPrepareSampleProjectInstanceAdditionalLifecycleCoverage(t *testing.T) {require.Zero(t, fixture.sampleRecordCount(ctx, t))})- t.Run("Cloud-only gating", func(t *testing.T) {- fixture.service.profile.SaaS = false- _, err := fixture.service.PrepareSampleProjectInstance(ctx, connect.NewRequest(&v1pb.PrepareSampleProjectInstanceRequest{- Parent: common.FormatProject(fixture.projectID),- }))- require.Equal(t, connect.CodeFailedPrecondition, connect.CodeOf(err))- fixture.service.profile.SaaS = true- })-t.Run("workspace without environments still prepares a sample", func(t *testing.T) {workspaceID := "sample-workspace-no-environment"projectID := "sample-project-no-environment"@@ -351,7 +371,7 @@ func newSampleProjectInstanceFixture(t *testing.T, clock func() time.Time) (contservice: &InstanceService{store: stores,profile: &config.Profile{SaaS: true},- licenseService: &instanceLicenseServiceStub{instanceLimit: 10, activatedInstanceLimit: 0},+ licenseService: licenseService,dbFactory: dbFactory,schemaSyncer: syncer,sampleManager: manager,diff --git a/backend/api/v1/testdata/mcp_method_classification.md b/backend/api/v1/testdata/mcp_method_classification.mdindex e672831213..cb0a955286 100644--- a/backend/api/v1/testdata/mcp_method_classification.md+++ b/backend/api/v1/testdata/mcp_method_classification.md@@ -18,10 +18,10 @@ served by no ceiling.|---|---|---|| READ | 57 | served to a read-only session and above || WRITE | 40 | served to a read-write session only |-| EXCLUDED | 86 | served by no ceiling this phase ships |+| EXCLUDED | 85 | served by no ceiling this phase ships || FORBIDDEN | 34 | never served, whatever the ceiling || MCP_METHOD_CLASS_UNSPECIFIED | 0 | unclassified — CI rejects this, and the gate refuses it |-| **total** | **217** | |+| **total** | **216** | || Method | Class | Reason | Permission ||---|---|---|---|@@ -33,7 +33,6 @@ served by no ceiling.| AccessGrantService/RevokeAccessGrant | EXCLUDED | ADMINISTERS_THE_WORKSPACE | bb.accessGrants.revoke || AccessGrantService/SearchMyAccessGrants | READ | — | bb.accessGrants.get || ActuatorService/GetActuatorInfo | READ | — | — |-| ActuatorService/SetupSample | EXCLUDED | ADMINISTERS_THE_WORKSPACE | bb.projects.create || AuditLogService/ExportAuditLogs | EXCLUDED | ADMINISTERS_THE_WORKSPACE | bb.auditLogs.export || AuditLogService/SearchAuditLogs | EXCLUDED | ADMINISTERS_THE_WORKSPACE | bb.auditLogs.search || AuthService/ExchangeToken | FORBIDDEN | MINTS_CREDENTIAL | — |diff --git a/backend/component/sample/saas/manager.go b/backend/component/sample/saas/manager.goindex 4c6d7412b3..6e19ac6bcf 100644--- a/backend/component/sample/saas/manager.go+++ b/backend/component/sample/saas/manager.go@@ -87,23 +87,30 @@ func sampleNames(instanceID string) (string, string) {return "bb_sample_" + token, "bb_sample_role_" + token}-// Available reports cached target readiness, refreshing stale state with a+// CheckAvailable checks cached target readiness, refreshing stale state with a// short probe.-func (m *Manager) Available(ctx context.Context) bool {+func (m *Manager) CheckAvailable(ctx context.Context) error {if m == nil || m.target == nil {- return false+ return sample.NewFailure(sample.FailureUnavailable, errors.New("SaaS sample target is not configured"))}m.availabilityMu.Lock()defer m.availabilityMu.Unlock()now := m.clock()if !m.availabilityCheckedAt.IsZero() && now.Before(m.availabilityCheckedAt.Add(targetAvailabilityCacheTTL)) {- return m.available+ if m.available {+ return nil+ }+ return sample.NewFailure(sample.FailureUnavailable, errors.New("SaaS sample target is unavailable"))}validationCtx, cancel := context.WithTimeout(ctx, targetAvailabilityDeadline)defer cancel()- m.available = m.target.validate(validationCtx) == nil+ err := m.target.validate(validationCtx)+ m.available = err == nilm.availabilityCheckedAt = m.clock()- return m.available+ if err != nil {+ return sample.NewFailure(sample.FailureUnavailable, err)+ }+ return nil}func (m *Manager) recordAvailability(available bool) {@@ -113,8 +120,8 @@ func (m *Manager) recordAvailability(available bool) {m.availabilityCheckedAt = m.clock()}-// SetupSample provisions and registers one seven-day sample instance.-func (m *Manager) SetupSample(ctx context.Context, request sample.SetupRequest) (*sample.SetupResult, error) {+// PrepareSampleProjectInstance provisions and registers one seven-day sample instance.+func (m *Manager) PrepareSampleProjectInstance(ctx context.Context, request sample.PrepareRequest) (*store.InstanceMessage, error) {if m == nil || m.store == nil || m.target == nil || m.syncer == nil || m.replicaID == "" {return nil, errors.New("SaaS sample manager is not configured")}@@ -183,7 +190,7 @@ func (m *Manager) SetupSample(ctx context.Context, request sample.SetupRequest)}}-func (m *Manager) reserve(ctx context.Context, request sample.SetupRequest) (*store.SampleInstanceSetupMessage, bool, error) {+func (m *Manager) reserve(ctx context.Context, request sample.PrepareRequest) (*store.SampleInstanceSetupMessage, bool, error) {instanceID, err := randomInstanceID(m.random)if err != nil {return nil, false, errors.Join(errors.New("failed to generate SaaS sample instance ID"), err)@@ -228,7 +235,7 @@ func decodePayload(setup *store.SampleInstanceSetupMessage) (*storepb.SaaSSamplereturn payload, nil}-func (m *Manager) prepareOwned(ctx context.Context, setup *store.SampleInstanceSetupMessage, payload *storepb.SaaSSampleInstanceSetupPayload, takeover bool) (*sample.SetupResult, error) {+func (m *Manager) prepareOwned(ctx context.Context, setup *store.SampleInstanceSetupMessage, payload *storepb.SaaSSampleInstanceSetupPayload, takeover bool) (*store.InstanceMessage, error) {workCtx, cancel := preparationWorkContext(ctx)defer cancel()if takeover {@@ -302,10 +309,10 @@ func (m *Manager) prepareOwned(ctx context.Context, setup *store.SampleInstanceSreturn m.handleActivationFailure(ctx, setup, payload, errors.Join(errors.New("failed to activate SaaS sample setup"), err))}m.syncer.SyncDatabasesAsync(databases)- return &sample.SetupResult{Instances: []*store.InstanceMessage{synced}}, nil+ return synced, nil}-func (m *Manager) activeSetup(ctx context.Context, setup *store.SampleInstanceSetupMessage, payload *storepb.SaaSSampleInstanceSetupPayload) (*sample.SetupResult, error) {+func (m *Manager) activeSetup(ctx context.Context, setup *store.SampleInstanceSetupMessage, payload *storepb.SaaSSampleInstanceSetupPayload) (*store.InstanceMessage, error) {projectID := payload.ProjectIdstate, err := sample.LookupMetadata(ctx, m.store, sample.MetadataLookup{WorkspaceID: setup.WorkspaceID,@@ -320,7 +327,7 @@ func (m *Manager) activeSetup(ctx context.Context, setup *store.SampleInstanceSeif !state.Active() {return nil, sample.NewFailure(sample.FailureFailedPrecondition, errors.New("SaaS sample metadata is not active"))}- return &sample.SetupResult{Instances: []*store.InstanceMessage{state.Instance}}, nil+ return state.Instance, nil}func (m *Manager) reconcile(ctx context.Context, setup *store.SampleInstanceSetupMessage, payload *storepb.SaaSSampleInstanceSetupPayload) error {@@ -330,7 +337,7 @@ func (m *Manager) reconcile(ctx context.Context, setup *store.SampleInstanceSetureturn errors.Join(metadataErr, targetErr)}-func (m *Manager) compensate(ctx context.Context, setup *store.SampleInstanceSetupMessage, payload *storepb.SaaSSampleInstanceSetupPayload, original error) (*sample.SetupResult, error) {+func (m *Manager) compensate(ctx context.Context, setup *store.SampleInstanceSetupMessage, payload *storepb.SaaSSampleInstanceSetupPayload, original error) (*store.InstanceMessage, error) {compensationCtx, cancel := context.WithTimeout(ctx, compensationDeadline)defer cancel()current, err := m.store.GetSampleInstanceSetup(compensationCtx, setup.WorkspaceID)@@ -365,7 +372,7 @@ func (m *Manager) discardReservation(ctx context.Context, setup *store.SampleInsreturn original}-func (m *Manager) handleActivationFailure(ctx context.Context, setup *store.SampleInstanceSetupMessage, payload *storepb.SaaSSampleInstanceSetupPayload, original error) (*sample.SetupResult, error) {+func (m *Manager) handleActivationFailure(ctx context.Context, setup *store.SampleInstanceSetupMessage, payload *storepb.SaaSSampleInstanceSetupPayload, original error) (*store.InstanceMessage, error) {current, err := m.store.GetSampleInstanceSetup(ctx, setup.WorkspaceID)if err != nil {return nil, sample.NewFailure(sample.FailureUnavailable, errors.Join(original, err))@@ -383,26 +390,24 @@ func (m *Manager) handleActivationFailure(ctx context.Context, setup *store.Sampreturn m.compensate(ctx, setup, payload, original)}-// Info returns target readiness and the provisioned SaaS instance.-func (m *Manager) Info(ctx context.Context, workspaceID string) (*sample.Info, error) {+// ListInstances returns the provisioned SaaS instances.+func (m *Manager) ListInstances(ctx context.Context, workspaceID string) ([]*sample.Instance, error) {if m == nil {- return &sample.Info{}, nil+ return nil, nil}- info := &sample.Info{Available: m.Available(ctx)}setup, err := m.store.GetSampleInstanceSetup(ctx, workspaceID)if err != nil || setup == nil || setup.ActivatedAt == nil {- return info, err+ return nil, err}payload, err := decodePayload(setup)if err != nil {return nil, err}- instance := sample.InstanceInfo{Instance: common.FormatProjectInstance(payload.ProjectId, payload.InstanceId)}+ instance := &sample.Instance{Name: common.FormatProjectInstance(payload.ProjectId, payload.InstanceId)}if setup.DeletedAt == nil {instance.ExpireTime = setup.ExpiresAt}- info.Instances = append(info.Instances, instance)- return info, nil+ return []*sample.Instance{instance}, nil}// Start is a no-op because the external PostgreSQL server is already running.@@ -486,6 +491,34 @@ func (m *Manager) ValidateInstanceRestore(ctx context.Context, workspaceID, inst// change external PostgreSQL resources before expiration.func (*Manager) HandleInstanceLifecycle(context.Context, string, string, bool) error { return nil }+// HandleProjectPurge removes sample resources owned by a project before purge.+func (m *Manager) HandleProjectPurge(ctx context.Context, workspaceID, projectID string) error {+ if m == nil || m.store == nil || m.target == nil {+ return errors.New("SaaS sample manager is not configured")+ }+ return m.store.WithLockedSampleInstanceSetup(ctx, workspaceID, func(callbackCtx context.Context, tx *store.SampleInstanceSetupTx, setup *store.SampleInstanceSetupMessage) error {+ payload, err := decodePayload(setup)+ if err != nil {+ return err+ }+ if payload.ProjectId != projectID {+ return nil+ }+ attemptCtx, cancel := context.WithTimeout(callbackCtx, cleanupAttemptDeadline)+ defer cancel()+ if setup.ActivatedAt == nil {+ return errors.New("sample provisioning is still in progress")+ }+ if err := m.target.remove(attemptCtx, allocation{database: payload.DatabaseName, role: payload.RoleName}); err != nil {+ return err+ }+ if _, err := sample.ArchiveMetadata(attemptCtx, m.store, workspaceID, &projectID, payload.InstanceId); err != nil {+ return err+ }+ return tx.MarkDeleted(attemptCtx, m.clock())+ })+}+// Stop is a no-op for the external target.func (*Manager) Stop() {}diff --git a/backend/component/sample/saas/manager_test.go b/backend/component/sample/saas/manager_test.goindex 0cd85936a4..3cf94c8cce 100644--- a/backend/component/sample/saas/manager_test.go+++ b/backend/component/sample/saas/manager_test.go@@ -1,11 +1,21 @@package saasimport (+ "context""testing""github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/backend/component/sample")+func TestCheckAvailableRejectsUnconfiguredManager(t *testing.T) {+ var manager *Manager+ err := manager.CheckAvailable(context.Background())+ require.Error(t, err)+ require.Equal(t, sample.FailureUnavailable, sample.FailureKindOf(err))+}+func TestSampleNamesAreStableAndShort(t *testing.T) {database, role := sampleNames("sample-0123456789abcdef")require.Equal(t, "bb_sample_d3bc52190e66d2ca", database)diff --git a/backend/component/sample/selfhost/manager.go b/backend/component/sample/selfhost/manager.goindex fbbbace08e..8f80dfad47 100644--- a/backend/component/sample/selfhost/manager.go+++ b/backend/component/sample/selfhost/manager.go@@ -1,5 +1,5 @@-// Package selfhost manages the two workspace-level embedded PostgreSQL sample-// instances used by self-hosted Bytebase.+// Package selfhost manages embedded PostgreSQL sample instances used by+// self-hosted Bytebase.package selfhostimport (@@ -84,22 +84,16 @@ func managedEntry(instanceID, title string, portOffset int32, database string) *}}-func newPayload(reader io.Reader, projectID string, testEnvironment, prodEnvironment *string) (*storepb.SelfHostSampleInstanceSetupPayload, error) {- testID, err := randomInstanceID(reader)+func newPayload(reader io.Reader, projectID string, environmentID *string) (*storepb.SelfHostSampleInstanceSetupPayload, error) {+ instanceID, err := randomInstanceID(reader)if err != nil {return nil, err}- prodID, err := randomInstanceID(reader)- if err != nil {- return nil, err- }- test := managedEntry(testID, "Test Sample Instance", 0, sampleDatabaseTest)- prod := managedEntry(prodID, "Prod Sample Instance", 1, sampleDatabaseProd)- test.EnvironmentId = testEnvironment- prod.EnvironmentId = prodEnvironment+ entry := managedEntry(instanceID, "Sample Project Instance", 0, sampleDatabaseTest)+ entry.EnvironmentId = environmentID+ entry.ProjectId = &projectIDreturn &storepb.SelfHostSampleInstanceSetupPayload{- DatabaseProjectId: projectID,- Instances: []*storepb.SelfHostSampleInstanceSetupPayload_Instance{test, prod},+ Instances: []*storepb.SelfHostSampleInstanceSetupPayload_Instance{entry},}, nil}@@ -128,19 +122,28 @@ func decode(setup *store.SampleInstanceSetupMessage) (*storepb.SelfHostSampleInsif err := common.ProtojsonUnmarshaler.Unmarshal(setup.Payload, payload); err != nil {return nil, sample.NewFailure(sample.FailureFailedPrecondition, errors.New("invalid self-host sample setup payload"))}- if payload.DatabaseProjectId == "" || len(payload.Instances) != 2 {- return nil, sample.NewFailure(sample.FailureFailedPrecondition, errors.New("incomplete self-host sample setup payload"))- }for _, entry := range payload.Instances {if entry.InstanceId == "" || entry.Title == "" || entry.DatabaseName == "" || entry.RoleName == "" {return nil, sample.NewFailure(sample.FailureFailedPrecondition, errors.New("incomplete self-host sample instance payload"))}}+ if len(payload.Instances) != 1 || payload.Instances[0].ProjectId == nil || payload.Instances[0].GetProjectId() == "" {+ return nil, sample.NewFailure(sample.FailureFailedPrecondition, errors.New("unsupported self-host sample setup payload"))+ }return payload, nil}-// SetupSample creates two permanent workspace-level embedded sample instances.-func (m *Manager) SetupSample(ctx context.Context, request sample.SetupRequest) (*sample.SetupResult, error) {+// CheckAvailable reports whether embedded PostgreSQL is available for a+// self-host sample instance.+func (m *Manager) CheckAvailable(context.Context) error {+ if m == nil || m.profile == nil || !m.profile.UseEmbedDB() {+ return sample.NewFailure(sample.FailureFailedPrecondition, errors.New("self-host sample requires embedded PostgreSQL"))+ }+ return nil+}++// PrepareSampleProjectInstance creates one permanent project-level embedded sample instance.+func (m *Manager) PrepareSampleProjectInstance(ctx context.Context, request sample.PrepareRequest) (*store.InstanceMessage, error) {if m == nil || m.store == nil || m.profile == nil || m.syncer == nil || m.replicaID == "" {return nil, errors.New("self-host sample manager is not configured")}@@ -166,7 +169,7 @@ func (m *Manager) SetupSample(ctx context.Context, request sample.SetupRequest)if err != nil {return nil, err}- if payload.DatabaseProjectId != request.ProjectID || setup.DeletedAt != nil {+ if len(payload.Instances) != 1 || payload.Instances[0].GetProjectId() != request.ProjectID || setup.DeletedAt != nil {return nil, sample.NewFailure(sample.FailureFailedPrecondition, errors.New("sample setup entitlement is already consumed"))}if created {@@ -209,24 +212,17 @@ func (m *Manager) SetupSample(ctx context.Context, request sample.SetupRequest)}}-func (m *Manager) reserve(ctx context.Context, request sample.SetupRequest) (*store.SampleInstanceSetupMessage, bool, error) {+func (m *Manager) reserve(ctx context.Context, request sample.PrepareRequest) (*store.SampleInstanceSetupMessage, bool, error) {environments, err := m.store.GetEnvironment(ctx, request.WorkspaceID)if err != nil {return nil, false, err}- var testEnvironment, prodEnvironment *string- for _, environment := range environments.GetEnvironments() {- switch environment.Id {- case common.DefaultTestEnvironmentID:- value := environment.Id- testEnvironment = &value- case common.DefaultProdEnvironmentID:- value := environment.Id- prodEnvironment = &value- default:- }+ var environmentID *string+ if len(environments.GetEnvironments()) > 0 {+ value := environments.GetEnvironments()[0].Id+ environmentID = &value}- payload, err := newPayload(m.random, request.ProjectID, testEnvironment, prodEnvironment)+ payload, err := newPayload(m.random, request.ProjectID, environmentID)if err != nil {return nil, false, pkgerrors.Wrap(err, "failed to generate self-host sample payload")}@@ -241,46 +237,47 @@ func (m *Manager) reserve(ctx context.Context, request sample.SetupRequest) (*st})}-func (m *Manager) prepareOwned(ctx context.Context, setup *store.SampleInstanceSetupMessage, payload *storepb.SelfHostSampleInstanceSetupPayload, takeover bool) (*sample.SetupResult, error) {+func (m *Manager) prepareOwned(ctx context.Context, setup *store.SampleInstanceSetupMessage, payload *storepb.SelfHostSampleInstanceSetupPayload, takeover bool) (*store.InstanceMessage, error) {+ if len(payload.Instances) != 1 || payload.Instances[0].ProjectId == nil {+ return nil, sample.NewFailure(sample.FailureFailedPrecondition, errors.New("sample setup entitlement is already consumed"))+ }if takeover {if err := m.reconcile(ctx, setup.WorkspaceID, payload); err != nil {return nil, sample.NewFailure(sample.FailureUnavailable, err)}}- instances := make([]*store.InstanceMessage, 0, len(payload.Instances))- for _, entry := range payload.Instances {- if err := m.startEntry(ctx, entry); err != nil {- return nil, m.compensate(ctx, setup, payload, err)- }- registered, err := sample.CreateMetadata(ctx, m.store, sample.Registration{- WorkspaceID: setup.WorkspaceID,- EnvironmentID: entry.EnvironmentId,- InstanceID: entry.InstanceId,- Title: entry.Title,- AdminDataSource: dataSource(m.profile, entry),- SyncDatabaseNames: []string{entry.DatabaseName},- })- if err != nil {- return nil, m.compensate(ctx, setup, payload, err)- }- synced, _, databases, err := m.syncer.SyncInstance(ctx, registered)- if err != nil || len(databases) != 1 || databases[0].DatabaseName != entry.DatabaseName || databases[0].Deleted {- return nil, m.compensate(ctx, setup, payload, errors.Join(err, errors.New("self-host sample database discovery invariant failed")))- }- if err := sample.TransferDatabase(ctx, m.store, payload.DatabaseProjectId, entry.InstanceId, entry.DatabaseName); err != nil {- return nil, m.compensate(ctx, setup, payload, err)- }- if err := m.createBaseline(ctx, databases[0]); err != nil {- return nil, m.compensate(ctx, setup, payload, err)- }- m.syncer.SyncDatabasesAsync(databases)- instances = append(instances, synced)+ entry := payload.Instances[0]+ if err := m.startEntry(ctx, entry); err != nil {+ return nil, m.compensate(ctx, setup, payload, err)+ }+ registered, err := sample.CreateMetadata(ctx, m.store, sample.Registration{+ WorkspaceID: setup.WorkspaceID,+ InstanceProjectID: entry.ProjectId,+ EnvironmentID: entry.EnvironmentId,+ InstanceID: entry.InstanceId,+ Title: entry.Title,+ AdminDataSource: dataSource(m.profile, entry),+ SyncDatabaseNames: []string{entry.DatabaseName},+ })+ if err != nil {+ return nil, m.compensate(ctx, setup, payload, err)+ }+ synced, _, databases, err := m.syncer.SyncInstance(ctx, registered)+ if err != nil || len(databases) != 1 || databases[0].DatabaseName != entry.DatabaseName || databases[0].Deleted {+ return nil, m.compensate(ctx, setup, payload, errors.Join(err, errors.New("self-host sample database discovery invariant failed")))+ }+ if err := sample.TransferDatabase(ctx, m.store, entry.GetProjectId(), entry.InstanceId, entry.DatabaseName); err != nil {+ return nil, m.compensate(ctx, setup, payload, err)+ }+ if err := m.createBaseline(ctx, databases[0]); err != nil {+ return nil, m.compensate(ctx, setup, payload, err)}- activated, err := m.store.ActivateSampleInstanceSetup(ctx, setup.WorkspaceID, m.replicaID, []string{payload.DatabaseProjectId}, m.clock(), nil)+ m.syncer.SyncDatabasesAsync(databases)+ activated, err := m.store.ActivateSampleInstanceSetup(ctx, setup.WorkspaceID, m.replicaID, []string{entry.GetProjectId()}, m.clock(), nil)if err != nil || !activated {return nil, m.compensate(ctx, setup, payload, errors.Join(errors.New("failed to activate self-host sample setup"), err))}- return &sample.SetupResult{Instances: instances}, nil+ return synced, nil}func dataSource(profile *config.Profile, entry *storepb.SelfHostSampleInstanceSetupPayload_Instance) *storepb.DataSource {@@ -309,24 +306,25 @@ func (m *Manager) createBaseline(ctx context.Context, database *store.DatabaseMereturn err}-func (m *Manager) activeSetup(ctx context.Context, setup *store.SampleInstanceSetupMessage, payload *storepb.SelfHostSampleInstanceSetupPayload) (*sample.SetupResult, error) {- instances := make([]*store.InstanceMessage, 0, len(payload.Instances))- for _, entry := range payload.Instances {- state, err := sample.LookupMetadata(ctx, m.store, sample.MetadataLookup{- WorkspaceID: setup.WorkspaceID,- DatabaseProjectID: payload.DatabaseProjectId,- InstanceID: entry.InstanceId,- DatabaseName: entry.DatabaseName,- })- if err != nil {- return nil, err- }- if !state.Active() {- return nil, sample.NewFailure(sample.FailureFailedPrecondition, errors.New("self-host sample metadata is not active"))- }- instances = append(instances, state.Instance)+func (m *Manager) activeSetup(ctx context.Context, setup *store.SampleInstanceSetupMessage, payload *storepb.SelfHostSampleInstanceSetupPayload) (*store.InstanceMessage, error) {+ if len(payload.Instances) != 1 || payload.Instances[0].ProjectId == nil {+ return nil, sample.NewFailure(sample.FailureFailedPrecondition, errors.New("sample setup entitlement is already consumed"))+ }+ entry := payload.Instances[0]+ state, err := sample.LookupMetadata(ctx, m.store, sample.MetadataLookup{+ WorkspaceID: setup.WorkspaceID,+ InstanceProjectID: entry.ProjectId,+ DatabaseProjectID: entry.GetProjectId(),+ InstanceID: entry.InstanceId,+ DatabaseName: entry.DatabaseName,+ })+ if err != nil {+ return nil, err+ }+ if !state.Active() {+ return nil, sample.NewFailure(sample.FailureFailedPrecondition, errors.New("self-host sample metadata is not active"))}- return &sample.SetupResult{Instances: instances}, nil+ return state.Instance, nil}func (m *Manager) compensate(ctx context.Context, setup *store.SampleInstanceSetupMessage, payload *storepb.SelfHostSampleInstanceSetupPayload, original error) error {@@ -343,7 +341,7 @@ func (m *Manager) compensate(ctx context.Context, setup *store.SampleInstanceSetfunc (m *Manager) reconcile(ctx context.Context, workspaceID string, payload *storepb.SelfHostSampleInstanceSetupPayload) error {var result errorfor _, entry := range payload.Instances {- result = errors.Join(result, sample.PurgePartialMetadata(ctx, m.store, workspaceID, nil, entry.InstanceId))+ result = errors.Join(result, sample.PurgePartialMetadata(ctx, m.store, workspaceID, entry.ProjectId, entry.InstanceId))m.stopEntry(entry.InstanceId)result = errors.Join(result, postgres.RemoveEmbeddedInstance(sampleConfig(m.profile, entry).DataDir))}@@ -379,8 +377,8 @@ func (m *Manager) stopEntry(instanceID string) {}}-// Info reports managed payload instances or historical static instances.-func (m *Manager) Info(ctx context.Context, workspaceID string) (*sample.Info, error) {+// ListInstances reports managed payload instances or historical static instances.+func (m *Manager) ListInstances(ctx context.Context, workspaceID string) ([]*sample.Instance, error) {setup, err := m.store.GetSampleInstanceSetup(ctx, workspaceID)if err != nil {return nil, err@@ -390,25 +388,25 @@ func (m *Manager) Info(ctx context.Context, workspaceID string) (*sample.Info, eif err != nil {return nil, err}- info := &sample.Info{Available: setup.DeletedAt == nil}+ instances := make([]*sample.Instance, 0, len(payload.Instances))for _, entry := range payload.Instances {- instance := sample.InstanceInfo{Instance: common.FormatInstance(entry.InstanceId)}+ instance := &sample.Instance{Name: common.FormatProjectInstance(entry.GetProjectId(), entry.InstanceId)}if setup.DeletedAt == nil {instance.ExpireTime = setup.ExpiresAt}- info.Instances = append(info.Instances, instance)+ instances = append(instances, instance)}- return info, nil+ return instances, nil}legacy, err := m.legacy.info(ctx, workspaceID)if err != nil {return nil, err}- info := &sample.Info{Available: true}+ instances := make([]*sample.Instance, 0, len(legacy))for _, entry := range legacy {- info.Instances = append(info.Instances, sample.InstanceInfo{Instance: entry.instance})+ instances = append(instances, &sample.Instance{Name: entry.instance})}- return info, nil+ return instances, nil}// Start restores active embedded sample processes after server restart.@@ -471,7 +469,7 @@ func (m *Manager) Cleanup(ctx context.Context) error {if err := postgres.RemoveEmbeddedInstance(sampleConfig(m.profile, entry).DataDir); err != nil {return err}- if _, err := sample.ArchiveMetadata(callbackCtx, m.store, setup.WorkspaceID, nil, entry.InstanceId); err != nil {+ if _, err := sample.ArchiveMetadata(callbackCtx, m.store, setup.WorkspaceID, entry.ProjectId, entry.InstanceId); err != nil {return err}}@@ -557,6 +555,38 @@ func (m *Manager) HandleInstanceLifecycle(ctx context.Context, workspaceID, instreturn nil}+// HandleProjectPurge removes sample resources owned by a project before purge.+func (m *Manager) HandleProjectPurge(ctx context.Context, workspaceID, projectID string) error {+ if m == nil || m.store == nil || m.profile == nil {+ return errors.New("self-host sample manager is not configured")+ }+ return m.store.WithLockedSampleInstanceSetup(ctx, workspaceID, func(callbackCtx context.Context, tx *store.SampleInstanceSetupTx, setup *store.SampleInstanceSetupMessage) error {+ payload, err := decode(setup)+ if err != nil {+ return err+ }+ if len(payload.Instances) != 1 || payload.Instances[0].GetProjectId() != projectID {+ return nil+ }+ if setup.ActivatedAt == nil {+ if err := m.reconcile(callbackCtx, workspaceID, payload); err != nil {+ return err+ }+ return tx.DeleteReservation(callbackCtx)+ }+ for _, entry := range payload.Instances {+ m.stopEntry(entry.InstanceId)+ if err := postgres.RemoveEmbeddedInstance(sampleConfig(m.profile, entry).DataDir); err != nil {+ return err+ }+ if _, err := sample.ArchiveMetadata(callbackCtx, m.store, workspaceID, entry.ProjectId, entry.InstanceId); err != nil {+ return err+ }+ }+ return tx.MarkDeleted(callbackCtx, m.clock())+ })+}+// Stop stops managed and legacy embedded sample processes.func (m *Manager) Stop() {m.mu.Lock()diff --git a/backend/component/sample/selfhost/manager_test.go b/backend/component/sample/selfhost/manager_test.goindex d23bca2360..fce86b2dc5 100644--- a/backend/component/sample/selfhost/manager_test.go+++ b/backend/component/sample/selfhost/manager_test.go@@ -2,25 +2,100 @@ package selfhostimport ("bytes"+ "context""path/filepath""testing""github.com/stretchr/testify/require"+ "google.golang.org/protobuf/encoding/protojson""github.com/bytebase/bytebase/backend/component/config"+ "github.com/bytebase/bytebase/backend/component/sample"+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/store")-func TestNewPayloadCreatesTwoShortRandomInstances(t *testing.T) {- payload, err := newPayload(bytes.NewReader([]byte("0123456789abcdef")), "project-a", nil, nil)+func TestCheckAvailableRequiresEmbeddedPostgres(t *testing.T) {+ manager := NewManager(nil, &config.Profile{}, nil, sample.ManagerOptions{})+ require.NoError(t, manager.CheckAvailable(context.Background()))++ manager.profile.PgURL = "postgresql://metadata.example.com/bytebase"+ err := manager.CheckAvailable(context.Background())+ require.Error(t, err)+ require.Equal(t, sample.FailureFailedPrecondition, sample.FailureKindOf(err))+}++func TestNewPayloadCreatesOneProjectScopedInstance(t *testing.T) {+ environmentID := "test"+ payload, err := newPayload(bytes.NewReader([]byte("01234567")), "project-a", &environmentID)require.NoError(t, err)- require.Equal(t, "project-a", payload.DatabaseProjectId)- require.Len(t, payload.Instances, 2)+ require.Len(t, payload.Instances, 1)require.Equal(t, "sample-3031323334353637", payload.Instances[0].InstanceId)- require.Equal(t, "sample-3839616263646566", payload.Instances[1].InstanceId)+ require.NotNil(t, payload.Instances[0].ProjectId)+ require.Equal(t, "project-a", payload.Instances[0].GetProjectId())require.Equal(t, int32(0), payload.Instances[0].PortOffset)- require.Equal(t, int32(1), payload.Instances[1].PortOffset)require.Equal(t, sampleDatabaseTest, payload.Instances[0].DatabaseName)- require.Equal(t, sampleDatabaseProd, payload.Instances[1].DatabaseName)+ require.Equal(t, &environmentID, payload.Instances[0].EnvironmentId)+}++func TestDecodeAcceptsOnlyCurrentPayload(t *testing.T) {+ completeEntry := func(id string) *storepb.SelfHostSampleInstanceSetupPayload_Instance {+ return managedEntry(id, "Sample Instance", 0, sampleDatabaseTest)+ }+ projectID := "project-a"+ currentEntry := completeEntry("sample-one")+ currentEntry.ProjectId = &projectID+ tests := []struct {+ name string+ payload *storepb.SelfHostSampleInstanceSetupPayload+ wantErr bool+ }{+ {+ name: "current",+ payload: &storepb.SelfHostSampleInstanceSetupPayload{+ Instances: []*storepb.SelfHostSampleInstanceSetupPayload_Instance{currentEntry},+ },+ },+ {+ name: "single member without project owner",+ payload: &storepb.SelfHostSampleInstanceSetupPayload{+ Instances: []*storepb.SelfHostSampleInstanceSetupPayload_Instance{completeEntry("sample-one")},+ },+ wantErr: true,+ },+ {+ name: "multiple members",+ payload: &storepb.SelfHostSampleInstanceSetupPayload{+ Instances: []*storepb.SelfHostSampleInstanceSetupPayload_Instance{currentEntry, currentEntry},+ },+ wantErr: true,+ },+ {+ name: "missing members",+ payload: &storepb.SelfHostSampleInstanceSetupPayload{},+ wantErr: true,+ },+ {+ name: "incomplete member",+ payload: &storepb.SelfHostSampleInstanceSetupPayload{+ Instances: []*storepb.SelfHostSampleInstanceSetupPayload_Instance{{InstanceId: "sample-one", ProjectId: &projectID}},+ },+ wantErr: true,+ },+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ encoded, err := protojson.Marshal(test.payload)+ require.NoError(t, err)+ _, err = decode(&store.SampleInstanceSetupMessage{Payload: encoded})+ if test.wantErr {+ require.Error(t, err)+ require.Equal(t, sample.FailureFailedPrecondition, sample.FailureKindOf(err))+ return+ }+ require.NoError(t, err)+ })+ }}func TestSampleConfigUsesManagedDirectoryAndPortOffset(t *testing.T) {diff --git a/backend/component/sample/types.go b/backend/component/sample/types.goindex 2cddfee0f5..fd85f4d479 100644--- a/backend/component/sample/types.go+++ b/backend/component/sample/types.go@@ -12,38 +12,29 @@ import ("github.com/bytebase/bytebase/backend/store")-// SetupRequest identifies the workspace and database-owning project.-type SetupRequest struct {+// PrepareRequest identifies the workspace and owning project.+type PrepareRequest struct {WorkspaceID stringProjectID string}-// SetupResult contains every instance created by the selected implementation.-type SetupResult struct {- Instances []*store.InstanceMessage-}--// InstanceInfo describes one provisioned sample instance.-type InstanceInfo struct {- Instance string+// Instance describes one provisioned sample instance.+type Instance struct {+ Name stringExpireTime *time.Time}-// Info describes availability and provisioned resources for one workspace.-type Info struct {- Available bool- Instances []InstanceInfo-}-// Manager is the lifecycle interface implemented independently by self-host// and SaaS sample managers.type Manager interface {- SetupSample(context.Context, SetupRequest) (*SetupResult, error)- Info(context.Context, string) (*Info, error)+ CheckAvailable(context.Context) error+ PrepareSampleProjectInstance(context.Context, PrepareRequest) (*store.InstanceMessage, error)+ ListInstances(context.Context, string) ([]*Instance, error)Start(context.Context, string) errorCleanup(context.Context) errorValidateInstanceRestore(context.Context, string, string) errorHandleInstanceLifecycle(context.Context, string, string, bool) error+ HandleProjectPurge(context.Context, string, string) errorStop()}diff --git a/backend/generated-go/store/sample_instance.pb.go b/backend/generated-go/store/sample_instance.pb.goindex 2b9650823f..c85f8ee926 100644--- a/backend/generated-go/store/sample_instance.pb.go+++ b/backend/generated-go/store/sample_instance.pb.go@@ -106,11 +106,10 @@ func (x *SaaSSampleInstanceSetupPayload) GetRoleName() string {}type SelfHostSampleInstanceSetupPayload struct {- state protoimpl.MessageState `protogen:"open.v1"`- DatabaseProjectId string `protobuf:"bytes,1,opt,name=database_project_id,json=databaseProjectId,proto3" json:"database_project_id,omitempty"`- Instances []*SelfHostSampleInstanceSetupPayload_Instance `protobuf:"bytes,2,rep,name=instances,proto3" json:"instances,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ state protoimpl.MessageState `protogen:"open.v1"`+ Instances []*SelfHostSampleInstanceSetupPayload_Instance `protobuf:"bytes,1,rep,name=instances,proto3" json:"instances,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *SelfHostSampleInstanceSetupPayload) Reset() {@@ -143,13 +142,6 @@ func (*SelfHostSampleInstanceSetupPayload) Descriptor() ([]byte, []int) {return file_store_sample_instance_proto_rawDescGZIP(), []int{1}}-func (x *SelfHostSampleInstanceSetupPayload) GetDatabaseProjectId() string {- if x != nil {- return x.DatabaseProjectId- }- return ""-}-func (x *SelfHostSampleInstanceSetupPayload) GetInstances() []*SelfHostSampleInstanceSetupPayload_Instance {if x != nil {return x.Instances@@ -165,6 +157,7 @@ type SelfHostSampleInstanceSetupPayload_Instance struct {PortOffset int32 `protobuf:"varint,4,opt,name=port_offset,json=portOffset,proto3" json:"port_offset,omitempty"`DatabaseName string `protobuf:"bytes,5,opt,name=database_name,json=databaseName,proto3" json:"database_name,omitempty"`RoleName string `protobuf:"bytes,6,opt,name=role_name,json=roleName,proto3" json:"role_name,omitempty"`+ ProjectId *string `protobuf:"bytes,7,opt,name=project_id,json=projectId,proto3,oneof" json:"project_id,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}@@ -241,6 +234,13 @@ func (x *SelfHostSampleInstanceSetupPayload_Instance) GetRoleName() string {return ""}+func (x *SelfHostSampleInstanceSetupPayload_Instance) GetProjectId() string {+ if x != nil && x.ProjectId != nil {+ return *x.ProjectId+ }+ return ""+}+var File_store_sample_instance_proto protoreflect.FileDescriptorconst file_store_sample_instance_proto_rawDesc = "" +@@ -255,10 +255,9 @@ const file_store_sample_instance_proto_rawDesc = "" +"\x0eenvironment_id\x18\x04 \x01(\tH\x00R\renvironmentId\x88\x01\x01\x12#\n" +"\rdatabase_name\x18\x05 \x01(\tR\fdatabaseName\x12\x1b\n" +"\trole_name\x18\x06 \x01(\tR\broleNameB\x11\n" +- "\x0f_environment_id\"\x95\x03\n" +- "\"SelfHostSampleInstanceSetupPayload\x12.\n" +- "\x13database_project_id\x18\x01 \x01(\tR\x11databaseProjectId\x12Y\n" +- "\tinstances\x18\x02 \x03(\v2;.bytebase.store.SelfHostSampleInstanceSetupPayload.InstanceR\tinstances\x1a\xe3\x01\n" ++ "\x0f_environment_id\"\x98\x03\n" ++ "\"SelfHostSampleInstanceSetupPayload\x12Y\n" ++ "\tinstances\x18\x01 \x03(\v2;.bytebase.store.SelfHostSampleInstanceSetupPayload.InstanceR\tinstances\x1a\x96\x02\n" +"\bInstance\x12\x1f\n" +"\vinstance_id\x18\x01 \x01(\tR\n" +"instanceId\x12\x14\n" +@@ -267,8 +266,11 @@ const file_store_sample_instance_proto_rawDesc = "" +"\vport_offset\x18\x04 \x01(\x05R\n" +"portOffset\x12#\n" +"\rdatabase_name\x18\x05 \x01(\tR\fdatabaseName\x12\x1b\n" +- "\trole_name\x18\x06 \x01(\tR\broleNameB\x11\n" +- "\x0f_environment_idB\x96\x01\n" ++ "\trole_name\x18\x06 \x01(\tR\broleName\x12\"\n" ++ "\n" ++ "project_id\x18\a \x01(\tH\x01R\tprojectId\x88\x01\x01B\x11\n" ++ "\x0f_environment_idB\r\n" ++ "\v_project_idB\x96\x01\n" +"\x12com.bytebase.storeB\x13SampleInstanceProtoP\x01Z\x12generated-go/store\xa2\x02\x03BSX\xaa\x02\x0eBytebase.Store\xca\x02\x0eBytebase\\Store\xe2\x02\x1aBytebase\\Store\\GPBMetadata\xea\x02\x0fBytebase::Storeb\x06proto3"var (diff --git a/backend/generated-go/store/sample_instance_equal.pb.go b/backend/generated-go/store/sample_instance_equal.pb.goindex 41292b3e3a..098cf7c9f9 100644--- a/backend/generated-go/store/sample_instance_equal.pb.go+++ b/backend/generated-go/store/sample_instance_equal.pb.go@@ -56,6 +56,9 @@ func (x *SelfHostSampleInstanceSetupPayload_Instance) Equal(y *SelfHostSampleInsif x.RoleName != y.RoleName {return false}+ if p, q := x.ProjectId, y.ProjectId; (p == nil && q != nil) || (p != nil && (q == nil || *p != *q)) {+ return false+ }return true}@@ -66,9 +69,6 @@ func (x *SelfHostSampleInstanceSetupPayload) Equal(y *SelfHostSampleInstanceSetuif x == nil || y == nil {return x == nil && y == nil}- if x.DatabaseProjectId != y.DatabaseProjectId {- return false- }if len(x.Instances) != len(y.Instances) {return false}diff --git a/backend/generated-go/v1/actuator_service.pb.go b/backend/generated-go/v1/actuator_service.pb.goindex c3534f4480..0389ec1662 100644--- a/backend/generated-go/v1/actuator_service.pb.go+++ b/backend/generated-go/v1/actuator_service.pb.go@@ -10,7 +10,6 @@ import (_ "google.golang.org/genproto/googleapis/api/annotations"protoreflect "google.golang.org/protobuf/reflect/protoreflect"protoimpl "google.golang.org/protobuf/runtime/protoimpl"- emptypb "google.golang.org/protobuf/types/known/emptypb"timestamppb "google.golang.org/protobuf/types/known/timestamppb"reflect "reflect"sync "sync"@@ -24,43 +23,6 @@ const (_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20))-// Request message for setting up sample data.-type SetupSampleRequest struct {- state protoimpl.MessageState `protogen:"open.v1"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache-}--func (x *SetupSampleRequest) Reset() {- *x = SetupSampleRequest{}- mi := &file_v1_actuator_service_proto_msgTypes[0]- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- ms.StoreMessageInfo(mi)-}--func (x *SetupSampleRequest) String() string {- return protoimpl.X.MessageStringOf(x)-}--func (*SetupSampleRequest) ProtoMessage() {}--func (x *SetupSampleRequest) ProtoReflect() protoreflect.Message {- mi := &file_v1_actuator_service_proto_msgTypes[0]- if x != nil {- ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))- if ms.LoadMessageInfo() == nil {- ms.StoreMessageInfo(mi)- }- return ms- }- return mi.MessageOf(x)-}--// Deprecated: Use SetupSampleRequest.ProtoReflect.Descriptor instead.-func (*SetupSampleRequest) Descriptor() ([]byte, []int) {- return file_v1_actuator_service_proto_rawDescGZIP(), []int{0}-}-// Request message for getting actuator information.type GetActuatorInfoRequest struct {state protoimpl.MessageState `protogen:"open.v1"`@@ -70,7 +32,7 @@ type GetActuatorInfoRequest struct {func (x *GetActuatorInfoRequest) Reset() {*x = GetActuatorInfoRequest{}- mi := &file_v1_actuator_service_proto_msgTypes[1]+ mi := &file_v1_actuator_service_proto_msgTypes[0]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -82,7 +44,7 @@ func (x *GetActuatorInfoRequest) String() string {func (*GetActuatorInfoRequest) ProtoMessage() {}func (x *GetActuatorInfoRequest) ProtoReflect() protoreflect.Message {- mi := &file_v1_actuator_service_proto_msgTypes[1]+ mi := &file_v1_actuator_service_proto_msgTypes[0]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -95,7 +57,7 @@ func (x *GetActuatorInfoRequest) ProtoReflect() protoreflect.Message {// Deprecated: Use GetActuatorInfoRequest.ProtoReflect.Descriptor instead.func (*GetActuatorInfoRequest) Descriptor() ([]byte, []int) {- return file_v1_actuator_service_proto_rawDescGZIP(), []int{1}+ return file_v1_actuator_service_proto_rawDescGZIP(), []int{0}}// SampleInfo describes sample setup availability and provisioned resources.@@ -111,7 +73,7 @@ type SampleInfo struct {func (x *SampleInfo) Reset() {*x = SampleInfo{}- mi := &file_v1_actuator_service_proto_msgTypes[2]+ mi := &file_v1_actuator_service_proto_msgTypes[1]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -123,7 +85,7 @@ func (x *SampleInfo) String() string {func (*SampleInfo) ProtoMessage() {}func (x *SampleInfo) ProtoReflect() protoreflect.Message {- mi := &file_v1_actuator_service_proto_msgTypes[2]+ mi := &file_v1_actuator_service_proto_msgTypes[1]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -136,7 +98,7 @@ func (x *SampleInfo) ProtoReflect() protoreflect.Message {// Deprecated: Use SampleInfo.ProtoReflect.Descriptor instead.func (*SampleInfo) Descriptor() ([]byte, []int) {- return file_v1_actuator_service_proto_rawDescGZIP(), []int{2}+ return file_v1_actuator_service_proto_rawDescGZIP(), []int{1}}func (x *SampleInfo) GetAvailable() bool {@@ -195,7 +157,7 @@ type ActuatorInfo struct {func (x *ActuatorInfo) Reset() {*x = ActuatorInfo{}- mi := &file_v1_actuator_service_proto_msgTypes[3]+ mi := &file_v1_actuator_service_proto_msgTypes[2]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -207,7 +169,7 @@ func (x *ActuatorInfo) String() string {func (*ActuatorInfo) ProtoMessage() {}func (x *ActuatorInfo) ProtoReflect() protoreflect.Message {- mi := &file_v1_actuator_service_proto_msgTypes[3]+ mi := &file_v1_actuator_service_proto_msgTypes[2]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -220,7 +182,7 @@ func (x *ActuatorInfo) ProtoReflect() protoreflect.Message {// Deprecated: Use ActuatorInfo.ProtoReflect.Descriptor instead.func (*ActuatorInfo) Descriptor() ([]byte, []int) {- return file_v1_actuator_service_proto_rawDescGZIP(), []int{3}+ return file_v1_actuator_service_proto_rawDescGZIP(), []int{2}}func (x *ActuatorInfo) GetVersion() string {@@ -342,7 +304,7 @@ type SampleInfo_Instance struct {func (x *SampleInfo_Instance) Reset() {*x = SampleInfo_Instance{}- mi := &file_v1_actuator_service_proto_msgTypes[4]+ mi := &file_v1_actuator_service_proto_msgTypes[3]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -354,7 +316,7 @@ func (x *SampleInfo_Instance) String() string {func (*SampleInfo_Instance) ProtoMessage() {}func (x *SampleInfo_Instance) ProtoReflect() protoreflect.Message {- mi := &file_v1_actuator_service_proto_msgTypes[4]+ mi := &file_v1_actuator_service_proto_msgTypes[3]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -367,7 +329,7 @@ func (x *SampleInfo_Instance) ProtoReflect() protoreflect.Message {// Deprecated: Use SampleInfo_Instance.ProtoReflect.Descriptor instead.func (*SampleInfo_Instance) Descriptor() ([]byte, []int) {- return file_v1_actuator_service_proto_rawDescGZIP(), []int{2, 0}+ return file_v1_actuator_service_proto_rawDescGZIP(), []int{1, 0}}func (x *SampleInfo_Instance) GetInstance() string {@@ -388,8 +350,7 @@ var File_v1_actuator_service_proto protoreflect.FileDescriptorconst file_v1_actuator_service_proto_rawDesc = "" +"\n" +- "\x19v1/actuator_service.proto\x12\vbytebase.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x13v1/annotation.proto\"\x14\n" +- "\x12SetupSampleRequest\"\x18\n" ++ "\x19v1/actuator_service.proto\x12\vbytebase.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x13v1/annotation.proto\"\x18\n" +"\x16GetActuatorInfoRequest\"\xfe\x01\n" +"\n" +"SampleInfo\x12!\n" +@@ -418,10 +379,9 @@ const file_v1_actuator_service_proto_rawDesc = "" +"\x15active_vcs_user_count\x18\x1c \x01(\x05B\x03\xe0A\x03R\x12activeVcsUserCount\x124\n" +"\x06sample\x18\x1d \x01(\v2\x17.bytebase.v1.SampleInfoB\x03\xe0A\x03R\x06sampleJ\x04\b\x03\x10\x04J\x04\b\x05\x10\bJ\x04\b\t\x10\n" +"J\x04\b\n" +- "\x10\vJ\x04\b\f\x10\rJ\x04\b\x0e\x10\x0fJ\x04\b\x10\x10\x14J\x04\b\x16\x10\x17J\x04\b\x19\x10\x1a2\x97\x02\n" ++ "\x10\vJ\x04\b\f\x10\rJ\x04\b\x0e\x10\x0fJ\x04\b\x10\x10\x14J\x04\b\x16\x10\x17J\x04\b\x19\x10\x1a2\x86\x01\n" +"\x0fActuatorService\x12s\n" +- "\x0fGetActuatorInfo\x12#.bytebase.v1.GetActuatorInfoRequest\x1a\x19.bytebase.v1.ActuatorInfo\" \xdaA\x00\xa0\xea0\x01\x82\xd3\xe4\x93\x02\x13\x12\x11/v1/actuator/info\x12\x8e\x01\n" +- "\vSetupSample\x12\x1f.bytebase.v1.SetupSampleRequest\x1a\x16.google.protobuf.Empty\"F\x8a\xea0\x12bb.projects.create\x90\xea0\x01\x98\xea0\x01\xa0\xea0\x04\xa8\xea0\t\x82\xd3\xe4\x93\x02\x1a\"\x18/v1/actuator:setupSampleB\xaa\x01\n" ++ "\x0fGetActuatorInfo\x12#.bytebase.v1.GetActuatorInfoRequest\x1a\x19.bytebase.v1.ActuatorInfo\" \xdaA\x00\xa0\xea0\x01\x82\xd3\xe4\x93\x02\x13\x12\x11/v1/actuator/infoB\xaa\x01\n" +"\x0fcom.bytebase.v1B\x14ActuatorServiceProtoP\x01Z4github.com/bytebase/bytebase/backend/generated-go/v1\xa2\x02\x03BXX\xaa\x02\vBytebase.V1\xca\x02\vBytebase\\V1\xe2\x02\x17Bytebase\\V1\\GPBMetadata\xea\x02\fBytebase::V1b\x06proto3"var (@@ -436,27 +396,23 @@ func file_v1_actuator_service_proto_rawDescGZIP() []byte {return file_v1_actuator_service_proto_rawDescData}-var file_v1_actuator_service_proto_msgTypes = make([]protoimpl.MessageInfo, 5)+var file_v1_actuator_service_proto_msgTypes = make([]protoimpl.MessageInfo, 4)var file_v1_actuator_service_proto_goTypes = []any{- (*SetupSampleRequest)(nil), // 0: bytebase.v1.SetupSampleRequest- (*GetActuatorInfoRequest)(nil), // 1: bytebase.v1.GetActuatorInfoRequest- (*SampleInfo)(nil), // 2: bytebase.v1.SampleInfo- (*ActuatorInfo)(nil), // 3: bytebase.v1.ActuatorInfo- (*SampleInfo_Instance)(nil), // 4: bytebase.v1.SampleInfo.Instance- (*timestamppb.Timestamp)(nil), // 5: google.protobuf.Timestamp- (*emptypb.Empty)(nil), // 6: google.protobuf.Empty+ (*GetActuatorInfoRequest)(nil), // 0: bytebase.v1.GetActuatorInfoRequest+ (*SampleInfo)(nil), // 1: bytebase.v1.SampleInfo+ (*ActuatorInfo)(nil), // 2: bytebase.v1.ActuatorInfo+ (*SampleInfo_Instance)(nil), // 3: bytebase.v1.SampleInfo.Instance+ (*timestamppb.Timestamp)(nil), // 4: google.protobuf.Timestamp}var file_v1_actuator_service_proto_depIdxs = []int32{- 4, // 0: bytebase.v1.SampleInfo.instances:type_name -> bytebase.v1.SampleInfo.Instance- 5, // 1: bytebase.v1.ActuatorInfo.last_active_time:type_name -> google.protobuf.Timestamp- 2, // 2: bytebase.v1.ActuatorInfo.sample:type_name -> bytebase.v1.SampleInfo- 5, // 3: bytebase.v1.SampleInfo.Instance.expire_time:type_name -> google.protobuf.Timestamp- 1, // 4: bytebase.v1.ActuatorService.GetActuatorInfo:input_type -> bytebase.v1.GetActuatorInfoRequest- 0, // 5: bytebase.v1.ActuatorService.SetupSample:input_type -> bytebase.v1.SetupSampleRequest- 3, // 6: bytebase.v1.ActuatorService.GetActuatorInfo:output_type -> bytebase.v1.ActuatorInfo- 6, // 7: bytebase.v1.ActuatorService.SetupSample:output_type -> google.protobuf.Empty- 6, // [6:8] is the sub-list for method output_type- 4, // [4:6] is the sub-list for method input_type+ 3, // 0: bytebase.v1.SampleInfo.instances:type_name -> bytebase.v1.SampleInfo.Instance+ 4, // 1: bytebase.v1.ActuatorInfo.last_active_time:type_name -> google.protobuf.Timestamp+ 1, // 2: bytebase.v1.ActuatorInfo.sample:type_name -> bytebase.v1.SampleInfo+ 4, // 3: bytebase.v1.SampleInfo.Instance.expire_time:type_name -> google.protobuf.Timestamp+ 0, // 4: bytebase.v1.ActuatorService.GetActuatorInfo:input_type -> bytebase.v1.GetActuatorInfoRequest+ 2, // 5: bytebase.v1.ActuatorService.GetActuatorInfo:output_type -> bytebase.v1.ActuatorInfo+ 5, // [5:6] is the sub-list for method output_type+ 4, // [4:5] is the sub-list for method input_type4, // [4:4] is the sub-list for extension type_name4, // [4:4] is the sub-list for extension extendee0, // [0:4] is the sub-list for field type_name@@ -474,7 +430,7 @@ func file_v1_actuator_service_proto_init() {GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_v1_actuator_service_proto_rawDesc), len(file_v1_actuator_service_proto_rawDesc)),NumEnums: 0,- NumMessages: 5,+ NumMessages: 4,NumExtensions: 0,NumServices: 1,},diff --git a/backend/generated-go/v1/actuator_service.pb.gw.go b/backend/generated-go/v1/actuator_service.pb.gw.goindex 1bae2ff21a..fb56cfd049 100644--- a/backend/generated-go/v1/actuator_service.pb.gw.go+++ b/backend/generated-go/v1/actuator_service.pb.gw.go@@ -56,27 +56,6 @@ func local_request_ActuatorService_GetActuatorInfo_0(ctx context.Context, marshareturn msg, metadata, err}-func request_ActuatorService_SetupSample_0(ctx context.Context, marshaler runtime.Marshaler, client ActuatorServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {- var (- protoReq SetupSampleRequest- metadata runtime.ServerMetadata- )- if req.Body != nil {- _, _ = io.Copy(io.Discard, req.Body)- }- msg, err := client.SetupSample(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))- return msg, metadata, err-}--func local_request_ActuatorService_SetupSample_0(ctx context.Context, marshaler runtime.Marshaler, server ActuatorServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {- var (- protoReq SetupSampleRequest- metadata runtime.ServerMetadata- )- msg, err := server.SetupSample(ctx, &protoReq)- return msg, metadata, err-}-// RegisterActuatorServiceHandlerServer registers the http handlers for service ActuatorService to "mux".// UnaryRPC :call ActuatorServiceServer directly.// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.@@ -103,26 +82,6 @@ func RegisterActuatorServiceHandlerServer(ctx context.Context, mux *runtime.Serv}forward_ActuatorService_GetActuatorInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)})- mux.Handle(http.MethodPost, pattern_ActuatorService_SetupSample_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {- ctx, cancel := context.WithCancel(req.Context())- defer cancel()- var stream runtime.ServerTransportStream- ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)- inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)- annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/bytebase.v1.ActuatorService/SetupSample", runtime.WithHTTPPathPattern("/v1/actuator:setupSample"))- if err != nil {- runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)- return- }- resp, md, err := local_request_ActuatorService_SetupSample_0(annotatedContext, inboundMarshaler, server, req, pathParams)- md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())- annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)- if err != nil {- runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)- return- }- forward_ActuatorService_SetupSample_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)- })return nil}@@ -180,32 +139,13 @@ func RegisterActuatorServiceHandlerClient(ctx context.Context, mux *runtime.Serv}forward_ActuatorService_GetActuatorInfo_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)})- mux.Handle(http.MethodPost, pattern_ActuatorService_SetupSample_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {- ctx, cancel := context.WithCancel(req.Context())- defer cancel()- inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)- annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/bytebase.v1.ActuatorService/SetupSample", runtime.WithHTTPPathPattern("/v1/actuator:setupSample"))- if err != nil {- runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)- return- }- resp, md, err := request_ActuatorService_SetupSample_0(annotatedContext, inboundMarshaler, client, req, pathParams)- annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)- if err != nil {- runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)- return- }- forward_ActuatorService_SetupSample_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)- })return nil}var (pattern_ActuatorService_GetActuatorInfo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "actuator", "info"}, ""))- pattern_ActuatorService_SetupSample_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "actuator"}, "setupSample")))var (forward_ActuatorService_GetActuatorInfo_0 = runtime.ForwardResponseMessage- forward_ActuatorService_SetupSample_0 = runtime.ForwardResponseMessage)diff --git a/backend/generated-go/v1/actuator_service_equal.pb.go b/backend/generated-go/v1/actuator_service_equal.pb.goindex 8aa2c572ca..0c50a01679 100644--- a/backend/generated-go/v1/actuator_service_equal.pb.go+++ b/backend/generated-go/v1/actuator_service_equal.pb.go@@ -3,16 +3,6 @@package v1-func (x *SetupSampleRequest) Equal(y *SetupSampleRequest) bool {- if x == y {- return true- }- if x == nil || y == nil {- return x == nil && y == nil- }- return true-}-func (x *GetActuatorInfoRequest) Equal(y *GetActuatorInfoRequest) bool {if x == y {return truediff --git a/backend/generated-go/v1/actuator_service_grpc.pb.go b/backend/generated-go/v1/actuator_service_grpc.pb.goindex 6feede96ae..52eebcf935 100644--- a/backend/generated-go/v1/actuator_service_grpc.pb.go+++ b/backend/generated-go/v1/actuator_service_grpc.pb.go@@ -11,7 +11,6 @@ import (grpc "google.golang.org/grpc"codes "google.golang.org/grpc/codes"status "google.golang.org/grpc/status"- emptypb "google.golang.org/protobuf/types/known/emptypb")// This is a compile-time assertion to ensure that this generated file@@ -21,7 +20,6 @@ const _ = grpc.SupportPackageIsVersion9const (ActuatorService_GetActuatorInfo_FullMethodName = "/bytebase.v1.ActuatorService/GetActuatorInfo"- ActuatorService_SetupSample_FullMethodName = "/bytebase.v1.ActuatorService/SetupSample")// ActuatorServiceClient is the client API for ActuatorService service.@@ -34,9 +32,6 @@ type ActuatorServiceClient interface {// The workspace is resolved from the authenticated session.// Permissions required: None (authentication required)GetActuatorInfo(ctx context.Context, in *GetActuatorInfoRequest, opts ...grpc.CallOption) (*ActuatorInfo, error)- // Sets up sample data for demonstration and testing purposes.- // Permissions required: bb.projects.create- SetupSample(ctx context.Context, in *SetupSampleRequest, opts ...grpc.CallOption) (*emptypb.Empty, error)}type actuatorServiceClient struct {@@ -57,16 +52,6 @@ func (c *actuatorServiceClient) GetActuatorInfo(ctx context.Context, in *GetActureturn out, nil}-func (c *actuatorServiceClient) SetupSample(ctx context.Context, in *SetupSampleRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) {- cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)- out := new(emptypb.Empty)- err := c.cc.Invoke(ctx, ActuatorService_SetupSample_FullMethodName, in, out, cOpts...)- if err != nil {- return nil, err- }- return out, nil-}-// ActuatorServiceServer is the server API for ActuatorService service.// All implementations must embed UnimplementedActuatorServiceServer// for forward compatibility.@@ -77,9 +62,6 @@ type ActuatorServiceServer interface {// The workspace is resolved from the authenticated session.// Permissions required: None (authentication required)GetActuatorInfo(context.Context, *GetActuatorInfoRequest) (*ActuatorInfo, error)- // Sets up sample data for demonstration and testing purposes.- // Permissions required: bb.projects.create- SetupSample(context.Context, *SetupSampleRequest) (*emptypb.Empty, error)mustEmbedUnimplementedActuatorServiceServer()}@@ -93,9 +75,6 @@ type UnimplementedActuatorServiceServer struct{}func (UnimplementedActuatorServiceServer) GetActuatorInfo(context.Context, *GetActuatorInfoRequest) (*ActuatorInfo, error) {return nil, status.Error(codes.Unimplemented, "method GetActuatorInfo not implemented")}-func (UnimplementedActuatorServiceServer) SetupSample(context.Context, *SetupSampleRequest) (*emptypb.Empty, error) {- return nil, status.Error(codes.Unimplemented, "method SetupSample not implemented")-}func (UnimplementedActuatorServiceServer) mustEmbedUnimplementedActuatorServiceServer() {}func (UnimplementedActuatorServiceServer) testEmbeddedByValue() {}@@ -135,24 +114,6 @@ func _ActuatorService_GetActuatorInfo_Handler(srv interface{}, ctx context.Contereturn interceptor(ctx, in, info, handler)}-func _ActuatorService_SetupSample_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {- in := new(SetupSampleRequest)- if err := dec(in); err != nil {- return nil, err- }- if interceptor == nil {- return srv.(ActuatorServiceServer).SetupSample(ctx, in)- }- info := &grpc.UnaryServerInfo{- Server: srv,- FullMethod: ActuatorService_SetupSample_FullMethodName,- }- handler := func(ctx context.Context, req interface{}) (interface{}, error) {- return srv.(ActuatorServiceServer).SetupSample(ctx, req.(*SetupSampleRequest))- }- return interceptor(ctx, in, info, handler)-}-// ActuatorService_ServiceDesc is the grpc.ServiceDesc for ActuatorService service.// It's only intended for direct use with grpc.RegisterService,// and not to be introspected or modified (even as a copy)@@ -164,10 +125,6 @@ var ActuatorService_ServiceDesc = grpc.ServiceDesc{MethodName: "GetActuatorInfo",Handler: _ActuatorService_GetActuatorInfo_Handler,},- {- MethodName: "SetupSample",- Handler: _ActuatorService_SetupSample_Handler,- },},Streams: []grpc.StreamDesc{},Metadata: "v1/actuator_service.proto",diff --git a/backend/generated-go/v1/v1connect/actuator_service.connect.go b/backend/generated-go/v1/v1connect/actuator_service.connect.goindex bf924bce8e..1298f6c275 100644--- a/backend/generated-go/v1/v1connect/actuator_service.connect.go+++ b/backend/generated-go/v1/v1connect/actuator_service.connect.go@@ -9,7 +9,6 @@ import (context "context"errors "errors"v1 "github.com/bytebase/bytebase/backend/generated-go/v1"- emptypb "google.golang.org/protobuf/types/known/emptypb"http "net/http"strings "strings")@@ -37,9 +36,6 @@ const (// ActuatorServiceGetActuatorInfoProcedure is the fully-qualified name of the ActuatorService's// GetActuatorInfo RPC.ActuatorServiceGetActuatorInfoProcedure = "/bytebase.v1.ActuatorService/GetActuatorInfo"- // ActuatorServiceSetupSampleProcedure is the fully-qualified name of the ActuatorService's- // SetupSample RPC.- ActuatorServiceSetupSampleProcedure = "/bytebase.v1.ActuatorService/SetupSample")// ActuatorServiceClient is a client for the bytebase.v1.ActuatorService service.@@ -48,9 +44,6 @@ type ActuatorServiceClient interface {// The workspace is resolved from the authenticated session.// Permissions required: None (authentication required)GetActuatorInfo(context.Context, *connect.Request[v1.GetActuatorInfoRequest]) (*connect.Response[v1.ActuatorInfo], error)- // Sets up sample data for demonstration and testing purposes.- // Permissions required: bb.projects.create- SetupSample(context.Context, *connect.Request[v1.SetupSampleRequest]) (*connect.Response[emptypb.Empty], error)}// NewActuatorServiceClient constructs a client for the bytebase.v1.ActuatorService service. By@@ -70,19 +63,12 @@ func NewActuatorServiceClient(httpClient connect.HTTPClient, baseURL string, optconnect.WithSchema(actuatorServiceMethods.ByName("GetActuatorInfo")),connect.WithClientOptions(opts...),),- setupSample: connect.NewClient[v1.SetupSampleRequest, emptypb.Empty](- httpClient,- baseURL+ActuatorServiceSetupSampleProcedure,- connect.WithSchema(actuatorServiceMethods.ByName("SetupSample")),- connect.WithClientOptions(opts...),- ),}}// actuatorServiceClient implements ActuatorServiceClient.type actuatorServiceClient struct {getActuatorInfo *connect.Client[v1.GetActuatorInfoRequest, v1.ActuatorInfo]- setupSample *connect.Client[v1.SetupSampleRequest, emptypb.Empty]}// GetActuatorInfo calls bytebase.v1.ActuatorService.GetActuatorInfo.@@ -90,20 +76,12 @@ func (c *actuatorServiceClient) GetActuatorInfo(ctx context.Context, req *connecreturn c.getActuatorInfo.CallUnary(ctx, req)}-// SetupSample calls bytebase.v1.ActuatorService.SetupSample.-func (c *actuatorServiceClient) SetupSample(ctx context.Context, req *connect.Request[v1.SetupSampleRequest]) (*connect.Response[emptypb.Empty], error) {- return c.setupSample.CallUnary(ctx, req)-}-// ActuatorServiceHandler is an implementation of the bytebase.v1.ActuatorService service.type ActuatorServiceHandler interface {// Gets system information and health status of the Bytebase instance.// The workspace is resolved from the authenticated session.// Permissions required: None (authentication required)GetActuatorInfo(context.Context, *connect.Request[v1.GetActuatorInfoRequest]) (*connect.Response[v1.ActuatorInfo], error)- // Sets up sample data for demonstration and testing purposes.- // Permissions required: bb.projects.create- SetupSample(context.Context, *connect.Request[v1.SetupSampleRequest]) (*connect.Response[emptypb.Empty], error)}// NewActuatorServiceHandler builds an HTTP handler from the service implementation. It returns the@@ -119,18 +97,10 @@ func NewActuatorServiceHandler(svc ActuatorServiceHandler, opts ...connect.Handlconnect.WithSchema(actuatorServiceMethods.ByName("GetActuatorInfo")),connect.WithHandlerOptions(opts...),)- actuatorServiceSetupSampleHandler := connect.NewUnaryHandler(- ActuatorServiceSetupSampleProcedure,- svc.SetupSample,- connect.WithSchema(actuatorServiceMethods.ByName("SetupSample")),- connect.WithHandlerOptions(opts...),- )return "/bytebase.v1.ActuatorService/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {switch r.URL.Path {case ActuatorServiceGetActuatorInfoProcedure:actuatorServiceGetActuatorInfoHandler.ServeHTTP(w, r)- case ActuatorServiceSetupSampleProcedure:- actuatorServiceSetupSampleHandler.ServeHTTP(w, r)default:http.NotFound(w, r)}@@ -143,7 +113,3 @@ type UnimplementedActuatorServiceHandler struct{}func (UnimplementedActuatorServiceHandler) GetActuatorInfo(context.Context, *connect.Request[v1.GetActuatorInfoRequest]) (*connect.Response[v1.ActuatorInfo], error) {return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.ActuatorService.GetActuatorInfo is not implemented"))}--func (UnimplementedActuatorServiceHandler) SetupSample(context.Context, *connect.Request[v1.SetupSampleRequest]) (*connect.Response[emptypb.Empty], error) {- return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.ActuatorService.SetupSample is not implemented"))-}diff --git a/backend/server/grpc_routes.go b/backend/server/grpc_routes.goindex dc12606b8b..c9e594e7b0 100644--- a/backend/server/grpc_routes.go+++ b/backend/server/grpc_routes.go@@ -107,7 +107,7 @@ func configureGrpcRouters(issueService := apiv1.NewIssueService(stores, webhookManager, bus, licenseService, iamManager)orgPolicyService := apiv1.NewOrgPolicyService(stores, licenseService, iamManager)planService := apiv1.NewPlanService(stores, bus, iamManager, webhookManager, licenseService)- projectService := apiv1.NewProjectService(stores, profile, iamManager)+ projectService := apiv1.NewProjectService(stores, profile, iamManager, sampleManager)queryHistoryService := apiv1.NewQueryHistoryService(stores)releaseService := apiv1.NewReleaseService(stores, sheetManager, dbFactory, licenseService)reviewConfigService := apiv1.NewReviewConfigService(stores)diff --git a/backend/server/server.go b/backend/server/server.goindex 767d609e64..e89abecea0 100644--- a/backend/server/server.go+++ b/backend/server/server.go@@ -291,8 +291,8 @@ func configureSampleManager(slog.Warn("invalid SAMPLE_PROJECT_INSTANCE_PG_URL; Sample Project Instance is disabled", log.BBError(err))return nil}- if !manager.Available(ctx) {- slog.Warn("Sample Project Instance target is temporarily unavailable")+ if err := manager.CheckAvailable(ctx); err != nil {+ slog.Warn("Sample Project Instance target is temporarily unavailable", log.BBError(err))}return manager}diff --git a/backend/store/sample_instance.go b/backend/store/sample_instance.goindex b456fb7b8e..8395fe9ebe 100644--- a/backend/store/sample_instance.go+++ b/backend/store/sample_instance.go@@ -43,6 +43,34 @@ func (s *Store) GetSampleInstanceSetup(ctx context.Context, workspaceID string)return getSampleInstanceSetup(ctx, s.GetDB(), workspaceID)}+// WithLockedSampleInstanceSetup locks one undeleted setup for a lifecycle+// operation and invokes callback in the same transaction.+func (s *Store) WithLockedSampleInstanceSetup(ctx context.Context, workspaceID string, callback func(context.Context, *SampleInstanceSetupTx, *SampleInstanceSetupMessage) error) error {+ tx, err := s.GetDB().BeginTx(ctx, nil)+ if err != nil {+ return errors.Wrap(err, "failed to begin sample instance setup lifecycle")+ }+ defer tx.Rollback()++ setup, err := scanSampleInstanceSetup(tx.QueryRowContext(ctx, `+ SELECT workspace, replica_id, payload, created_at, updated_at,+ activated_at, expires_at, deleted_at+ FROM sample_instance_setup+ WHERE workspace = $1 AND deleted_at IS NULL+ FOR UPDATE+ `, workspaceID))+ if errors.Is(err, sql.ErrNoRows) {+ return errors.Wrap(tx.Commit(), "failed to commit empty sample instance setup lifecycle")+ }+ if err != nil {+ return errors.Wrap(err, "failed to lock sample instance setup lifecycle")+ }+ if err := callback(ctx, &SampleInstanceSetupTx{tx: tx, workspace: workspaceID, replica: setup.ReplicaID}, setup); err != nil {+ return err+ }+ return errors.Wrap(tx.Commit(), "failed to commit sample instance setup lifecycle")+}+// ReserveSampleInstanceSetup atomically consumes a workspace's setup// entitlement and persists the complete implementation payload.func (s *Store) ReserveSampleInstanceSetup(ctx context.Context, create *SampleInstanceSetupMessage) (*SampleInstanceSetupMessage, bool, error) {diff --git a/backend/store/workspace_test.go b/backend/store/workspace_test.goindex 84eb1ea03f..359bd3b410 100644--- a/backend/store/workspace_test.go+++ b/backend/store/workspace_test.go@@ -19,6 +19,64 @@ import (_ "github.com/bytebase/bytebase/backend/plugin/db/pg")+func TestCreateWorkspaceInitializesDefaults(t *testing.T) {+ ctx := context.Background()+ container := testcontainer.GetTestPgContainer(ctx, t)+ t.Cleanup(func() { container.Close(ctx) })+ db := container.GetDB()+ require.NoError(t, migrator.MigrateSchema(ctx, db))++ pgURL := fmt.Sprintf(+ "host=%s port=%s user=postgres password=root-password database=postgres",+ container.GetHost(), container.GetPort(),+ )+ stores, err := store.New(ctx, pgURL, false)+ require.NoError(t, err)+ t.Cleanup(func() { require.NoError(t, stores.Close()) })++ const workspaceID = "workspace-defaults"+ _, err = stores.CreateWorkspace(ctx, &store.WorkspaceMessage{+ ResourceID: workspaceID,+ AdditionalSettings: []store.AdditionalSetting{{+ Name: storepb.SettingName_AI,+ Payload: &storepb.AISetting{},+ }},+ }, "[email protected]")+ require.NoError(t, err)++ settings, err := stores.ListSettings(ctx, &store.FindSettingMessage{Workspace: workspaceID})+ require.NoError(t, err)+ var names []storepb.SettingName+ for _, setting := range settings {+ names = append(names, setting.Name)+ }+ for _, name := range []storepb.SettingName{+ storepb.SettingName_SYSTEM,+ storepb.SettingName_APP_IM,+ storepb.SettingName_DATA_CLASSIFICATION,+ storepb.SettingName_WORKSPACE_APPROVAL,+ storepb.SettingName_WORKSPACE_PROFILE,+ storepb.SettingName_ENVIRONMENT,+ storepb.SettingName_AI,+ } {+ require.Truef(t, slices.Contains(names, name), "missing setting %s", name)+ }++ environmentSetting, err := stores.GetSetting(ctx, workspaceID, storepb.SettingName_ENVIRONMENT)+ require.NoError(t, err)+ environments, ok := environmentSetting.Value.(*storepb.EnvironmentSetting)+ require.True(t, ok)+ require.Equal(t, []string{common.DefaultTestEnvironmentID, common.DefaultProdEnvironmentID}, []string{+ environments.Environments[0].Id,+ environments.Environments[1].Id,+ })++ defaultProjectID := common.DefaultProjectID(workspaceID)+ project, err := stores.GetProject(ctx, &store.FindProjectMessage{Workspace: workspaceID, ResourceID: &defaultProjectID})+ require.NoError(t, err)+ require.NotNil(t, project)+}+func TestListWorkspacesByEmailEvaluatesBindingConditions(t *testing.T) {ctx := context.Background()container := testcontainer.GetTestPgContainer(ctx, t)diff --git a/frontend/scripts/ui-guideline-legacy-debt.json b/frontend/scripts/ui-guideline-legacy-debt.jsonindex 00e485a8e7..488e8662e6 100644--- a/frontend/scripts/ui-guideline-legacy-debt.json+++ b/frontend/scripts/ui-guideline-legacy-debt.json@@ -1860,12 +1860,6 @@"token": "bg-white","count": 1},- {- "path": "src/routes/auth/SetupPage.tsx",- "rule": "no-raw-color",- "token": "bg-white",- "count": 1- },{"path": "src/routes/auth/SigninPage.tsx","rule": "no-raw-color",diff --git a/frontend/src/app/analytics/RouteBehaviorRecorder.test.tsx b/frontend/src/app/analytics/RouteBehaviorRecorder.test.tsxindex e90414ada4..7fd65c1aac 100644--- a/frontend/src/app/analytics/RouteBehaviorRecorder.test.tsx+++ b/frontend/src/app/analytics/RouteBehaviorRecorder.test.tsx@@ -95,6 +95,7 @@ describe("RouteBehaviorRecorder", () => {disable_session_recording: false,}),properties: {+ deployment: "cloud",git_commit: "abc123",},})diff --git a/frontend/src/app/analytics/RouteBehaviorRecorder.tsx b/frontend/src/app/analytics/RouteBehaviorRecorder.tsxindex f6099ac4e6..b184a31059 100644--- a/frontend/src/app/analytics/RouteBehaviorRecorder.tsx+++ b/frontend/src/app/analytics/RouteBehaviorRecorder.tsx@@ -36,10 +36,18 @@ export function RouteBehaviorRecorder() {return null;}- return <EnabledRouteBehaviorRecorder />;+ return (+ <EnabledRouteBehaviorRecorder+ deployment={isSaaSMode ? "cloud" : "self-host"}+ />+ );}-function EnabledRouteBehaviorRecorder() {+function EnabledRouteBehaviorRecorder({+ deployment,+}: {+ deployment: "cloud" | "self-host";+}) {const route = useCurrentRoute();const currentUserName = useAppStore((state) => state.currentUserName);const workspaceName = useAppStore((state) => state.workspaceResourceName());@@ -51,13 +59,14 @@ function EnabledRouteBehaviorRecorder() {buildBehaviorAnalyticsConfig({posthogKey: import.meta.env.BB_POSTHOG_KEY as string | undefined,posthogHost: import.meta.env.BB_POSTHOG_HOST as string | undefined,+ deployment,gitCommit: import.meta.env.GIT_COMMIT as string | undefined,recordingSampleRate: parseRecordingSampleRate(import.meta.env.BB_POSTHOG_RECORDING_SAMPLE_RATE as string | undefined),resolveRouteId,}),- []+ [deployment]);useEffect(() => {diff --git a/frontend/src/app/analytics/behavior.test.ts b/frontend/src/app/analytics/behavior.test.tsindex dda5ce130f..a9378b5d1e 100644--- a/frontend/src/app/analytics/behavior.test.ts+++ b/frontend/src/app/analytics/behavior.test.ts@@ -12,6 +12,7 @@ describe("behavior analytics config", () => {buildBehaviorAnalyticsConfig({posthogKey: "",posthogHost: "https://us.i.posthog.com",+ deployment: "cloud",recordingSampleRate: 0.1,})).toBeNull();@@ -19,6 +20,7 @@ describe("behavior analytics config", () => {expect(buildBehaviorAnalyticsConfig({posthogKey: "phc_test",+ deployment: "cloud",recordingSampleRate: 0.1,})).toBeNull();@@ -28,6 +30,7 @@ describe("behavior analytics config", () => {const config = buildBehaviorAnalyticsConfig({posthogKey: "phc_test",posthogHost: "https://us.i.posthog.com",+ deployment: "cloud",recordingSampleRate: 0.25,});@@ -72,10 +75,11 @@ describe("behavior analytics config", () => {).toBeUndefined();});- test("adds build commit metadata to PostHog event properties", () => {+ test("adds common metadata to PostHog event properties", () => {const config = buildBehaviorAnalyticsConfig({posthogKey: "phc_test",posthogHost: "https://us.i.posthog.com",+ deployment: "cloud",recordingSampleRate: 0.25,gitCommit: "abc123",resolveRouteId: (url) =>@@ -88,6 +92,7 @@ describe("behavior analytics config", () => {throw new Error("Expected behavior analytics config");}expect(config.properties).toEqual({+ deployment: "cloud",git_commit: "abc123",});@@ -106,6 +111,7 @@ describe("behavior analytics config", () => {"$pageview")).toEqual({+ deployment: "cloud",git_commit: "abc123",route_id: "workspace.project.database",});@@ -116,10 +122,10 @@ describe("behavior analytics routes", () => {test("allows page sessions on any named route", () => {expect(classifyBehaviorRoute({- name: "auth.profile.setup",+ name: "auth.setup",})).toMatchObject({- routeId: "auth.profile.setup",+ routeId: "auth.setup",recording: "allow",});diff --git a/frontend/src/app/analytics/behavior.ts b/frontend/src/app/analytics/behavior.tsindex 2ae6656bb5..43eef50ebf 100644--- a/frontend/src/app/analytics/behavior.ts+++ b/frontend/src/app/analytics/behavior.ts@@ -27,6 +27,8 @@ export type BehaviorMetricName =| "locked feature clicked"| "setup guide action clicked"| "setup guide dismissed"+ | "workspace setup completed"+ | "workspace setup skipped"| "post sync first change clicked"| "post sync sql editor clicked";@@ -47,6 +49,7 @@ export type BehaviorMetricInput = {export function buildBehaviorAnalyticsConfig(params: {posthogKey?: string;posthogHost?: string;+ deployment: "cloud" | "self-host";gitCommit?: string;recordingSampleRate: number;resolveRouteId?: (url: string) => string | undefined;@@ -57,6 +60,7 @@ export function buildBehaviorAnalyticsConfig(params: {return null;}const properties = sanitizeBehaviorProperties({+ deployment: params.deployment,git_commit: params.gitCommit?.trim() || undefined,});diff --git a/frontend/src/app/analytics/provider.test.ts b/frontend/src/app/analytics/provider.test.tsindex a197a0db6a..f11608a4a3 100644--- a/frontend/src/app/analytics/provider.test.ts+++ b/frontend/src/app/analytics/provider.test.ts@@ -24,6 +24,7 @@ const configWithProperties: BehaviorAnalyticsConfig = {apiKey: "phc_test",options: {},properties: {+ deployment: "cloud",git_commit: "abc123",},};@@ -106,6 +107,7 @@ describe("BehaviorAnalytics provider", () => {});expect(client.capture).toHaveBeenCalledWith("connect database clicked", {+ deployment: "cloud",git_commit: "abc123",route_id: "workspace.project.database",});diff --git a/frontend/src/app/router/guard.test.ts b/frontend/src/app/router/guard.test.tsindex 88160855f1..fb1964797f 100644--- a/frontend/src/app/router/guard.test.ts+++ b/frontend/src/app/router/guard.test.ts@@ -164,6 +164,20 @@ describe("rootGuard", () => {expect(handle?.name).toBe(WORKSPACE_ROUTE_404);});+ test("the legacy /setup path is no longer a setup route", () => {+ const matched = matchRoutes(routes, "/setup");+ const leafRoute = matched?.at(-1)?.route;+ const handle = leafRoute?.handle as { name?: string } | undefined;++ expect(handle?.name).toBe(WORKSPACE_ROUTE_404);+ });++ test("matches the unified workspace setup route under /auth", () => {+ const matched = matchRoutes(routes, "/auth/setup");++ expect(matched?.at(-1)?.route.handle).toEqual({ name: "auth.setup" });+ });+test("oauth callback is allowed directly", () => {expect(run(AUTH_OAUTH_CALLBACK_MODULE, "/auth/oauth/callback")).toBeNull();});diff --git a/frontend/src/app/router/guard.ts b/frontend/src/app/router/guard.tsindex e421ea0c05..5a3ccbfe81 100644--- a/frontend/src/app/router/guard.ts+++ b/frontend/src/app/router/guard.ts@@ -14,7 +14,7 @@ import {AUTH_OIDC_CALLBACK_MODULE,AUTH_PASSWORD_FORGOT_MODULE,AUTH_PASSWORD_RESET_MODULE,- AUTH_PROFILE_SETUP_MODULE,+ AUTH_SETUP_MODULE,AUTH_SIGNIN_MODULE,AUTH_SIGNUP_MODULE,DATABASE_ROUTE_DASHBOARD,@@ -23,7 +23,6 @@ import {OAUTH2_CONSENT_MODULE,PROJECT_V1_ROUTE_DASHBOARD,SETTING_ROUTE,- SETUP_MODULE,SQL_EDITOR_HOME_MODULE,WORKSPACE_ROOT_MODULE,WORKSPACE_ROUTE_403,@@ -85,7 +84,6 @@ const ALLOWED_ROUTE_PATTERNS = [PROJECT_V1_ROUTE_DASHBOARD,DATABASE_ROUTE_DASHBOARD,SETTING_ROUTE,- SETUP_MODULE,"workspace","sql-editor",];@@ -102,8 +100,6 @@ const ALLOWED_ROUTE_PATTERNS = [// boot cannot load it, the setting is authenticated-only). Miss that and an// EDITOR workspace silently falls through to the landing page. This loader// resolves synchronously (see AppRoot), so it does not fetch the profile-// itself. `SetupPage.homePath` still keeps its own copy of the EDITOR rule;-// folding it in here is a follow-up.function resolveRootRedirect(store: ReturnType<typeof useAppStore.getState>): string {@@ -209,12 +205,12 @@ export function rootGuard({);}- // Allow 2FA setup / password reset / profile setup for logged-in users.+ // Allow 2FA setup / password reset / workspace setup for logged-in users.if (isLoggedIn &&(toName === AUTH_2FA_SETUP_MODULE ||toName === AUTH_PASSWORD_RESET_MODULE ||- toName === AUTH_PROFILE_SETUP_MODULE)+ toName === AUTH_SETUP_MODULE)) {return null;}diff --git a/frontend/src/app/router/handles.ts b/frontend/src/app/router/handles.tsindex 847bbbf4c1..2a8f6ac17d 100644--- a/frontend/src/app/router/handles.ts+++ b/frontend/src/app/router/handles.ts@@ -42,13 +42,10 @@ export const AUTH_PASSWORD_RESET_MODULE = "auth.password.reset";export const AUTH_PASSWORD_FORGOT_MODULE = "auth.password.forgot";export const AUTH_OAUTH_CALLBACK_MODULE = "auth.oauth.callback";export const AUTH_OIDC_CALLBACK_MODULE = "auth.oidc.callback";-export const AUTH_PROFILE_SETUP_MODULE = "auth.profile.setup";+export const AUTH_SETUP_MODULE = "auth.setup";export const AUTH_2FA_SETUP_MODULE = "auth.2fa.setup";export const OAUTH2_CONSENT_MODULE = "oauth2.consent";-// --- setup.ts ----export const SETUP_MODULE = "setup";-// --- sqlEditor.ts ---export const SQL_EDITOR_HOME_MODULE = "sql-editor.home";export const SQL_EDITOR_PROJECT_MODULE = "sql-editor.project";diff --git a/frontend/src/app/router/routes/auth.tsx b/frontend/src/app/router/routes/auth.tsxindex a3c0828800..3bd873580e 100644--- a/frontend/src/app/router/routes/auth.tsx+++ b/frontend/src/app/router/routes/auth.tsx@@ -7,11 +7,10 @@ import {AUTH_OIDC_CALLBACK_MODULE,AUTH_PASSWORD_FORGOT_MODULE,AUTH_PASSWORD_RESET_MODULE,- AUTH_PROFILE_SETUP_MODULE,+ AUTH_SETUP_MODULE,AUTH_SIGNIN_MODULE,AUTH_SIGNUP_MODULE,OAUTH2_CONSENT_MODULE,- SETUP_MODULE,} from "@/app/router/handles";import { lazyPage } from "@/app/router/lazyPage";@@ -88,11 +87,11 @@ export const authRoutes: RouteObject[] = [),},{- path: "profile-setup",- handle: { name: AUTH_PROFILE_SETUP_MODULE },+ path: "setup",+ handle: { name: AUTH_SETUP_MODULE },lazy: lazyPage(- () => import("@/routes/auth/ProfileSetupPage"),- (m) => m.ProfileSetupPage+ () => import("@/routes/auth/WorkspaceSetupPage"),+ (m) => m.WorkspaceSetupPage),},],@@ -121,18 +120,4 @@ export const authRoutes: RouteObject[] = [(m) => m.TwoFactorRequiredPage),},- {- path: "/setup",- element: <SplashLayout />,- children: [- {- index: true,- handle: { name: SETUP_MODULE },- lazy: lazyPage(- () => import("@/routes/auth/SetupPage"),- (m) => m.SetupPage- ),- },- ],- },];diff --git a/frontend/src/architecture/e2e-sample-bootstrap.test.ts b/frontend/src/architecture/e2e-sample-bootstrap.test.tsnew file mode 100644index 0000000000..ac88e4bbba--- /dev/null+++ b/frontend/src/architecture/e2e-sample-bootstrap.test.ts@@ -0,0 +1,36 @@+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, test } from "vitest";++const frameworkDir = join(import.meta.dirname, "../../tests/e2e/framework");+const apiClientSource = readFileSync(+ join(frameworkDir, "api-client.ts"),+ "utf8"+);+const bootstrapSource = readFileSync(+ join(frameworkDir, "mode-start-new-bytebase.ts"),+ "utf8"+);+const setupProjectSource = readFileSync(+ join(frameworkDir, "setup-project.ts"),+ "utf8"+);++describe("E2E sample bootstrap", () => {+ test("uses the project-scoped sample API and its single-instance result", () => {+ expect(apiClientSource).not.toContain(+ ["/v1/actuator", ["setup", "Sample"].join("")].join(":")+ );+ expect(apiClientSource).toContain("instances:prepareSampleProjectInstance");++ expect(bootstrapSource).not.toContain(+ ["api", ["setup", "Sample()"].join("")].join(".")+ );+ expect(bootstrapSource).toContain("api.prepareSampleProjectInstance(");+ expect(bootstrapSource).not.toContain("instances/prod-sample-instance");+ expect(bootstrapSource).not.toContain("[port + 3, port + 4]");++ expect(setupProjectSource).toContain("updateDatabaseEnvironment(");+ expect(setupProjectSource).toContain('"environments/prod"');+ });+});diff --git a/frontend/src/components/HowBytebaseWorksSheet.test.tsx b/frontend/src/components/HowBytebaseWorksSheet.test.tsxnew file mode 100644index 0000000000..09e97023f5--- /dev/null+++ b/frontend/src/components/HowBytebaseWorksSheet.test.tsx@@ -0,0 +1,122 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { beforeEach, describe, expect, test, vi } from "vitest";+import guideContent from "@/locales/guides/how-bytebase-works.en-US.md?raw";+import { HowBytebaseWorksSheet } from "./HowBytebaseWorksSheet";++const mocks = vi.hoisted(() => ({+ captureMetric: vi.fn(),+ resolvedLanguage: "en-US",+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ i18n: { resolvedLanguage: mocks.resolvedLanguage },+ }),+}));++vi.mock("@/app/analytics/provider", () => ({+ behaviorAnalytics: {+ captureMetric: mocks.captureMetric,+ },+}));++describe("HowBytebaseWorksSheet", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.resolvedLanguage = "en-US";+ });++ test("keeps the product model concise in Markdown", () => {+ expect(guideContent).toContain(+ "Bytebase sits between your team and your databases"+ );+ expect(guideContent).toContain("- **Workspace:**");+ expect(guideContent).toContain("- **Project:**");+ expect(guideContent).toContain("- **Instance:**");+ expect(guideContent).toContain("- **Database:**");+ expect(guideContent).toContain("- **Query data:**");+ expect(guideContent).toContain("- **Change data:**");+ expect(guideContent).not.toContain("## ");+ });++ test("renders the documentation-aligned explanation without an abstract diagram", async () => {+ render(<HowBytebaseWorksSheet open onOpenChange={vi.fn()} />);++ expect(+ await screen.findByText("workspace-setup-guide.product-model")+ ).toBeInTheDocument();+ expect(+ screen.getByText(/sits between your team and your databases/i)+ ).toBeInTheDocument();+ expect(screen.queryByRole("img")).not.toBeInTheDocument();++ const learnMoreLink = screen.getByRole("link", {+ name: "Learn more about how Bytebase organizes resources",+ });+ expect(learnMoreLink).toHaveAttribute(+ "href",+ "https://docs.bytebase.com/onboarding/organize-resources"+ );+ expect(learnMoreLink).toHaveAttribute("target", "_blank");+ });++ test("captures the learn more action", async () => {+ render(<HowBytebaseWorksSheet open onOpenChange={vi.fn()} />);++ fireEvent.click(+ await screen.findByRole("link", {+ name: "Learn more about how Bytebase organizes resources",+ })+ );++ expect(mocks.captureMetric).toHaveBeenCalledWith({+ event: "setup guide action clicked",+ properties: {+ action: "product_model_learn_more",+ source: "drawer",+ },+ });+ });++ test.each([+ {+ locale: "zh-CN",+ intro: "Bytebase 位于你的团队和数据库之间",+ link: "进一步了解 Bytebase 如何组织资源",+ },+ {+ locale: "es-ES",+ intro: "Bytebase se sitúa entre tu equipo y tus bases de datos",+ link: "Más información sobre cómo Bytebase organiza los recursos",+ },+ {+ locale: "ja-JP",+ intro: "Bytebase はチームとデータベースの間に位置し",+ link: "Bytebase のリソース構成について詳しく見る",+ },+ {+ locale: "vi-VN",+ intro: "Bytebase nằm giữa nhóm của bạn và các cơ sở dữ liệu",+ link: "Tìm hiểu thêm về cách Bytebase tổ chức tài nguyên",+ },+ ])("renders the $locale guide", async ({ locale, intro, link }) => {+ mocks.resolvedLanguage = locale;++ render(<HowBytebaseWorksSheet open onOpenChange={vi.fn()} />);++ expect(await screen.findByText(new RegExp(intro))).toBeInTheDocument();+ expect(screen.getByRole("link", { name: link })).toHaveAttribute(+ "href",+ "https://docs.bytebase.com/onboarding/organize-resources"+ );+ });++ test("does not render without content for the resolved locale", () => {+ mocks.resolvedLanguage = "fr-FR";++ render(<HowBytebaseWorksSheet open onOpenChange={vi.fn()} />);++ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });+});diff --git a/frontend/src/components/HowBytebaseWorksSheet.tsx b/frontend/src/components/HowBytebaseWorksSheet.tsxnew file mode 100644index 0000000000..bd91669f02--- /dev/null+++ b/frontend/src/components/HowBytebaseWorksSheet.tsx@@ -0,0 +1,71 @@+import type { MouseEvent, ReactElement } from "react";+import { useTranslation } from "react-i18next";+import { createBehaviorMetric } from "@/app/analytics/behavior";+import { behaviorAnalytics } from "@/app/analytics/provider";+import { MarkdownEditor } from "@/components/MarkdownEditor";+import {+ Sheet,+ SheetBody,+ SheetContent,+ SheetHeader,+ SheetTitle,+} from "@/components/ui/sheet";++type Props = {+ open: boolean;+ onOpenChange: (open: boolean) => void;+};++const guideFiles = import.meta.glob<string>(+ "../locales/guides/how-bytebase-works.*.md",+ { eager: true, import: "default", query: "?raw" }+);++export function getHowBytebaseWorksGuideContent(+ locale: string+): string | undefined {+ const content =+ guideFiles[`../locales/guides/how-bytebase-works.${locale}.md`];+ return content?.trim() ? content : undefined;+}++export function HowBytebaseWorksSheet({+ open,+ onOpenChange,+}: Props): ReactElement | null {+ const { i18n, t } = useTranslation();+ const guideContent = getHowBytebaseWorksGuideContent(+ i18n.resolvedLanguage ?? "en-US"+ );++ if (!guideContent) {+ return null;+ }++ const handleContentClick = (event: MouseEvent<HTMLElement>) => {+ if (!(event.target instanceof Element) || !event.target.closest("a")) {+ return;+ }+ behaviorAnalytics.captureMetric(+ createBehaviorMetric("setup guide action clicked", {+ properties: {+ action: "product_model_learn_more",+ source: "drawer",+ },+ })+ );+ };++ return (+ <Sheet open={open} onOpenChange={onOpenChange}>+ <SheetContent width="narrow">+ <SheetHeader>+ <SheetTitle>{t("workspace-setup-guide.product-model")}</SheetTitle>+ </SheetHeader>+ <SheetBody onClick={handleContentClick}>+ <MarkdownEditor content={guideContent} mode="preview" />+ </SheetBody>+ </SheetContent>+ </Sheet>+ );+}diff --git a/frontend/src/components/WorkspaceSetupGuide.test.tsx b/frontend/src/components/WorkspaceSetupGuide.test.tsxindex f75ec81d67..483057fe3c 100644--- a/frontend/src/components/WorkspaceSetupGuide.test.tsx+++ b/frontend/src/components/WorkspaceSetupGuide.test.tsx@@ -15,7 +15,6 @@ import { sqlEditorEvents } from "@/modules/sql-editor/model/events";).IS_REACT_ACT_ENVIRONMENT = true;const mocks = vi.hoisted(() => ({- isSaaSMode: vi.fn(() => true),projectsByName: {} as Record<string, unknown>,instancesByName: {} as Record<string, unknown>,databasesByName: {} as Record<string, unknown>,@@ -53,14 +52,15 @@ const mocks = vi.hoisted(() => ({currentRoute: { name: "workspace.home" } as {name?: string;params?: Record<string, string | undefined>;+ query?: Record<string, string | undefined>;},routerPush: vi.fn(),captureMetric: vi.fn(),defaultProjectName: "projects/default",- sampleInstances: [] as { instance: string }[],userCountInIam: 1,hideQuickStart: false,workspaceName: "workspaces/default",+ productModelContent: "guide content" as string | undefined,}));const dismissedIntroStateKey = "workspace-setup-guide.dismissed";@@ -72,6 +72,7 @@ vi.mock("react-i18next", () => ({initReactI18next: { type: "3rdParty", init: () => {} },useTranslation: () => ({t: (key: string) => key,+ i18n: { resolvedLanguage: "en-US" },}),}));@@ -120,7 +121,6 @@ vi.mock("@/app/analytics/provider", () => ({vi.mock("@/stores/app", () => {const getState = () => ({- isSaaSMode: mocks.isSaaSMode,projectsByName: mocks.projectsByName,instancesByName: mocks.instancesByName,databasesByName: mocks.databasesByName,@@ -136,7 +136,6 @@ vi.mock("@/stores/app", () => {hasWorkspacePermission: mocks.hasWorkspacePermissionV2,serverInfo: {defaultProject: mocks.defaultProjectName,- sample: { instances: mocks.sampleInstances },},introStateVersion: mocks.introStateVersion,getIntroStateByKey: mocks.getIntroStateByKey,@@ -203,6 +202,28 @@ vi.mock("@/lib/plan/issue", () => ({preCreateIssue: mocks.preCreateIssue,}));+vi.mock("@/components/HowBytebaseWorksSheet", () => ({+ getHowBytebaseWorksGuideContent: () => mocks.productModelContent,+ HowBytebaseWorksSheet: ({+ open,+ onOpenChange,+ }: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ }) =>+ open ? (+ <div data-testid="product-model-sheet">+ <button+ data-testid="close-product-model"+ type="button"+ onClick={() => onOpenChange(false)}+ >+ Close+ </button>+ </div>+ ) : null,+}));+import { WorkspaceSetupGuide } from "./WorkspaceSetupGuide";let container: HTMLDivElement;@@ -219,7 +240,6 @@ beforeEach(() => {mocks.introState[key] = newState;mocks.introStateVersion += 1;});- mocks.isSaaSMode.mockReturnValue(true);mocks.projectsByName = {};mocks.instancesByName = {};mocks.databasesByName = {};@@ -245,10 +265,10 @@ beforeEach(() => {mocks.hasWorkspacePermissionV2.mockReturnValue(true);mocks.currentRoute = { name: "workspace.home" };mocks.defaultProjectName = "projects/default";- mocks.sampleInstances = [];mocks.userCountInIam = 1;mocks.hideQuickStart = false;mocks.workspaceName = "workspaces/default";+ mocks.productModelContent = "guide content";container = document.createElement("div");document.body.appendChild(container);root = createRoot(container);@@ -273,18 +293,99 @@ const render = async (element: ReactElement) => {};describe("WorkspaceSetupGuide", () => {- it("renders outside SaaS mode", async () => {- mocks.isSaaSMode.mockReturnValue(false);+ it("opens the product model once for a new eligible guide", async () => {+ await render(<WorkspaceSetupGuide />);++ expect(+ container.querySelector('[data-testid="product-model-sheet"]')+ ).not.toBeNull();+ });++ it("does not auto-open the product model over a contextual intro", async () => {+ mocks.currentRoute = {+ name: "workspace.project.database",+ query: { intro: "connect-database" },+ };await render(<WorkspaceSetupGuide />);- expect(container.textContent).toContain(- "workspace-setup-guide.self"- );- expect(mocks.fetchProjectList).toHaveBeenCalled();+ expect(+ container.querySelector('[data-testid="product-model-sheet"]')+ ).toBeNull();+ });++ it("does not auto-open a product model that was already seen", async () => {+ mocks.introState["workspace-setup-guide.product-model-seen"] = true;++ await render(<WorkspaceSetupGuide />);++ expect(+ container.querySelector('[data-testid="product-model-sheet"]')+ ).toBeNull();+ });++ it("disables the product model drawer when localized content is missing", async () => {+ mocks.productModelContent = undefined;++ await render(<WorkspaceSetupGuide />);++ expect(+ container.querySelector('[data-testid="open-product-model"]')+ ).toBeNull();+ expect(+ container.querySelector('[data-testid="product-model-sheet"]')+ ).toBeNull();+ });++ it("persists seen state when the product model closes", async () => {+ await render(<WorkspaceSetupGuide />);++ act(() => {+ container+ .querySelector<HTMLButtonElement>(+ '[data-testid="close-product-model"]'+ )+ ?.click();+ });++ expect(mocks.saveIntroStateByKey).toHaveBeenCalledWith({+ key: "workspace-setup-guide.product-model-seen",+ newState: true,+ });+ });++ it("uses the shared product model label for the guide control", async () => {+ await render(<WorkspaceSetupGuide />);++ expect(+ container.querySelector('[data-testid="open-product-model"]')+ ).toHaveAttribute("aria-label", "workspace-setup-guide.product-model");+ });++ it("reopens the product model from the guide control", async () => {+ mocks.introState["workspace-setup-guide.product-model-seen"] = true;++ await render(<WorkspaceSetupGuide />);++ act(() => {+ container+ .querySelector<HTMLButtonElement>('[data-testid="open-product-model"]')+ ?.click();+ });++ expect(+ container.querySelector('[data-testid="product-model-sheet"]')+ ).not.toBeNull();+ expect(mocks.captureMetric).toHaveBeenCalledWith({+ event: "setup guide action clicked",+ properties: {+ action: "product_model_open",+ source: "guide_bar",+ },+ });});- it("shows the first incomplete setup action for SaaS workspaces", async () => {+ it("shows the first incomplete setup action", async () => {await render(<WorkspaceSetupGuide />);expect(container.textContent).toContain(@@ -792,11 +893,7 @@ describe("WorkspaceSetupGuide", () => {]);});- it("counts self-host sample resources as project and instance readiness", async () => {- mocks.sampleInstances = [- { instance: "instances/sample-one" },- { instance: "instances/sample-two" },- ];+ it("counts workspace-owned instances as project and instance readiness", async () => {mocks.fetchProjectList.mockResolvedValue({projects: [{ name: "projects/project-sample" }],nextPageToken: "",@@ -840,22 +937,19 @@ describe("WorkspaceSetupGuide", () => {}});- it("counts SaaS sample resources as project and instance readiness", async () => {- mocks.sampleInstances = [- { instance: "projects/app/instances/saas-sample" },- ];+ it("counts project-owned instances as project and instance readiness", async () => {mocks.fetchProjectList.mockResolvedValue({projects: [{ name: "projects/app" }],nextPageToken: "",});mocks.fetchInstanceList.mockResolvedValue({- instances: [{ name: "projects/app/instances/saas-sample" }],+ instances: [{ name: "projects/app/instances/project-sample" }],nextPageToken: "",});mocks.fetchDatabases.mockResolvedValue({databases: [{- name: "projects/app/instances/saas-sample/databases/employee",+ name: "projects/app/instances/project-sample/databases/employee",project: "projects/app",},],@@ -882,7 +976,6 @@ describe("WorkspaceSetupGuide", () => {it("uses only the first resource page", async () => {mocks.introState[databaseExploredIntroStateKey] = true;- mocks.sampleInstances = [{ instance: "instances/sample" }];mocks.fetchProjectList.mockResolvedValue({projects: [{ name: "projects/project-sample" }],nextPageToken: "project-page-2",@@ -919,13 +1012,13 @@ describe("WorkspaceSetupGuide", () => {}));expect(mocks.fetchProjectList).toHaveBeenCalledTimes(1);- expect(mocks.fetchInstanceList).toHaveBeenCalledTimes(1);+ expect(mocks.fetchInstanceList).toHaveBeenCalledTimes(2);expect(mocks.fetchDatabases).toHaveBeenCalledTimes(1);expect(mocks.fetchProjectList).toHaveBeenCalledWith(expect.objectContaining({ pageSize: 1 }));expect(mocks.fetchInstanceList).toHaveBeenCalledWith(- expect.objectContaining({ pageSize: 1 })+ expect.objectContaining({ pageSize: 1, parent: "projects/project-sample" }));expect(mocks.fetchDatabases).toHaveBeenCalledWith(expect.objectContaining({@@ -1322,9 +1415,6 @@ describe("WorkspaceSetupGuide", () => {});it("completes Query data only after SQL execution finishes", async () => {- mocks.sampleInstances = [- { instance: "projects/app/instances/saas-sample" },- ];mocks.fetchProjectList.mockResolvedValue({projects: [{ name: "projects/project-a" }],nextPageToken: "",@@ -1365,8 +1455,8 @@ describe("WorkspaceSetupGuide", () => {await act(async () => {await sqlEditorEvents.emit("query-executed", {- database: "projects/app/instances/saas-sample/databases/employee",- project: "projects/project-sample",+ database: "projects/project-a/instances/instance-a/databases/db-a",+ project: "projects/project-a",});});@@ -1742,6 +1832,31 @@ describe("WorkspaceSetupGuide", () => {);});+ it("completes the instance step for an instance owned by the project", async () => {+ mocks.fetchProjectList.mockResolvedValue({+ projects: [{ name: "projects/project-a" }],+ nextPageToken: "",+ });+ mocks.fetchInstanceList.mockImplementation(async (params) => ({+ instances:+ params?.parent === "projects/project-a"+ ? [{ name: "projects/project-a/instances/sample" }]+ : [],+ nextPageToken: "",+ }));++ await render(<WorkspaceSetupGuide />);++ expect(mocks.fetchInstanceList).toHaveBeenCalledWith(+ expect.objectContaining({ parent: "projects/project-a", pageSize: 1 })+ );+ expect(+ container+ .querySelector("[data-testid='setup-step-hasInstance']")+ ?.querySelector(".lucide-circle-check-big")+ ).not.toBeNull();+ });+it("keeps the guide visible while progress is refreshing", async () => {let resolveProjectList:| ((value: { projects: unknown[]; nextPageToken: string }) => void)diff --git a/frontend/src/components/WorkspaceSetupGuide.tsx b/frontend/src/components/WorkspaceSetupGuide.tsxindex 6d85f759a0..89afff6d86 100644--- a/frontend/src/components/WorkspaceSetupGuide.tsx+++ b/frontend/src/components/WorkspaceSetupGuide.tsx@@ -1,4 +1,4 @@-import { CheckCircle, Circle, X } from "lucide-react";+import { CheckCircle, Circle, CircleHelp, X } from "lucide-react";import { useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { createBehaviorMetric } from "@/app/analytics/behavior";@@ -14,6 +14,10 @@ import {PROJECT_V1_ROUTE_INSTANCES,SQL_EDITOR_DATABASE_MODULE,} from "@/app/router/handles";+import {+ getHowBytebaseWorksGuideContent,+ HowBytebaseWorksSheet,+} from "@/components/HowBytebaseWorksSheet";import { SQLEditorButton } from "@/components/SQLEditorButton";import { Button } from "@/components/ui/button";import { Tooltip } from "@/components/ui/tooltip";@@ -72,6 +76,8 @@ const WORKSPACE_SETUP_GUIDE_DATABASE_EXPLORED_KEY ="workspace-setup-guide.database-explored";const WORKSPACE_SETUP_GUIDE_QUERY_EXECUTED_KEY ="workspace-setup-guide.query-executed";+const WORKSPACE_SETUP_GUIDE_PRODUCT_MODEL_SEEN_KEY =+ "workspace-setup-guide.product-model-seen";const isRouteInside = (routeName: string | undefined, parentName: string) =>routeName === parentName || !!routeName?.startsWith(`${parentName}.`);@@ -106,7 +112,7 @@ const isConcreteDatabaseRoute = (};export function WorkspaceSetupGuide() {- const { t } = useTranslation();+ const { i18n, t } = useTranslation();const currentRoute = useCurrentRoute();const dismissed = useIntroStateByKey(WORKSPACE_SETUP_GUIDE_DISMISSED_KEY);const databaseExplored = useIntroStateByKey(@@ -115,6 +121,9 @@ export function WorkspaceSetupGuide() {const queryExecuted = useIntroStateByKey(WORKSPACE_SETUP_GUIDE_QUERY_EXECUTED_KEY);+ const productModelSeen = useIntroStateByKey(+ WORKSPACE_SETUP_GUIDE_PRODUCT_MODEL_SEEN_KEY+ );const serverInfo = useAppStore((s) => s.serverInfo);const defaultProject = serverInfo?.defaultProject ?? "";const projectCacheSize = useAppStore(@@ -128,9 +137,16 @@ export function WorkspaceSetupGuide() {);const workspaceResourceName = useAppStore((s) => s.workspaceResourceName());const guideEnabled = useAppStore((s) => s.workspaceSetupGuideEnabled());+ const productModelAvailable = !!getHowBytebaseWorksGuideContent(+ i18n.resolvedLanguage ?? "en-US"+ );+ const hasContextualProductIntro =+ typeof currentRoute.query?.[PRODUCT_INTRO_QUERY_KEY] === "string";const [loading, setLoading] = useState(true);+ const [productModelOpen, setProductModelOpen] = useState(false);const [selectedStepKey, setSelectedStepKey] = useState<keyof SetupKeys>();const [setupState, setSetupState] = useState<SetupState>(initialSetupState);+ const productModelAutoOpenedScopeRef = useRef<string | undefined>(undefined);const queryTargetRef = useRef<{ projectName: string; databaseName: string } | undefined>(undefined);@@ -204,6 +220,34 @@ export function WorkspaceSetupGuide() {setSelectedStepKey(undefined);}, [currentRoute.name]);+ useEffect(() => {+ if (productModelSeen) {+ productModelAutoOpenedScopeRef.current = undefined;+ return;+ }+ if (+ loading ||+ dismissed ||+ !guideEnabled ||+ !productModelAvailable ||+ hasContextualProductIntro ||+ !workspaceResourceName ||+ productModelAutoOpenedScopeRef.current === workspaceResourceName+ ) {+ return;+ }+ productModelAutoOpenedScopeRef.current = workspaceResourceName;+ setProductModelOpen(true);+ }, [+ dismissed,+ guideEnabled,+ hasContextualProductIntro,+ loading,+ productModelAvailable,+ productModelSeen,+ workspaceResourceName,+ ]);+const onSelectStep = (step: SetupStep) => {behaviorAnalytics.captureMetric(createBehaviorMetric("setup guide action clicked", {@@ -228,34 +272,47 @@ export function WorkspaceSetupGuide() {void (async () => {const store = useAppStore.getState();try {- const [projectResponse, instanceResponse] = await Promise.all([- store.fetchProjectList({- pageSize: 1,- silent: true,- filter: {- excludeDefault: true,- state: State.ACTIVE,- },- }),+ const projectResponse = await store.fetchProjectList({+ pageSize: 1,+ silent: true,+ filter: {+ excludeDefault: true,+ state: State.ACTIVE,+ },+ });+ const project = projectResponse.projects.find(+ ({ name }) => !!name && name !== defaultProject+ );+ const [+ workspaceInstanceResponse,+ projectInstanceResponse,+ databaseResponse,+ ] = await Promise.all([store.fetchInstanceList({pageSize: 1,filter: { state: State.ACTIVE },silent: true,}),- ]);- const project = projectResponse.projects.find(- ({ name }) => !!name && name !== defaultProject- );- const instance = instanceResponse.instances[0];- const databaseResponse =+ project+ ? store.fetchInstanceList({+ parent: project.name,+ pageSize: 1,+ filter: { state: State.ACTIVE },+ silent: true,+ })+ : Promise.resolve({ instances: [], nextPageToken: "" }),project && workspaceResourceName- ? await store.fetchDatabases({+ ? store.fetchDatabases({parent: workspaceResourceName,pageSize: 1,filter: { project: project.name },silent: true,})- : undefined;+ : Promise.resolve(undefined),+ ]);+ const instance =+ workspaceInstanceResponse.instances[0] ??+ projectInstanceResponse.instances[0];const database = databaseResponse?.databases.find(({ name, project }) => !!name && !!project);@@ -433,105 +490,147 @@ export function WorkspaceSetupGuide() {});};+ const handleProductModelOpenChange = (open: boolean) => {+ if (open) {+ behaviorAnalytics.captureMetric(+ createBehaviorMetric("setup guide action clicked", {+ properties: {+ action: "product_model_open",+ source: "guide_bar",+ },+ })+ );+ }+ setProductModelOpen(open);+ if (!open && !productModelSeen) {+ useAppStore.getState().saveIntroStateByKey({+ key: WORKSPACE_SETUP_GUIDE_PRODUCT_MODEL_SEEN_KEY,+ newState: true,+ });+ }+ };+if (dismissed || !guideEnabled || loading) {return null;}return (- <div className="flex w-full shrink-0 items-center gap-x-2 border-t border-block-border bg-white px-3 py-2 shadow-[0_-2px_10px_rgba(0,0,0,0.04)] 2xl:gap-x-4 2xl:px-5 2xl:py-4">- <div className="flex min-w-0 flex-1 items-center gap-x-2 overflow-hidden 2xl:gap-x-4">- <div className="flex shrink-0 items-baseline gap-x-2">- <div className="shrink-0 text-sm font-semibold text-main 2xl:text-base">- {t("workspace-setup-guide.self")}+ <>+ <div className="flex w-full shrink-0 items-center gap-x-2 border-t border-block-border bg-white px-3 py-2 shadow-[0_-2px_10px_rgba(0,0,0,0.04)] 2xl:gap-x-4 2xl:px-5 2xl:py-4">+ <div className="flex min-w-0 flex-1 items-center gap-x-2 overflow-hidden 2xl:gap-x-4">+ <div className="flex shrink-0 items-center gap-x-1">+ <div className="shrink-0 text-sm font-semibold text-main 2xl:text-base">+ {t("workspace-setup-guide.self")}+ </div>+ {productModelAvailable && (+ <Tooltip content={t("workspace-setup-guide.product-model")}>+ <Button+ type="button"+ appearance="secondary"+ size="sm"+ data-testid="open-product-model"+ aria-label={t("workspace-setup-guide.product-model")}+ onClick={() => handleProductModelOpenChange(true)}+ >+ <CircleHelp className="size-4" />+ </Button>+ </Tooltip>+ )}</div>- </div>- <div className="flex min-w-0 flex-1 items-center gap-x-2 overflow-x-auto pr-1 2xl:gap-x-3 2xl:pr-2">- {steps.map((step, index) => {- const isHighlighted = step.key === highlightedStep?.key;- const tooltipContent = step.disabled- ? t("workspace-setup-guide.previous-step-required")- : step.description;- const className = cn(- "inline-flex items-center gap-x-1 rounded-sm px-2 py-1 text-sm whitespace-nowrap 2xl:gap-x-2 2xl:px-3 2xl:py-2 2xl:text-base",- isHighlighted- ? "bg-accent/10 text-accent"- : step.done- ? "text-control-light"- : "text-control"- );+ <div className="flex min-w-0 flex-1 items-center gap-x-2 overflow-x-auto pr-1 2xl:gap-x-3 2xl:pr-2">+ {steps.map((step, index) => {+ const isHighlighted = step.key === highlightedStep?.key;+ const tooltipContent = step.disabled+ ? t("workspace-setup-guide.previous-step-required")+ : step.description;+ const className = cn(+ "inline-flex items-center gap-x-1 rounded-sm px-2 py-1 text-sm whitespace-nowrap 2xl:gap-x-2 2xl:px-3 2xl:py-2 2xl:text-base",+ isHighlighted+ ? "bg-accent/10 text-accent"+ : step.done+ ? "text-control-light"+ : "text-control"+ );- return (- <div- key={step.key}- className="inline-flex items-center gap-x-2 2xl:gap-x-3"- >- <Tooltip content={tooltipContent}>- <Button- type="button"- appearance="secondary"- data-testid={`setup-step-${step.key}`}- className={cn(- className,- "h-auto justify-start py-1 font-medium 2xl:py-2"- )}- disabled={step.disabled}- onClick={() => onSelectStep(step)}- >- {step.done ? (- <CheckCircle className="size-4 text-success 2xl:size-5" />- ) : (- <Circle className="size-4 2xl:size-5" />- )}- <span>{step.label}</span>- </Button>- </Tooltip>- {index < steps.length - 1 && (- <span className="text-sm text-control-light 2xl:text-base">- ›- </span>- )}- </div>- );- })}+ return (+ <div+ key={step.key}+ className="inline-flex items-center gap-x-2 2xl:gap-x-3"+ >+ <Tooltip content={tooltipContent}>+ <Button+ type="button"+ appearance="secondary"+ data-testid={`setup-step-${step.key}`}+ className={cn(+ className,+ "h-auto justify-start py-1 font-medium 2xl:py-2"+ )}+ disabled={step.disabled}+ onClick={() => onSelectStep(step)}+ >+ {step.done ? (+ <CheckCircle className="size-4 text-success 2xl:size-5" />+ ) : (+ <Circle className="size-4 2xl:size-5" />+ )}+ <span>{step.label}</span>+ </Button>+ </Tooltip>+ {index < steps.length - 1 && (+ <span className="text-sm text-control-light 2xl:text-base">+ ›+ </span>+ )}+ </div>+ );+ })}+ </div></div>- </div>- <div className="ml-auto flex shrink-0 items-center gap-x-2">- {actionStep.key === "hasFirstQuery" &&- setupState.databaseProjectName &&- setupState.databaseName && (- <Button- type="button"- data-testid="secondary-action"- appearance="secondary"- size="md"- className="hidden 2xl:inline-flex"- onClick={handleCreateFirstChange}- >- {t("workspace-setup-guide.actions.change")}- </Button>+ <div className="ml-auto flex shrink-0 items-center gap-x-2">+ {actionStep.key === "hasFirstQuery" &&+ setupState.databaseProjectName &&+ setupState.databaseName && (+ <Button+ type="button"+ data-testid="secondary-action"+ appearance="secondary"+ size="md"+ className="hidden 2xl:inline-flex"+ onClick={handleCreateFirstChange}+ >+ {t("workspace-setup-guide.actions.change")}+ </Button>+ )}+ {actionStep.key === "hasFirstQuery" && sqlEditorDatabase && (+ <SQLEditorButton+ data-testid="active-action"+ database={sqlEditorDatabase}+ openInNewTab+ size="sm"+ className="2xl:h-9 2xl:gap-1.5 2xl:px-3 2xl:text-sm 2xl:leading-5"+ label={t("workspace-setup-guide.actions.query")}+ />)}- {actionStep.key === "hasFirstQuery" && sqlEditorDatabase && (- <SQLEditorButton- data-testid="active-action"- database={sqlEditorDatabase}- openInNewTab+ <Button+ type="button"+ data-testid="dismiss-guide"+ aria-label={t("workspace-setup-guide.dismiss")}+ appearance="secondary"size="sm"- className="2xl:h-9 2xl:gap-1.5 2xl:px-3 2xl:text-sm 2xl:leading-5"- label={t("workspace-setup-guide.actions.query")}- />- )}- <Button- type="button"- data-testid="dismiss-guide"- aria-label={t("workspace-setup-guide.dismiss")}- appearance="secondary"- size="sm"- className="text-control-light hover:text-control 2xl:h-9 2xl:gap-1.5 2xl:px-3 2xl:text-sm 2xl:leading-5"- onClick={handleDismiss}- >- <X className="size-4 2xl:size-5" />- </Button>+ className="text-control-light hover:text-control 2xl:h-9 2xl:gap-1.5 2xl:px-3 2xl:text-sm 2xl:leading-5"+ onClick={handleDismiss}+ >+ <X className="size-4 2xl:size-5" />+ </Button>+ </div></div>- </div>+ {productModelAvailable && (+ <HowBytebaseWorksSheet+ open={productModelOpen && !hasContextualProductIntro}+ onOpenChange={handleProductModelOpenChange}+ />+ )}+ </>);}diff --git a/frontend/src/components/header/ProfileMenuTrigger.test.tsx b/frontend/src/components/header/ProfileMenuTrigger.test.tsxindex 7e73199393..816a91d3de 100644--- a/frontend/src/components/header/ProfileMenuTrigger.test.tsx+++ b/frontend/src/components/header/ProfileMenuTrigger.test.tsx@@ -28,7 +28,6 @@ const mocks = vi.hoisted(() => ({hideQuickStart: false,canReadSetupResources: true,userCountInIam: 1,- sampleAvailable: true,isDev: false,}));@@ -136,10 +135,6 @@ vi.mock("@/hooks/useAppState", () => ({title: "Alice",email: "[email protected]",}),- useServerInfo: () => ({- sample: { available: mocks.sampleAvailable },- userCountInIam: mocks.userCountInIam,- }),useSubscription: () => ({subscription: { plan: PlanType.FREE },uploadLicense: mocks.uploadLicense,@@ -198,7 +193,6 @@ beforeEach(async () => {mocks.hideQuickStart = false;mocks.canReadSetupResources = true;mocks.userCountInIam = 1;- mocks.sampleAvailable = true;mocks.isDev = false;mocks.currentRoute.name = "sql-editor.home";window.open = vi.fn();@@ -289,8 +283,7 @@ describe("ProfileMenuTrigger", () => {unmount();});- test("restores the unified guide even when no sample is available", () => {- mocks.sampleAvailable = false;+ test("restores the unified guide", () => {const { container, render, unmount } = renderIntoContainer(<ProfileMenuTrigger size="medium" link />);diff --git a/frontend/src/components/instance/CreateInstanceView.test.tsx b/frontend/src/components/instance/CreateInstanceView.test.tsxindex ec6996b0ef..d646f309c1 100644--- a/frontend/src/components/instance/CreateInstanceView.test.tsx+++ b/frontend/src/components/instance/CreateInstanceView.test.tsx@@ -38,12 +38,15 @@ vi.mock("react-i18next", () => ({({"instance.use-sample-instance":"Use sample instance (Available for 7 days)",+ "instance.use-sample-instance-self-host": "Use sample instance","instance.preparing-sample-instance":"Preparing Sample Project Instance…","instance.prepare-sample-instance-failed":"Failed to prepare Sample Project Instance.","instance.sample-project-instance-description":"Use a Sample Project Instance to explore Bytebase with a ready-to-use database for 7 days.",+ "instance.sample-project-instance-description-self-host":+ "Use a Sample Project Instance to explore Bytebase with a ready-to-use database.","instance.sample-project-instance-title":"Try a Sample Project Instance","subscription.usage.instance-count.title": "Instance quota reached",@@ -534,7 +537,7 @@ describe("CreateInstanceView", () => {});});- test("keeps sample instance creation out of self-hosted project and SaaS workspace creation", () => {+ test("shows permanent sample creation for a self-hosted project", () => {const container = document.createElement("div");const root = createRoot(container);@@ -548,9 +551,45 @@ describe("CreateInstanceView", () => {);});- expect(container.textContent).not.toContain("Use sample instance");+ expect(container.textContent).toContain("Use sample instance");+ expect(container.textContent).toContain("ready-to-use database.");+ expect(container.textContent).not.toContain("7 days");++ act(() => {+ root.unmount();+ });+ });++ test("keeps seven-day sample copy for SaaS", () => {+ mocks.isSaaSMode = true;+ const container = document.createElement("div");+ const root = createRoot(container);++ act(() => {+ root.render(+ <CreateInstanceView+ parent="projects/demo"+ onDismiss={mocks.onDismiss}+ onCreated={mocks.onCreated}+ />+ );+ });++ expect(container.textContent).toContain(+ "Use sample instance (Available for 7 days)"+ );+ expect(container.textContent).toContain("ready-to-use database for 7 days.");+ act(() => {+ root.unmount();+ });+ });++ test("keeps sample creation out of workspace-owned instance creation", () => {mocks.isSaaSMode = true;+ const container = document.createElement("div");+ const root = createRoot(container);+act(() => {root.render(<CreateInstanceViewdiff --git a/frontend/src/components/instance/CreateInstanceView.tsx b/frontend/src/components/instance/CreateInstanceView.tsxindex c7cb50683b..9547141703 100644--- a/frontend/src/components/instance/CreateInstanceView.tsx+++ b/frontend/src/components/instance/CreateInstanceView.tsx@@ -48,7 +48,6 @@ export function CreateInstanceView({);const totalInstanceCount = useAppStore((state) => state.totalInstanceCount());const canPrepareSampleProjectInstance =- isSaaSMode &&sampleAvailable &&!sampleProvisioned &&totalInstanceCount === 0 &&@@ -80,6 +79,7 @@ export function CreateInstanceView({><CreateInstanceFormInnercanPrepareSampleProjectInstance={canPrepareSampleProjectInstance}+ isSaaSMode={isSaaSMode}onCreated={onCreated}parent={parent}/>@@ -90,10 +90,12 @@ export function CreateInstanceView({function CreateInstanceFormInner({canPrepareSampleProjectInstance,+ isSaaSMode,onCreated,parent,}: {canPrepareSampleProjectInstance: boolean;+ isSaaSMode: boolean;onCreated: (instance: Instance) => void;parent?: string;}) {@@ -215,7 +217,13 @@ function CreateInstanceFormInner({{canPrepareSampleProjectInstance && (<Alerttitle={t("instance.sample-project-instance-title")}- description={t("instance.sample-project-instance-description")}+ description={+ isSaaSMode+ ? t("instance.sample-project-instance-description")+ : t(+ "instance.sample-project-instance-description-self-host"+ )+ }><ButtonclassName="mt-3"@@ -226,7 +234,9 @@ function CreateInstanceFormInner({>{isPreparingSampleProjectInstance? t("instance.preparing-sample-instance")- : t("instance.use-sample-instance")}+ : isSaaSMode+ ? t("instance.use-sample-instance")+ : t("instance.use-sample-instance-self-host")}</Button></Alert>)}diff --git a/frontend/src/components/instance/InstanceDetailView.test.tsx b/frontend/src/components/instance/InstanceDetailView.test.tsxindex 440d5d51f8..5dc572cfc0 100644--- a/frontend/src/components/instance/InstanceDetailView.test.tsx+++ b/frontend/src/components/instance/InstanceDetailView.test.tsx@@ -349,6 +349,19 @@ describe("InstanceDetailView", () => {);});+ it("does not show an expiration warning without sample expiration metadata", async () => {+ mocks.serverInfo = {+ defaultProject: "projects/default",+ sample: {+ instances: [{ instance: "instances/prod" }],+ },+ };++ await render(<InstanceDetailView instanceName="instances/prod" />);++ expect(container.textContent).not.toContain("instance.sample-expiration");+ });+it("does not show the post-sync transfer action when there is no user project", async () => {await render(<InstanceDetailView instanceName="instances/prod" />);diff --git a/frontend/src/hooks/useEnsureWorkspaceCommonData.ts b/frontend/src/hooks/useEnsureWorkspaceCommonData.tsindex 143fd13622..43c91cfc86 100644--- a/frontend/src/hooks/useEnsureWorkspaceCommonData.ts+++ b/frontend/src/hooks/useEnsureWorkspaceCommonData.ts@@ -16,7 +16,7 @@ import { useAppStore } from "@/stores/app";* ready can use `usePermissionDataReady()` from ComponentPermissionGuard,* which awaits the same idempotent request.*- * Auth-flow pages (SetupPage, ProfileSetupPage, OAuth2ConsentPage) render+ * Auth-flow pages (WorkspaceSetupPage and OAuth2ConsentPage) render* outside any shell; they still handle their own loads because they need* a subset of this data before any shell would otherwise mount.*diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 5bc18f3694..17849c2cd9 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1221,6 +1221,7 @@"sample-expiration-future_one": "The sample instance will be removed in {{count}} day, at {{time}}.","sample-expiration-future_other": "The sample instance will be removed in {{count}} days, at {{time}}.","sample-project-instance-description": "Use a Sample Project Instance to explore Bytebase with a ready-to-use database for 7 days.",+ "sample-project-instance-description-self-host": "Use a Sample Project Instance to explore Bytebase with a ready-to-use database.","sample-project-instance-title": "Try a Sample Project Instance","scan-interval": {"default-never": "Default (never)",@@ -1317,6 +1318,7 @@"type-or-paste-credentials-write-only": "Type or paste CREDENTIALS - write only","unable-to-connect": "Bytebase couldn't connect with these settings. Review the guidance above, or continue and update the connection later.\n\nTechnical details: {{0}}","use-sample-instance": "Use sample instance (Available for 7 days)",+ "use-sample-instance-self-host": "Use sample instance","users": "Users","your-snowflake-account-locator": "Your Snowflake account locator"},@@ -2972,26 +2974,6 @@}}},- "setup": {- "basic-info": "Basic info",- "data": {- "built-in": "Use built-in sample",- "built-in-desc": "Generate sample project and instances",- "self-setup": "Setup the project"- },- "purposes": {- "alter-schema": "Alter schema",- "query-data": "Query data",- "self": "What's your main purpose with Bytebase?"- },- "self": "Setup",- "skip-setup": "Skip setup",- "workflow": {- "self": "What's your workflow with database?",- "simple": "No complex workflow, just need UI tools",- "team": "Work with teammates, need CI/CD pipeline"- }- },"sheet": {"filter": {"only-show-starred": "Only show starred",@@ -3560,6 +3542,7 @@},"prepare-database-tip": "Select databases to transfer to the project.","previous-step-required": "You need to finish the previous step.",+ "product-model": "How Bytebase works","self": "Set up Bytebase","steps": {"database": "Explore databases",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 2f5b0186e4..2246559eec 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -1221,6 +1221,7 @@"sample-expiration-future_one": "La instancia de muestra se eliminará en {{count}} día, a las {{time}}.","sample-expiration-future_other": "La instancia de muestra se eliminará en {{count}} días, a las {{time}}.","sample-project-instance-description": "Use una instancia de proyecto de muestra para explorar Bytebase con una base de datos lista para usar durante 7 días.",+ "sample-project-instance-description-self-host": "Use una instancia de proyecto de muestra para explorar Bytebase con una base de datos lista para usar.","sample-project-instance-title": "Pruebe una instancia de proyecto de muestra","scan-interval": {"default-never": "Predeterminado (nunca)",@@ -1317,6 +1318,7 @@"type-or-paste-credentials-write-only": "Escriba o pegue las CREDENCIALES - solo escritura","unable-to-connect": "Bytebase no pudo conectarse con esta configuración. Revisa las indicaciones anteriores o continúa y actualiza la conexión más tarde.\n\nDetalles técnicos: {{0}}","use-sample-instance": "Usar instancia de ejemplo (Disponible durante 7 días)",+ "use-sample-instance-self-host": "Usar instancia de ejemplo","users": "Usuarios","your-snowflake-account-locator": "Su localizador de cuentas Snowflake"},@@ -2972,26 +2974,6 @@}}},- "setup": {- "basic-info": "Información básica",- "data": {- "built-in": "Utilice la muestra incorporada",- "built-in-desc": "Generar proyecto de muestra e instancias",- "self-setup": "Configurar el proyecto"- },- "purposes": {- "alter-schema": "Alterar esquema",- "query-data": "Consultar datos",- "self": "¿Cuál es su propósito principal con Bytebase?"- },- "self": "Configuración",- "skip-setup": "Saltar configuración",- "workflow": {- "self": "¿Cuál es su flujo de trabajo con la base de datos?",- "simple": "No hay un flujo de trabajo complejo, solo se necesitan herramientas de interfaz de usuario",- "team": "Trabajar con compañeros de equipo, necesita una canalización de CI/CD"- }- },"sheet": {"filter": {"only-show-starred": "Mostrar solo destacadas",@@ -3560,6 +3542,7 @@},"prepare-database-tip": "Selecciona las bases de datos para transferirlas al proyecto.","previous-step-required": "Debes terminar el paso anterior.",+ "product-model": "Cómo funciona Bytebase","self": "Configurar Bytebase","steps": {"database": "Explorar bases de datos",diff --git a/frontend/src/locales/guides/how-bytebase-works.en-US.md b/frontend/src/locales/guides/how-bytebase-works.en-US.mdnew file mode 100644index 0000000000..d55466e13a--- /dev/null+++ b/frontend/src/locales/guides/how-bytebase-works.en-US.md@@ -0,0 +1,13 @@+Bytebase sits between your team and your databases, governing how data is accessed and changed.++- **Workspace:** Everything your team manages together in Bytebase.+- **Project:** Groups databases, people, and workflows. This is where database work happens.+- **Instance:** A database server or cluster connected to Bytebase. One instance can host multiple databases.+- **Database:** An individual database on an instance. Each database belongs to one project.++With a database in a project:++- **Query data:** Use SQL Editor to explore schemas, tables, and data.+- **Change data:** Use a reviewed and recorded workflow instead of making changes directly.++[Learn more about how Bytebase organizes resources](https://docs.bytebase.com/onboarding/organize-resources)diff --git a/frontend/src/locales/guides/how-bytebase-works.es-ES.md b/frontend/src/locales/guides/how-bytebase-works.es-ES.mdnew file mode 100644index 0000000000..34d65bb822--- /dev/null+++ b/frontend/src/locales/guides/how-bytebase-works.es-ES.md@@ -0,0 +1,13 @@+Bytebase se sitúa entre tu equipo y tus bases de datos para gobernar cómo se accede a los datos y cómo se modifican.++- **Espacio de trabajo:** Todo lo que tu equipo administra conjuntamente en Bytebase.+- **Proyecto:** Agrupa bases de datos, personas y flujos de trabajo. Aquí se trabaja con las bases de datos.+- **Instancia:** Un servidor o clúster de bases de datos conectado a Bytebase. Una instancia puede alojar varias bases de datos.+- **Base de datos:** Una base de datos individual dentro de una instancia. Cada base de datos pertenece a un solo proyecto.++Cuando una base de datos pertenece a un proyecto:++- **Consultar datos:** Usa SQL Editor para explorar esquemas, tablas y datos.+- **Cambiar datos:** Usa un flujo de trabajo revisado y registrado en lugar de realizar cambios directamente.++[Más información sobre cómo Bytebase organiza los recursos](https://docs.bytebase.com/onboarding/organize-resources)diff --git a/frontend/src/locales/guides/how-bytebase-works.ja-JP.md b/frontend/src/locales/guides/how-bytebase-works.ja-JP.mdnew file mode 100644index 0000000000..a0847bea6c--- /dev/null+++ b/frontend/src/locales/guides/how-bytebase-works.ja-JP.md@@ -0,0 +1,13 @@+Bytebase はチームとデータベースの間に位置し、データへのアクセスと変更を統制します。++- **ワークスペース:** チームが Bytebase で共同管理するすべてのものです。+- **プロジェクト:** データベース、メンバー、ワークフローをまとめます。データベースに関する作業はここで行います。+- **インスタンス:** Bytebase に接続されたデータベースサーバーまたはクラスターです。1 つのインスタンスで複数のデータベースをホストできます。+- **データベース:** インスタンス上の個々のデータベースです。各データベースは 1 つのプロジェクトに所属します。++データベースをプロジェクトに所属させると:++- **データをクエリ:** SQL Editor でスキーマ、テーブル、データを確認します。+- **データを変更:** データベースを直接変更せず、レビューと記録が行われるワークフローを使用します。++[Bytebase のリソース構成について詳しく見る](https://docs.bytebase.com/onboarding/organize-resources)diff --git a/frontend/src/locales/guides/how-bytebase-works.vi-VN.md b/frontend/src/locales/guides/how-bytebase-works.vi-VN.mdnew file mode 100644index 0000000000..f80bd763ec--- /dev/null+++ b/frontend/src/locales/guides/how-bytebase-works.vi-VN.md@@ -0,0 +1,13 @@+Bytebase nằm giữa nhóm của bạn và các cơ sở dữ liệu, quản trị cách dữ liệu được truy cập và thay đổi.++- **Không gian làm việc:** Mọi thứ nhóm của bạn cùng quản lý trong Bytebase.+- **Dự án:** Nhóm các cơ sở dữ liệu, thành viên và quy trình làm việc. Mọi công việc với cơ sở dữ liệu diễn ra tại đây.+- **Instance:** Máy chủ hoặc cụm cơ sở dữ liệu được kết nối với Bytebase. Một instance có thể lưu trữ nhiều cơ sở dữ liệu.+- **Cơ sở dữ liệu:** Một cơ sở dữ liệu riêng lẻ trên instance. Mỗi cơ sở dữ liệu chỉ thuộc về một dự án.++Khi cơ sở dữ liệu đã thuộc một dự án:++- **Truy vấn dữ liệu:** Dùng SQL Editor để khám phá lược đồ, bảng và dữ liệu.+- **Thay đổi dữ liệu:** Dùng quy trình được xét duyệt và ghi lại thay vì thay đổi trực tiếp.++[Tìm hiểu thêm về cách Bytebase tổ chức tài nguyên](https://docs.bytebase.com/onboarding/organize-resources)diff --git a/frontend/src/locales/guides/how-bytebase-works.zh-CN.md b/frontend/src/locales/guides/how-bytebase-works.zh-CN.mdnew file mode 100644index 0000000000..4858220cf7--- /dev/null+++ b/frontend/src/locales/guides/how-bytebase-works.zh-CN.md@@ -0,0 +1,13 @@+Bytebase 位于你的团队和数据库之间,统一治理数据访问和数据库变更。++- **工作区:** 团队在 Bytebase 中共同管理的所有资源。+- **项目:** 将数据库、成员和工作流组织在一起。数据库相关工作在这里进行。+- **实例:** 连接到 Bytebase 的数据库服务器或集群。一个实例可以托管多个数据库。+- **数据库:** 实例中的单个数据库。每个数据库仅属于一个项目。++数据库位于项目中后:++- **查询数据:** 使用 SQL Editor 探索 Schema、数据表和数据。+- **变更数据:** 使用经过审核并留有记录的工作流,而不是直接修改数据库。++[进一步了解 Bytebase 如何组织资源](https://docs.bytebase.com/onboarding/organize-resources)diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 83d9f7d729..a4e0d4c6dc 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -1221,6 +1221,7 @@"sample-expiration-future_one": "サンプルインスタンスは {{count}} 日後の {{time}} に削除されます。","sample-expiration-future_other": "サンプルインスタンスは {{count}} 日後の {{time}} に削除されます。","sample-project-instance-description": "すぐに使えるデータベースを備えたサンプルプロジェクトインスタンスを 7 日間使用して、Bytebase を試すことができます。",+ "sample-project-instance-description-self-host": "すぐに使えるデータベースを備えたサンプルプロジェクトインスタンスを使用して、Bytebase を試すことができます。","sample-project-instance-title": "サンプルプロジェクトインスタンスを試す","scan-interval": {"default-never": "デフォルト (なし)",@@ -1317,6 +1318,7 @@"type-or-paste-credentials-write-only": "資格情報を入力または貼り付けます - 書き込みのみ","unable-to-connect": "この設定では Bytebase から接続できませんでした。上のガイダンスを確認するか、そのまま続行して後で接続を更新してください。\n\n技術的な詳細: {{0}}","use-sample-instance": "サンプルインスタンスを使用する(7日間利用可能)",+ "use-sample-instance-self-host": "サンプルインスタンスを使用する","users": "ユーザー","your-snowflake-account-locator": "Snowflake アカウント ロケーター"},@@ -2972,26 +2974,6 @@}}},- "setup": {- "basic-info": "基本情報",- "data": {- "built-in": "組み込みサンプルを使用する",- "built-in-desc": "サンプルプロジェクトとインスタンスを生成する",- "self-setup": "プロジェクトのセットアップ"- },- "purposes": {- "alter-schema": "スキーマの変更",- "query-data": "クエリデータ",- "self": "Bytebase の主な目的は何ですか?"- },- "self": "設定",- "skip-setup": "セットアップをスキップ",- "workflow": {- "self": "データベースのワークフローは何ですか?",- "simple": "複雑なワークフローは不要、UIツールだけが必要です",- "team": "チームメイトと協力し、CI/CD パイプラインが必要"- }- },"sheet": {"filter": {"only-show-starred": "スター付きのみ表示",@@ -3560,6 +3542,7 @@},"prepare-database-tip": "プロジェクトに転送するデータベースを選択します。","previous-step-required": "前のステップを先に完了する必要があります。",+ "product-model": "Bytebase の仕組み","self": "Bytebase をセットアップ","steps": {"database": "データベースを探索",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 51ffe5bb93..718a1325c2 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -1221,6 +1221,7 @@"sample-expiration-future_one": "Phiên bản mẫu sẽ bị xóa sau {{count}} ngày, vào {{time}}.","sample-expiration-future_other": "Phiên bản mẫu sẽ bị xóa sau {{count}} ngày, vào {{time}}.","sample-project-instance-description": "Sử dụng Phiên bản dự án mẫu để khám phá Bytebase với cơ sở dữ liệu sẵn sàng sử dụng trong 7 ngày.",+ "sample-project-instance-description-self-host": "Sử dụng Phiên bản dự án mẫu để khám phá Bytebase với cơ sở dữ liệu sẵn sàng sử dụng.","sample-project-instance-title": "Dùng thử Phiên bản dự án mẫu","scan-interval": {"default-never": "Mặc định (không bao giờ)",@@ -1317,6 +1318,7 @@"type-or-paste-credentials-write-only": "Nhập hoặc dán THÔNG TIN XÁC THỰC - chỉ ghi","unable-to-connect": "Bytebase không thể kết nối với các cài đặt này. Hãy xem hướng dẫn ở trên hoặc tiếp tục và cập nhật kết nối sau.\n\nChi tiết kỹ thuật: {{0}}","use-sample-instance": "Sử dụng phiên bản mẫu (Có sẵn trong 7 ngày)",+ "use-sample-instance-self-host": "Sử dụng phiên bản mẫu","users": "Người dùng","your-snowflake-account-locator": "Định vị tài khoản Snowflake của bạn"},@@ -2972,26 +2974,6 @@}}},- "setup": {- "basic-info": "Thông tin cơ bản",- "data": {- "built-in": "Sử dụng mẫu tích hợp",- "built-in-desc": "Tạo dự án mẫu và các trường hợp",- "self-setup": "Thiết lập dự án"- },- "purposes": {- "alter-schema": "Thay đổi lược đồ",- "query-data": "Truy vấn dữ liệu",- "self": "Mục đích chính của bạn khi sử dụng Bytebase là gì?"- },- "self": "Thiết lập",- "skip-setup": "Bỏ qua thiết lập",- "workflow": {- "self": "Quy trình làm việc của bạn với cơ sở dữ liệu là gì?",- "simple": "Không có quy trình làm việc phức tạp, chỉ cần các công cụ UI",- "team": "Làm việc với đồng đội, cần có đường ống CI/CD"- }- },"sheet": {"filter": {"only-show-starred": "Chỉ hiển thị có dấu sao",@@ -3560,6 +3542,7 @@},"prepare-database-tip": "Chọn cơ sở dữ liệu để chuyển vào dự án.","previous-step-required": "Bạn cần hoàn thành bước trước đó.",+ "product-model": "Cách Bytebase hoạt động","self": "Thiết lập Bytebase","steps": {"database": "Khám phá cơ sở dữ liệu",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 9040e466e5..4fd75c9242 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1221,6 +1221,7 @@"sample-expiration-future_one": "示例实例将在 {{count}} 天后的 {{time}} 被移除。","sample-expiration-future_other": "示例实例将在 {{count}} 天后的 {{time}} 被移除。","sample-project-instance-description": "使用示例项目实例探索 Bytebase,并在 7 天内使用预配置的数据库。",+ "sample-project-instance-description-self-host": "使用带有预配置数据库的示例项目实例探索 Bytebase。","sample-project-instance-title": "试用示例项目实例","scan-interval": {"default-never": "默认(永不)",@@ -1317,6 +1318,7 @@"type-or-paste-credentials-write-only": "输入或粘贴 CREDENTIALS - 仅写入","unable-to-connect": "Bytebase 无法使用这些设置连接数据库。请检查上方指引,或继续操作并稍后更新连接。\n\n技术详情:{{0}}","use-sample-instance": "使用示例实例(可用 7 天)",+ "use-sample-instance-self-host": "使用示例实例","users": "用户","your-snowflake-account-locator": "您的 Snowflake 账户定位符"},@@ -2972,26 +2974,6 @@}}},- "setup": {- "basic-info": "基本信息",- "data": {- "built-in": "使用内置示例",- "built-in-desc": "生成示例项目和实例",- "self-setup": "设置项目"- },- "purposes": {- "alter-schema": "变更 Schema",- "query-data": "查询数据",- "self": "您使用 Bytebase 的主要目的是什么?"- },- "self": "设置",- "skip-setup": "跳过设置",- "workflow": {- "self": "您使用数据库的工作流程是怎样的?",- "simple": "无需复杂的工作流程,需要 UI 工具",- "team": "与队友合作,需要 CI/CD 工作流"- }- },"sheet": {"filter": {"only-show-starred": "仅显示收藏",@@ -3560,6 +3542,7 @@},"prepare-database-tip": "选择数据库并转移到项目。","previous-step-required": "你需要先完成上一步。",+ "product-model": "Bytebase 的运作方式","self": "设置 Bytebase","steps": {"database": "浏览数据库",diff --git a/frontend/src/modules/agent/logic/tools/navigate.ts b/frontend/src/modules/agent/logic/tools/navigate.tsindex d5b2f38c6a..2b2bb73cfb 100644--- a/frontend/src/modules/agent/logic/tools/navigate.ts+++ b/frontend/src/modules/agent/logic/tools/navigate.ts@@ -10,7 +10,6 @@ function getRouteMap(router: AppRouterInstance): string[] {if (!path ||path.startsWith("/auth") ||- path === "/setup" ||path === "/403" ||path === "/404") {diff --git a/frontend/src/routes/auth/SetupPage.test.tsx b/frontend/src/routes/auth/SetupPage.test.tsxdeleted file mode 100644index e0230c8158..0000000000--- a/frontend/src/routes/auth/SetupPage.test.tsx+++ /dev/null@@ -1,346 +0,0 @@-import { Code, ConnectError } from "@connectrpc/connect";-import type { ReactElement } from "react";-import { act } from "react";-import { createRoot } from "react-dom/client";-import { beforeEach, describe, expect, test, vi } from "vitest";--(- globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }-).IS_REACT_ACT_ENVIRONMENT = true;--const mocks = vi.hoisted(() => ({- routerIsReady: vi.fn(async () => {}),- routerPush: vi.fn(),- fetchServerInfo: vi.fn(async () => {}),- listRoles: vi.fn(async () => {}),- fetchIamPolicy: vi.fn(async () => {}),- getOrFetchProjectByName: vi.fn(async (): Promise<{ name: string }> => {- throw new ConnectError("not found", Code.NotFound);- }),- createProject: vi.fn(),- setupSample: vi.fn(),- updateWorkspaceProfile: vi.fn(),- resetWorkspaceSetupGuide: vi.fn(),-}));--vi.mock("@/app/router", async (importOriginal) => ({- ...(await importOriginal<typeof import("@/app/router")>()),- router: {- isReady: mocks.routerIsReady,- push: mocks.routerPush,- },-}));--vi.mock("@/stores/app", () => {- const state = {- enableOnboarding: () => true,- appFeatures: { "bb.feature.database-change-mode": 0 },- fetchServerInfo: mocks.fetchServerInfo,- loadWorkspaceProfile: vi.fn(async () => undefined),- listRoles: mocks.listRoles,- fetchWorkspaceIamPolicy: mocks.fetchIamPolicy,- getOrFetchProjectByName: mocks.getOrFetchProjectByName,- createProject: mocks.createProject,- setupSample: mocks.setupSample,- updateWorkspaceProfile: mocks.updateWorkspaceProfile,- resetWorkspaceSetupGuide: mocks.resetWorkspaceSetupGuide,- };- return {- useAppStore: Object.assign(- (selector?: (s: typeof state) => unknown) =>- selector ? selector(state) : state,- { getState: () => state }- ),- };-});--vi.mock("@/components/auth/AuthFooter", () => ({- AuthFooter: () => null,-}));--vi.mock("@/components/BytebaseLogo", () => ({- BytebaseLogo: ({ className }: { className?: string }) => (- <div className={className} data-testid="bytebase-logo" />- ),-}));--vi.mock("@/components/ComponentPermissionGuard", () => ({- ComponentPermissionGuard: ({ children }: { children: React.ReactNode }) =>- children,-}));--vi.mock("@/components/ResourceIdField", async () => {- const React = await import("react");- return {- ResourceIdField: ({- validate,- onValidationChange,- }: {- validate?: (- value: string- ) => Promise<{ type: string; message: string }[]>;- onValidationChange?: (valid: boolean) => void;- }) => {- React.useEffect(() => {- validate?.("new-project").then((messages) => {- onValidationChange?.(messages.length === 0);- });- }, [validate, onValidationChange]);- return React.createElement("div", {- "data-testid": "resource-id-field",- });- },- };-});--vi.mock("react-i18next", () => ({- initReactI18next: { type: "3rdParty", init: () => {} },- useTranslation: () => ({- t: (key: string, vars?: Record<string, unknown>) =>- vars ? `${key}:${JSON.stringify(vars)}` : key,- }),-}));--vi.mock("@/utils/connect", () => ({- getErrorCode: (error: unknown) =>- error instanceof ConnectError ? error.code : Code.Unknown,- extractGrpcErrorMessage: (error: unknown) =>- error instanceof ConnectError ? error.message : String(error),-}));--let SetupPage: typeof import("./SetupPage").SetupPage;--const renderIntoContainer = (element: ReactElement) => {- const container = document.createElement("div");- const root = createRoot(container);- return {- container,- render: () => {- act(() => {- root.render(element);- });- },- unmount: () =>- act(() => {- root.unmount();- }),- };-};--const flushPromises = () =>- act(async () => {- await Promise.resolve();- await Promise.resolve();- await Promise.resolve();- });--beforeEach(async () => {- vi.clearAllMocks();- ({ SetupPage } = await import("./SetupPage"));-});--describe("SetupPage", () => {- test("shows the Bytebase logo above setup steps", async () => {- const { container, render, unmount } = renderIntoContainer(<SetupPage />);- render();- await flushPromises();-- const logo = container.querySelector('[data-testid="bytebase-logo"]');- const stepIndicator = container.querySelector(- '[data-slot="step-indicator"]'- );- expect(logo).toBeTruthy();- expect(logo?.compareDocumentPosition(stepIndicator as Node)).toBe(- Node.DOCUMENT_POSITION_FOLLOWING- );-- unmount();- });-- test("finishes setup by navigating to the workspace landing page", async () => {- const { container, render, unmount } = renderIntoContainer(<SetupPage />);- render();- await flushPromises();-- const buttonByText = (text: string) =>- Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find(- (button) => button.textContent === text- );-- act(() => {- buttonByText("→")?.click();- });- await flushPromises();-- act(() => {- buttonByText("→")?.click();- });- await flushPromises();-- act(() => {- buttonByText("common.confirm")?.click();- });- await flushPromises();-- expect(mocks.routerPush).toHaveBeenLastCalledWith({- name: "workspace.landing",- });- expect(mocks.resetWorkspaceSetupGuide).toHaveBeenCalledTimes(1);-- unmount();- });-- test("aligns the built-in sample radio with its title and styles the description", async () => {- const { container, render, unmount } = renderIntoContainer(<SetupPage />);- render();- await flushPromises();-- const nextButton = () =>- Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find(- (button) => button.textContent === "→"- );-- act(() => {- nextButton()?.click();- });- await flushPromises();-- const title = Array.from(container.querySelectorAll("div")).find(- (element) => element.textContent === "setup.data.built-in"- );- const description = Array.from(container.querySelectorAll("div")).find(- (element) => element.textContent === "setup.data.built-in-desc"- );- const option = title?.closest("label");- const radio = option?.querySelector("[role='radio']");-- expect(option?.className).toContain("items-start");- expect(radio?.className).toContain("mt-0.5");- expect(title?.className).toContain("font-medium");- expect(description?.className).toContain("text-control");-- unmount();- });-- test("aligns default landing page radios with their titles and styles descriptions", async () => {- const { container, render, unmount } = renderIntoContainer(<SetupPage />);- render();- await flushPromises();-- const nextButton = () =>- Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find(- (button) => button.textContent === "→"- );-- act(() => {- nextButton()?.click();- });- await flushPromises();-- act(() => {- nextButton()?.click();- });- await flushPromises();-- const workspaceTitle = Array.from(container.querySelectorAll("div")).find(- (element) =>- element.textContent ===- "settings.general.workspace.default-landing-page.workspace.self"- );- const workspaceDescription = Array.from(- container.querySelectorAll("div")- ).find(- (element) =>- element.textContent ===- "settings.general.workspace.default-landing-page.workspace.description"- );- const option = workspaceTitle?.closest("label");- const radio = option?.querySelector("[role='radio']");-- expect(option?.className).toContain("items-start");- expect(radio?.className).toContain("mt-0.5");- expect(workspaceTitle?.className).toContain("font-medium");- expect(workspaceDescription?.className).toContain("text-control");-- unmount();- });-- test("allows advancing with a new project resource id", async () => {- const { container, render, unmount } = renderIntoContainer(<SetupPage />);- render();- await flushPromises();-- const nextButton = () =>- Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find(- (button) => button.textContent === "→"- );-- expect(nextButton()).toBeTruthy();- act(() => {- nextButton()?.click();- });- await flushPromises();-- expect(mocks.getOrFetchProjectByName).toHaveBeenCalledWith(- "projects/new-project",- true- );- expect(nextButton()?.disabled).toBe(false);-- unmount();- });-- test("allows advancing when project lookup resolves to the unknown placeholder", async () => {- mocks.getOrFetchProjectByName.mockResolvedValueOnce({- name: "projects/-1",- });-- const { container, render, unmount } = renderIntoContainer(<SetupPage />);- render();- await flushPromises();-- const nextButton = () =>- Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find(- (button) => button.textContent === "→"- );-- act(() => {- nextButton()?.click();- });- await flushPromises();-- expect(mocks.getOrFetchProjectByName).toHaveBeenCalledWith(- "projects/new-project",- true- );- expect(nextButton()?.disabled).toBe(false);-- unmount();- });-- test("blocks advancing when project lookup fails for reasons other than NotFound", async () => {- mocks.getOrFetchProjectByName.mockRejectedValueOnce(- new ConnectError("backend unavailable", Code.Unavailable)- );-- const { container, render, unmount } = renderIntoContainer(<SetupPage />);- render();- await flushPromises();-- const nextButton = () =>- Array.from(container.querySelectorAll<HTMLButtonElement>("button")).find(- (button) => button.textContent === "→"- );-- expect(nextButton()).toBeTruthy();- act(() => {- nextButton()?.click();- });- await flushPromises();-- expect(nextButton()).toBeTruthy();- expect(nextButton()?.disabled).toBe(true);-- unmount();- });-});diff --git a/frontend/src/routes/auth/SetupPage.tsx b/frontend/src/routes/auth/SetupPage.tsxdeleted file mode 100644index 500baf4527..0000000000--- a/frontend/src/routes/auth/SetupPage.tsx+++ /dev/null@@ -1,370 +0,0 @@-import { create } from "@bufbuild/protobuf";-import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";-import { Code } from "@connectrpc/connect";-import { Loader2 } from "lucide-react";-import { useCallback, useEffect, useRef, useState } from "react";-import { useTranslation } from "react-i18next";-import { router } from "@/app/router";-import {- SQL_EDITOR_HOME_MODULE,- WORKSPACE_ROUTE_LANDING,-} from "@/app/router/handles";-import { AuthFooter } from "@/components/auth/AuthFooter";-import { BytebaseLogo } from "@/components/BytebaseLogo";-import { ComponentPermissionGuard } from "@/components/ComponentPermissionGuard";-import {- ResourceIdField,- type ResourceIdFieldRef,-} from "@/components/ResourceIdField";-import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";-import { StepIndicator } from "@/components/ui/step-indicator";-import { useAppFeature } from "@/hooks/useAppState";-import { useAppStore } from "@/stores/app";-import { projectNamePrefix } from "@/stores/modules/v1/common";-import { isValidProjectName } from "@/types";-import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";-import { extractGrpcErrorMessage, getErrorCode } from "@/utils/connect";--type Purpose = "edit-schema" | "query-data";-type Workflow = "simple" | "team";-type DataChoice = "self-setup" | "builtin-sample";--const SETUP_PERMISSIONS = [- "bb.settings.get",- "bb.settings.setWorkspaceProfile",- "bb.projects.create",- "bb.roles.list",- "bb.workspaces.getIamPolicy",-] as const;--const homePath = (mode?: DatabaseChangeMode) => {- if (mode === DatabaseChangeMode.EDITOR) {- return { name: SQL_EDITOR_HOME_MODULE };- }- return { name: WORKSPACE_ROUTE_LANDING };-};--export function SetupPage() {- const [ready, setReady] = useState(false);-- useEffect(() => {- (async () => {- await router.isReady();- try {- await Promise.all([- // Force-refresh server info so `enableOnboarding()` reflects the- // post-signup active-user count. This page renders outside any- // shell, so useEnsureWorkspaceCommonData hasn't run.- useAppStore.getState().fetchServerInfo(),- useAppStore.getState().listRoles(),- useAppStore.getState().fetchWorkspaceIamPolicy(),- ]);- } catch (error) {- // Roles/IAM pre-fetch failed — proceed to render the wizard anyway.- // The wizard's own RPC calls surface their errors; blocking setup- // on a prefetch failure leaves the page stuck on a spinner.- console.error("Setup prefetch failed:", error);- }- setReady(true);- })();- }, []);-- return (- <>- <ComponentPermissionGuard permissions={[...SETUP_PERMISSIONS]}>- {ready ? (- <SetupWizard />- ) : (- <div className="w-full h-full flex items-center justify-center">- <Loader2 className="size-6 animate-spin" />- </div>- )}- </ComponentPermissionGuard>- <AuthFooter />- </>- );-}--function SetupWizard() {- const { t } = useTranslation();- const [currentStep, setCurrentStep] = useState(0);- const [purpose, setPurpose] = useState<Purpose>("edit-schema");- const [workflow, setWorkflow] = useState<Workflow>("team");- const [data, setData] = useState<DataChoice>("self-setup");- const [mode, setMode] = useState<DatabaseChangeMode>(- DatabaseChangeMode.PIPELINE- );- const [projectTitle, setProjectTitle] = useState("New Project");- const [resourceId, setResourceId] = useState("");- const [loading, setLoading] = useState(false);-- const resourceFieldRef = useRef<ResourceIdFieldRef>(null);- const [resourceValid, setResourceValid] = useState(false);-- const enableOnboarding = useAppStore((s) => s.enableOnboarding());- const databaseChangeMode = useAppFeature("bb.feature.database-change-mode");-- useEffect(() => {- if (!enableOnboarding) {- router.push(homePath(databaseChangeMode));- }- }, [enableOnboarding, databaseChangeMode]);-- const steps = [- t("setup.basic-info"),- t("setup.self"),- t("settings.general.workspace.default-landing-page.self"),- ];-- const canAdvance = (() => {- if (currentStep === 1 && data === "self-setup") {- return !!projectTitle && resourceValid;- }- return !loading;- })();-- const changeStepIndex = (next: number) => {- if (next === steps.length - 1) {- if (purpose === "query-data" && workflow === "simple") {- setMode(DatabaseChangeMode.EDITOR);- } else {- setMode(DatabaseChangeMode.PIPELINE);- }- }- setCurrentStep(next);- };-- const skip = () => router.push("/");-- const finish = async () => {- if (loading) return;- setLoading(true);- try {- if (data === "self-setup") {- await useAppStore.getState().createProject(projectTitle, resourceId);- } else {- await useAppStore.getState().setupSample();- }- await useAppStore.getState().updateWorkspaceProfile({- payload: { databaseChangeMode: mode },- updateMask: create(FieldMaskSchema, {- paths: ["value.workspace_profile.database_change_mode"],- }),- });- useAppStore.getState().resetWorkspaceSetupGuide();- router.push(homePath(mode));- } finally {- setLoading(false);- }- };-- const validateProjectResourceID = useCallback(- async (id: string) => {- try {- const project = await useAppStore- .getState()- .getOrFetchProjectByName(- `${projectNamePrefix}${id}`,- true /* silent */- );- if (!isValidProjectName(project.name)) {- return [];- }- return [- {- type: "error" as const,- message: t("resource-id.validation.duplicated", {- resource: "project",- }),- },- ];- } catch (error) {- if (getErrorCode(error) === Code.NotFound) {- return [];- }- return [- {- type: "error" as const,- message: extractGrpcErrorMessage(error),- },- ];- }- },- [t]- );- const stepItems = steps.map((title) => ({ title }));-- return (- <div className="w-full mx-auto max-w-2xl py-6 px-4 flex flex-col gap-4">- <BytebaseLogo className="mx-auto mb-6 h-14 max-w-64" />- <div className="sticky top-0 bg-white z-10 pb-4 border-b border-control-border">- <StepIndicator steps={stepItems} currentIndex={currentStep} />- </div>-- {currentStep === 0 && (- <div className="w-full flex flex-col gap-6 py-4">- <div className="flex flex-col gap-y-2">- <p>{t("setup.purposes.self")}</p>- <RadioGroup- value={purpose}- onValueChange={(v) => setPurpose(v as Purpose)}- className="flex-col items-start gap-y-2"- >- <RadioGroupItem value="edit-schema">- {t("setup.purposes.alter-schema")}- </RadioGroupItem>- <RadioGroupItem value="query-data">- {t("setup.purposes.query-data")}- </RadioGroupItem>- </RadioGroup>- </div>- <div className="flex flex-col gap-y-2">- <p>{t("setup.workflow.self")}</p>- <RadioGroup- value={workflow}- onValueChange={(v) => setWorkflow(v as Workflow)}- className="flex-col items-start gap-y-2"- >- <RadioGroupItem value="team">- {t("setup.workflow.team")}- </RadioGroupItem>- <RadioGroupItem value="simple">- {t("setup.workflow.simple")}- </RadioGroupItem>- </RadioGroup>- </div>- </div>- )}-- {currentStep === 1 && (- <div className="w-full flex flex-col gap-2 py-4">- <RadioGroup- value={data}- onValueChange={(v) => setData(v as DataChoice)}- className="flex-col items-start gap-y-6"- >- <div>- <RadioGroupItem value="self-setup">- <div className="font-medium">{t("setup.data.self-setup")}</div>- </RadioGroupItem>- {data === "self-setup" && (- <div className="mt-2 ml-6 flex flex-col gap-y-1">- <Input- value={projectTitle}- required- placeholder={t("project.create-modal.project-name")}- onChange={(e) => setProjectTitle(e.target.value)}- />- <ResourceIdField- suffix- ref={resourceFieldRef}- value={resourceId}- resourceName={t("common.project")}- resourceTitle={projectTitle}- validate={validateProjectResourceID}- onChange={setResourceId}- onValidationChange={setResourceValid}- />- </div>- )}- </div>- <div>- <RadioGroupItem- value="builtin-sample"- className="items-start"- radioClassName="mt-0.5"- >- <div className="flex flex-col gap-1">- <div className="font-medium">{t("setup.data.built-in")}</div>- <div className="text-control">- {t("setup.data.built-in-desc")}- </div>- </div>- </RadioGroupItem>- </div>- </RadioGroup>- </div>- )}-- {currentStep === 2 && (- <div className="py-4 flex flex-col gap-6">- <div className="font-medium">- {t("settings.general.workspace.default-landing-page.self")}- </div>- <RadioGroup- value={String(mode)}- onValueChange={(v) => setMode(Number(v) as DatabaseChangeMode)}- className="flex-col items-start gap-y-6"- >- <RadioGroupItem- value={String(DatabaseChangeMode.PIPELINE)}- className="items-start"- radioClassName="mt-0.5"- >- <div className="flex flex-col gap-1">- <div className="font-medium">- {t(- "settings.general.workspace.default-landing-page.workspace.self"- )}- </div>- <div className="text-control">- {t(- "settings.general.workspace.default-landing-page.workspace.description"- )}- </div>- </div>- </RadioGroupItem>- <RadioGroupItem- value={String(DatabaseChangeMode.EDITOR)}- className="items-start"- radioClassName="mt-0.5"- >- <div className="flex flex-col gap-1">- <div className="font-medium">- {t(- "settings.general.workspace.default-landing-page.sql-editor.self"- )}- </div>- <div className="text-control">- {t(- "settings.general.workspace.default-landing-page.sql-editor.description"- )}- </div>- </div>- </RadioGroupItem>- </RadioGroup>- </div>- )}-- <div className="flex items-center justify-between pt-4 border-t border-control-border">- <Button appearance="secondary" onClick={skip}>- {t("setup.skip-setup")}- </Button>- <div className="flex items-center gap-x-2">- {currentStep > 0 && (- <Button- appearance="outline"- onClick={() => changeStepIndex(currentStep - 1)}- >- ←- </Button>- )}- {currentStep < steps.length - 1 ? (- <Button- onClick={() => changeStepIndex(currentStep + 1)}- disabled={!canAdvance}- >- →- </Button>- ) : (- <Button onClick={finish} disabled={loading}>- {t("common.confirm")}- </Button>- )}- </div>- </div>- </div>- );-}diff --git a/frontend/src/routes/auth/ProfileSetupPage.test.tsx b/frontend/src/routes/auth/WorkspaceSetupPage.test.tsxsimilarity index 74%rename from frontend/src/routes/auth/ProfileSetupPage.test.tsxrename to frontend/src/routes/auth/WorkspaceSetupPage.test.tsxindex 9eab95a2a9..c738823508 100644--- a/frontend/src/routes/auth/ProfileSetupPage.test.tsx+++ b/frontend/src/routes/auth/WorkspaceSetupPage.test.tsx@@ -41,10 +41,19 @@ const mocks = vi.hoisted(() => ({prepareSampleProjectInstance: vi.fn(),setRecentProject: vi.fn(),routerReplace: vi.fn(),+ captureMetric: vi.fn(),pushNotification: vi.fn(),hasWorkspacePermissionV2: vi.fn(() => false),canCreateProject: true,sampleAvailable: true,+ sampleInstances: [] as Array<{ instance: string }>,+ isSaaSMode: false,+}));++vi.mock("@/app/analytics/provider", () => ({+ behaviorAnalytics: {+ captureMetric: mocks.captureMetric,+ },}));vi.mock("@/hooks/useAppState", () => ({@@ -67,7 +76,10 @@ vi.mock("@/stores/app", () => ({updateUser: typeof mocks.updateUser;updateWorkspace: typeof mocks.updateWorkspace;prepareSampleProjectInstance: typeof mocks.prepareSampleProjectInstance;- serverInfo: { sample: { available: boolean } };+ serverInfo: {+ sample: { available: boolean; instances: Array<{ instance: string }> };+ };+ isSaaSMode: () => boolean;}) => unknown) =>selector({@@ -76,8 +88,12 @@ vi.mock("@/stores/app", () => ({updateWorkspace: mocks.updateWorkspace,prepareSampleProjectInstance: mocks.prepareSampleProjectInstance,serverInfo: {- sample: { available: mocks.sampleAvailable },+ sample: {+ available: mocks.sampleAvailable,+ instances: mocks.sampleInstances,+ },},+ isSaaSMode: () => mocks.isSaaSMode,}),}));@@ -107,7 +123,16 @@ vi.mock("@/components/ResourceIdField", async () => {onChange?.("new-project");onValidationChange?.(true);}, [onChange, onValidationChange, resourceTitle]);- return <input data-testid="project-resource-id" readOnly value={value} />;+ return (+ <input+ data-testid="project-resource-id"+ value={value}+ onChange={(event) => {+ onChange?.(event.target.value);+ onValidationChange?.(event.target.value.length > 0);+ }}+ />+ );},};});@@ -148,7 +173,7 @@ vi.mock("react-i18next", () => ({}),}));-let ProfileSetupPage: typeof import("./ProfileSetupPage").ProfileSetupPage;+let WorkspaceSetupPage: typeof import("./WorkspaceSetupPage").WorkspaceSetupPage;const renderIntoContainer = (element: ReactElement) => {const container = document.createElement("div");@@ -172,6 +197,8 @@ beforeEach(async () => {mocks.canUpdateWorkspace = true;mocks.canCreateProject = true;mocks.sampleAvailable = true;+ mocks.sampleInstances = [];+ mocks.isSaaSMode = false;mocks.workspacePolicy = {bindings: [{@@ -187,12 +214,12 @@ beforeEach(async () => {mocks.prepareSampleProjectInstance.mockResolvedValue({name: "projects/new-project/instances/sample",});- ({ ProfileSetupPage } = await import("./ProfileSetupPage"));+ ({ WorkspaceSetupPage } = await import("./WorkspaceSetupPage"));});-describe("ProfileSetupPage", () => {+describe("WorkspaceSetupPage", () => {test("uses the shared product intro query key after creating a project", () => {- const source = readFileSync(join(componentDir, "ProfileSetupPage.tsx"), {+ const source = readFileSync(join(componentDir, "WorkspaceSetupPage.tsx"), {encoding: "utf8",});@@ -206,7 +233,7 @@ describe("ProfileSetupPage", () => {});test("shows workspace name when the sole member can update the workspace", () => {- const page = renderIntoContainer(<ProfileSetupPage />);+ const page = renderIntoContainer(<WorkspaceSetupPage />);page.render();@@ -246,7 +273,7 @@ describe("ProfileSetupPage", () => {},],} as IamPolicy;- const page = renderIntoContainer(<ProfileSetupPage />);+ const page = renderIntoContainer(<WorkspaceSetupPage />);page.render();@@ -258,7 +285,7 @@ describe("ProfileSetupPage", () => {});test("can optionally create a project and continue to its databases page", async () => {- const page = renderIntoContainer(<ProfileSetupPage />);+ const page = renderIntoContainer(<WorkspaceSetupPage />);page.render();@@ -328,8 +355,8 @@ describe("ProfileSetupPage", () => {page.unmount();});- test("creates a project with an empty title when its resource ID remains", async () => {- const page = renderIntoContainer(<ProfileSetupPage />);+ test("allows setup without creating a project when its title is cleared", async () => {+ const page = renderIntoContainer(<WorkspaceSetupPage />);page.render();@@ -343,17 +370,13 @@ describe("ProfileSetupPage", () => {});expect(- (- page.container.querySelector(- "[data-testid='project-resource-id']"- ) as HTMLInputElement- ).value- ).toBe("new-project");+ page.container.querySelector("[data-testid='project-resource-id']")+ ).toBeNull();const sampleCheckbox = page.container.querySelector("[data-testid='enable-sample-databases']") as HTMLButtonElement;- expect(sampleCheckbox).toBeChecked();- expect(sampleCheckbox).not.toHaveAttribute("aria-disabled", "true");+ expect(sampleCheckbox).not.toBeChecked();+ expect(sampleCheckbox).toHaveAttribute("aria-disabled", "true");const save = Array.from(page.container.querySelectorAll("button")).find((button) => button.textContent?.includes("Setup my workspace")@@ -364,25 +387,40 @@ describe("ProfileSetupPage", () => {await Promise.resolve();});- expect(mocks.createProject).toHaveBeenCalledWith("", "new-project");- expect(mocks.prepareSampleProjectInstance).toHaveBeenCalledWith(- "projects/new-project"- );- expect(mocks.setRecentProject).toHaveBeenCalledWith("projects/new-project");+ expect(mocks.createProject).not.toHaveBeenCalled();+ expect(mocks.prepareSampleProjectInstance).not.toHaveBeenCalled();+ expect(mocks.setRecentProject).not.toHaveBeenCalled();expect(mocks.routerReplace).toHaveBeenCalledWith({- name: "workspace.project.database",- params: { projectId: "new-project" },- query: {- syncingInstance: "sample",- intro: "project-instance-synced",- },+ name: "workspace.project",+ query: { intro: "create-project" },+ });++ page.unmount();+ });++ test("requires a project ID while the project title is present", async () => {+ const page = renderIntoContainer(<WorkspaceSetupPage />);++ page.render();++ const projectResourceIdInput = page.container.querySelector(+ "[data-testid='project-resource-id']"+ ) as HTMLInputElement;+ await act(async () => {+ fireEvent.change(projectResourceIdInput, { target: { value: "" } });+ await Promise.resolve();});+ const save = Array.from(page.container.querySelectorAll("button")).find(+ (button) => button.textContent?.includes("Setup my workspace")+ ) as HTMLButtonElement;+ expect(save).toBeDisabled();+page.unmount();});test("does not prepare sample databases when the user opts out", async () => {- const page = renderIntoContainer(<ProfileSetupPage />);+ const page = renderIntoContainer(<WorkspaceSetupPage />);page.render();@@ -418,7 +456,7 @@ describe("ProfileSetupPage", () => {mocks.prepareSampleProjectInstance.mockRejectedValue(new Error("sample target unavailable"));- const page = renderIntoContainer(<ProfileSetupPage />);+ const page = renderIntoContainer(<WorkspaceSetupPage />);page.render();@@ -448,7 +486,7 @@ describe("ProfileSetupPage", () => {test("hides sample database setup when the target is unavailable", () => {mocks.sampleAvailable = false;- const page = renderIntoContainer(<ProfileSetupPage />);+ const page = renderIntoContainer(<WorkspaceSetupPage />);page.render();@@ -461,8 +499,23 @@ describe("ProfileSetupPage", () => {page.unmount();});- test("skips profile setup to the projects page with create project highlighted", async () => {- const page = renderIntoContainer(<ProfileSetupPage />);+ test("hides sample database setup when the workspace already provisioned a sample", () => {+ mocks.sampleInstances = [{ instance: "instances/sample" }];+ const page = renderIntoContainer(<WorkspaceSetupPage />);++ page.render();++ expect(+ page.container.querySelector(+ "[data-testid='enable-sample-databases']"+ )+ ).toBeNull();++ page.unmount();+ });++ test("skips workspace setup to the projects page with create project highlighted", async () => {+ const page = renderIntoContainer(<WorkspaceSetupPage />);page.render();@@ -479,7 +532,47 @@ describe("ProfileSetupPage", () => {name: "workspace.project",query: { intro: "create-project" },});+ expect(mocks.captureMetric).toHaveBeenCalledWith({+ event: "workspace setup skipped",+ properties: { deployment: "self-host" },+ });page.unmount();});++ test.each([+ { isSaaSMode: false, deployment: "self-host" },+ { isSaaSMode: true, deployment: "cloud" },+ ])(+ "records a completed setup for the $deployment deployment",+ async ({ isSaaSMode, deployment }) => {+ mocks.isSaaSMode = isSaaSMode;+ const page = renderIntoContainer(<WorkspaceSetupPage />);++ page.render();++ const submit = Array.from(+ page.container.querySelectorAll("button")+ ).find((button) =>+ button.textContent?.includes("Setup my workspace")+ ) as HTMLButtonElement;+ await act(async () => {+ submit.click();+ await Promise.resolve();+ await Promise.resolve();+ });++ expect(mocks.captureMetric).toHaveBeenCalledWith({+ event: "workspace setup completed",+ properties: {+ deployment,+ project_created: true,+ sample_requested: true,+ sample_succeeded: true,+ },+ });++ page.unmount();+ }+ );});diff --git a/frontend/src/routes/auth/ProfileSetupPage.tsx b/frontend/src/routes/auth/WorkspaceSetupPage.tsxsimilarity index 79%rename from frontend/src/routes/auth/ProfileSetupPage.tsxrename to frontend/src/routes/auth/WorkspaceSetupPage.tsxindex 2f62f135fc..a78d9d6d03 100644--- a/frontend/src/routes/auth/ProfileSetupPage.tsx+++ b/frontend/src/routes/auth/WorkspaceSetupPage.tsx@@ -2,6 +2,8 @@ import { create } from "@bufbuild/protobuf";import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";import { useCallback, useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";+import { createBehaviorMetric } from "@/app/analytics/behavior";+import { behaviorAnalytics } from "@/app/analytics/provider";import { router } from "@/app/router";import {PROJECT_V1_ROUTE_DASHBOARD,@@ -38,7 +40,7 @@ import {} from "@/utils";import { extractGrpcErrorMessage } from "@/utils/connect";-export function ProfileSetupPage() {+export function WorkspaceSetupPage() {const { t } = useTranslation();const currentUser = useCurrentUser();const updateUser = useAppStore((state) => state.updateUser);@@ -49,6 +51,13 @@ export function ProfileSetupPage() {const sampleAvailable = useAppStore((state) => state.serverInfo?.sample?.available ?? false);+ const sampleProvisioned = useAppStore(+ (state) => (state.serverInfo?.sample?.instances.length ?? 0) > 0+ );+ const canPrepareSample = sampleAvailable && !sampleProvisioned;+ const deployment = useAppStore((state) =>+ state.isSaaSMode() ? "cloud" : "self-host"+ );const { createProject, setRecentProject } = useCreateProject();const workspace = useWorkspace();const workspacePolicy = useAppStore((state) => state.workspacePolicy);@@ -87,7 +96,10 @@ export function ProfileSetupPage() {useState(false);const [enableSampleDatabases, setEnableSampleDatabases] = useState(true);const [saving, setSaving] = useState(false);- const shouldCreateProject = canCreateProject && !!projectResourceId;+ const shouldCreateProject = canCreateProject && !!projectTitle.trim();+ const sampleRequested =+ shouldCreateProject && enableSampleDatabases && canPrepareSample;+ const canEnableSample = !!projectTitle.trim() && !!projectResourceId;const validateProjectResourceId = useCallback(async (id: string): Promise<ValidatedMessage[]> => {@@ -114,7 +126,7 @@ export function ProfileSetupPage() {const canSave =!!name.trim() &&!saving &&- (!shouldCreateProject || isProjectResourceIdValid);+ (!shouldCreateProject || (!!projectResourceId && isProjectResourceIdValid));const handleSave = async () => {if (!currentUser?.name || !canSave) return;@@ -137,6 +149,7 @@ export function ProfileSetupPage() {}let createdProjectName = "";let sampleInstanceName = "";+ let sampleSucceeded = false;if (shouldCreateProject) {const createdProject = await createProject(projectTitle.trim(),@@ -144,12 +157,13 @@ export function ProfileSetupPage() {);setRecentProject(createdProject.name);createdProjectName = createdProject.name;- if (enableSampleDatabases && sampleAvailable && createdProject.name) {+ if (sampleRequested && createdProject.name) {try {const sampleInstance = await prepareSampleProjectInstance(createdProject.name);sampleInstanceName = sampleInstance.name;+ sampleSucceeded = true;} catch (error) {pushNotification({module: "bytebase",@@ -165,6 +179,16 @@ export function ProfileSetupPage() {style: "SUCCESS",title: t("settings.profile.setup-success"),});+ behaviorAnalytics.captureMetric(+ createBehaviorMetric("workspace setup completed", {+ properties: {+ deployment,+ project_created: !!createdProjectName,+ sample_requested: sampleRequested,+ sample_succeeded: sampleSucceeded,+ },+ })+ );if (createdProjectName) {const sampleInstanceId =extractInstanceResourceName(sampleInstanceName);@@ -204,6 +228,15 @@ export function ProfileSetupPage() {});};+ const handleSkip = () => {+ behaviorAnalytics.captureMetric(+ createBehaviorMetric("workspace setup skipped", {+ properties: { deployment },+ })+ );+ goToDashboard();+ };+const displayName = name.trim() || currentUser?.email || "?";return (@@ -243,7 +276,7 @@ export function ProfileSetupPage() {<Inputdata-testid="profile-workspace-title"value={workspaceTitle}- onChange={(e) => setWorkspaceTitle(e.target.value)}+ onChange={(event) => setWorkspaceTitle(event.target.value)}placeholder={t("settings.profile.workspace-name-placeholder")}/></FormField>@@ -254,40 +287,41 @@ export function ProfileSetupPage() {<Inputdata-testid="profile-project-title"value={projectTitle}- onChange={(e) => {- const value = e.target.value;- setProjectTitle(value);- }}- placeholder={t("quick-action.new-project")}- />- <ResourceIdField- suffix- value={projectResourceId}- resourceName={t("common.project")}- resourceTitle={projectTitle}- validate={validateProjectResourceId}- onChange={(val) => {- setProjectResourceId(val);- if (!val) {- setEnableSampleDatabases(false);+ onChange={(event) => {+ const title = event.target.value;+ setProjectTitle(title);+ if (!title.trim()) {+ setProjectResourceId("");+ setIsProjectResourceIdValid(false);}}}- onValidationChange={setIsProjectResourceIdValid}+ placeholder={t("project.create-modal.project-name")}/>- {sampleAvailable && (+ {!!projectTitle.trim() && (+ <ResourceIdField+ suffix+ value={projectResourceId}+ resourceName={t("common.project")}+ resourceTitle={projectTitle}+ validate={validateProjectResourceId}+ onChange={setProjectResourceId}+ onValidationChange={setIsProjectResourceIdValid}+ />+ )}+ {canPrepareSample && (<div className="flex items-center gap-x-2 pt-1"><Checkboxid="enable-sample-databases"data-testid="enable-sample-databases"- checked={enableSampleDatabases}- disabled={!shouldCreateProject}+ checked={canEnableSample && enableSampleDatabases}+ disabled={!canEnableSample}onCheckedChange={setEnableSampleDatabases}/><labelhtmlFor="enable-sample-databases"className={cn("cursor-pointer",- !shouldCreateProject &&+ !canEnableSample &&"cursor-not-allowed text-control-placeholder")}>@@ -308,7 +342,7 @@ export function ProfileSetupPage() {</Button><Buttonappearance="secondary"- onClick={goToDashboard}+ onClick={handleSkip}className="w-full">{t("settings.profile.setup-skip")}diff --git a/frontend/src/stores/app/auth.ts b/frontend/src/stores/app/auth.tsindex f022dc05cd..38a4c4df09 100644--- a/frontend/src/stores/app/auth.ts+++ b/frontend/src/stores/app/auth.ts@@ -6,9 +6,8 @@ import { ignoredCodesContextKey, silentContextKey } from "@/api/context-key";import {AUTH_MFA_MODULE,AUTH_PASSWORD_RESET_MODULE,- AUTH_PROFILE_SETUP_MODULE,+ AUTH_SETUP_MODULE,AUTH_SIGNIN_MODULE,- SETUP_MODULE,} from "@/app/router/handles";import {navigateByName,@@ -209,8 +208,8 @@ export const createAuthSlice: AppSliceCreator<AuthSlice> = (set, get) => ({});return;}- if (get().isSaaSMode() && resp.user && needsProfileSetup(resp.user)) {- navigateByName(AUTH_PROFILE_SETUP_MODULE, {+ if (resp.user && needsProfileSetup(resp.user)) {+ navigateByName(AUTH_SETUP_MODULE, {query: { redirect: nextPage },});return;@@ -238,13 +237,13 @@ export const createAuthSlice: AppSliceCreator<AuthSlice> = (set, get) => ({}await get().fetchServerInfo();- // See `login()`. Loaded above the onboarding branch because `SetupPage`- // reads the change mode too, and its skip button navigates to "/".+ // See `login()`. The profile must be available before the next route is+ // selected because the root redirect reads the database change mode.await get().loadWorkspaceProfile(true);set({ authSessionKey: uniqueId() });if (get().enableOnboarding()) {- navigateByName(SETUP_MODULE, { replace: true });+ navigateByName(AUTH_SETUP_MODULE, { replace: true });return;}diff --git a/frontend/src/stores/app/index.test.ts b/frontend/src/stores/app/index.test.tsindex b8e19597bc..689d26e19c 100644--- a/frontend/src/stores/app/index.test.ts+++ b/frontend/src/stores/app/index.test.ts@@ -626,6 +626,32 @@ describe("useAppStore", () => {expect(mocks.navigateToPath).toHaveBeenCalledWith("/", { replace: true });});+ test("self-host first login uses the unified workspace setup route", async () => {+ const firstLoginUser = createProto(UserSchema, {+ ...user,+ title: user.email,+ });+ mocks.login.mockResolvedValue({+ requireResetPassword: false,+ user: firstLoginUser,+ });+ mocks.getCurrentUser.mockResolvedValue(firstLoginUser);+ mocks.getActuatorInfo.mockResolvedValue({+ workspace: user.workspace,+ saas: false,+ });+ mocks.getWorkspace.mockResolvedValue({ name: user.workspace });+ const store = createAppStore();++ await store.getState().login({+ request: { email: user.email, password: "secret" } as never,+ });++ expect(mocks.navigateByName).toHaveBeenCalledWith("auth.setup", {+ query: { redirect: "/" },+ });+ });+// Regression guard: `signup()` used to override the destination with the SQL// Editor whenever the mode read EDITOR, with no check for an explicit// redirect. That branch was dead (signup always boots signed out, so the mode@@ -665,6 +691,48 @@ describe("useAppStore", () => {});});+ test("self-host signup uses the unified workspace setup route", async () => {+ mocks.signup.mockResolvedValue({});+ mocks.getCurrentUser.mockResolvedValue(user);+ mocks.getActuatorInfo.mockResolvedValue({+ workspace: user.workspace,+ userCountInIam: 1,+ saas: false,+ });+ const store = createAppStore();++ await store.getState().signup({+ email: user.email,+ name: "Test",+ password: "secret",+ } as never);++ expect(mocks.navigateByName).toHaveBeenCalledWith("auth.setup", {+ replace: true,+ });+ });++ test("SaaS signup uses the unified workspace setup route", async () => {+ mocks.signup.mockResolvedValue({});+ mocks.getCurrentUser.mockResolvedValue(user);+ mocks.getActuatorInfo.mockResolvedValue({+ workspace: user.workspace,+ userCountInIam: 1,+ saas: true,+ });+ const store = createAppStore();++ await store.getState().signup({+ email: user.email,+ name: "Test",+ password: "secret",+ } as never);++ expect(mocks.navigateByName).toHaveBeenCalledWith("auth.setup", {+ replace: true,+ });+ });+// Guards signup's own `loadWorkspaceProfile` call. The explicit-redirect test// above returns before `rootGuard` is consulted, so it passes with or without// the load; this one pins that a no-redirect signup hands the guard a loaded@@ -2396,6 +2464,10 @@ describe("useAppStore", () => {key: "workspace-setup-guide.query-executed",newState: true,});+ store.getState().saveIntroStateByKey({+ key: "workspace-setup-guide.product-model-seen",+ newState: true,+ });store.getState().saveIntroStateByKey({ key: "unrelated.intro", newState: true });@@ -2415,6 +2487,11 @@ describe("useAppStore", () => {.getState().getIntroStateByKey("workspace-setup-guide.query-executed")).toBe(false);+ expect(+ store+ .getState()+ .getIntroStateByKey("workspace-setup-guide.product-model-seen")+ ).toBe(false);expect(store.getState().getIntroStateByKey("unrelated.intro")).toBe(true);});diff --git a/frontend/src/stores/app/types.ts b/frontend/src/stores/app/types.tsindex b35eb3d4af..57c28431a8 100644--- a/frontend/src/stores/app/types.ts+++ b/frontend/src/stores/app/types.ts@@ -313,7 +313,6 @@ export type WorkspaceSlice = {activeVcsUserCount: () => number;enableOnboarding: () => boolean;workspaceSetupGuideEnabled: () => boolean;- setupSample: () => Promise<void>;// Always returns a profile (never undefined), mirroring the Pinia// `workspaceProfile` getter so consumers read fields without null checks.getWorkspaceProfile: () => WorkspaceProfileSetting;diff --git a/frontend/src/stores/app/workspace.ts b/frontend/src/stores/app/workspace.tsindex 3fb2a3ae95..b636def2ae 100644--- a/frontend/src/stores/app/workspace.ts+++ b/frontend/src/stores/app/workspace.ts@@ -686,7 +686,7 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (activeVcsUserCount: () => get().serverInfo?.activeVcsUserCount ?? 0,- enableOnboarding: () => get().userCountInIam() === 1 && !get().isSaaSMode(),+ enableOnboarding: () => get().userCountInIam() === 1,workspaceSetupGuideEnabled: () =>!get().appFeatures["bb.feature.hide-quick-start"] &&@@ -695,10 +695,6 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (get().hasWorkspacePermission("bb.instances.list") &&get().hasWorkspacePermission("bb.databases.list"),- setupSample: async () => {- await actuatorServiceClientConnect.setupSample({});- },-fetchServerInfo: async () => {const info = await actuatorServiceClientConnect.getActuatorInfo({});set({ serverInfo: info, serverInfoTs: Date.now() });diff --git a/frontend/src/types/proto-es/v1/actuator_service_pb.d.ts b/frontend/src/types/proto-es/v1/actuator_service_pb.d.tsindex bf18e96311..5a3ca4200b 100644--- a/frontend/src/types/proto-es/v1/actuator_service_pb.d.ts+++ b/frontend/src/types/proto-es/v1/actuator_service_pb.d.ts@@ -4,27 +4,13 @@import type { GenFile, GenMessage, GenService } from "@bufbuild/protobuf/codegenv2";import type { Message } from "@bufbuild/protobuf";-import type { EmptySchema, Timestamp } from "@bufbuild/protobuf/wkt";+import type { Timestamp } from "@bufbuild/protobuf/wkt";/*** Describes the file v1/actuator_service.proto.*/export declare const file_v1_actuator_service: GenFile;-/**- * Request message for setting up sample data.- *- * @generated from message bytebase.v1.SetupSampleRequest- */-export declare type SetupSampleRequest = Message<"bytebase.v1.SetupSampleRequest"> & {-};--/**- * Describes the message bytebase.v1.SetupSampleRequest.- * Use `create(SetupSampleRequestSchema)` to create a new message.- */-export declare const SetupSampleRequestSchema: GenMessage<SetupSampleRequest>;-/*** Request message for getting actuator information.*@@ -233,16 +219,5 @@ export declare const ActuatorService: GenService<{input: typeof GetActuatorInfoRequestSchema;output: typeof ActuatorInfoSchema;},- /**- * Sets up sample data for demonstration and testing purposes.- * Permissions required: bb.projects.create- *- * @generated from rpc bytebase.v1.ActuatorService.SetupSample- */- setupSample: {- methodKind: "unary";- input: typeof SetupSampleRequestSchema;- output: typeof EmptySchema;- },}>;diff --git a/frontend/src/types/proto-es/v1/actuator_service_pb.js b/frontend/src/types/proto-es/v1/actuator_service_pb.jsindex 26a2f789f5..d335fc00c9 100644--- a/frontend/src/types/proto-es/v1/actuator_service_pb.js+++ b/frontend/src/types/proto-es/v1/actuator_service_pb.js@@ -7,49 +7,42 @@ import { file_google_api_annotations } from "../google/api/annotations_pb";import { file_google_api_client } from "../google/api/client_pb";import { file_google_api_field_behavior } from "../google/api/field_behavior_pb";import { file_google_api_resource } from "../google/api/resource_pb";-import { file_google_protobuf_empty, file_google_protobuf_timestamp } from "@bufbuild/protobuf/wkt";+import { file_google_protobuf_timestamp } from "@bufbuild/protobuf/wkt";import { file_v1_annotation } from "./annotation_pb";/*** Describes the file v1/actuator_service.proto.*/export const file_v1_actuator_service = /*@__PURE__*/- fileDesc("Chl2MS9hY3R1YXRvcl9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSIUChJTZXR1cFNhbXBsZVJlcXVlc3QiGAoWR2V0QWN0dWF0b3JJbmZvUmVxdWVzdCLRAQoKU2FtcGxlSW5mbxIWCglhdmFpbGFibGUYASABKAhCA+BBAxI4CglpbnN0YW5jZXMYAiADKAsyIC5ieXRlYmFzZS52MS5TYW1wbGVJbmZvLkluc3RhbmNlQgPgQQMacQoISW5zdGFuY2USLwoIaW5zdGFuY2UYASABKAlCHeBBA/pBFwoVYnl0ZWJhc2UuY29tL0luc3RhbmNlEjQKC2V4cGlyZV90aW1lGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDIrEECgxBY3R1YXRvckluZm8SFAoHdmVyc2lvbhgBIAEoCUID4EEDEhcKCmdpdF9jb21taXQYAiABKAlCA+BBAxIRCgRzYWFzGAQgASgIQgPgQQMSGQoMZXh0ZXJuYWxfdXJsGAggASgJQgPgQQMSOQoQbGFzdF9hY3RpdmVfdGltZRgLIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBCA+BBAxIWCgl3b3Jrc3BhY2UYDSABKAlCA+BBAxIgChN1bmxpY2Vuc2VkX2ZlYXR1cmVzGA8gAygJQgPgQQMSJQoYYWN0aXZhdGVkX2luc3RhbmNlX2NvdW50GBQgASgFQgPgQQMSIQoUdG90YWxfaW5zdGFuY2VfY291bnQYFSABKAVCA+BBAxIjChZleHRlcm5hbF91cmxfZnJvbV9mbGFnGBcgASgIQgPgQQMSGgoNcmVwbGljYV9jb3VudBgYIAEoBUID4EEDEhwKD2RlZmF1bHRfcHJvamVjdBgaIAEoCUID4EEDEh4KEXVzZXJfY291bnRfaW5faWFtGBsgASgFQgPgQQMSIgoVYWN0aXZlX3Zjc191c2VyX2NvdW50GBwgASgFQgPgQQMSLAoGc2FtcGxlGB0gASgLMhcuYnl0ZWJhc2UudjEuU2FtcGxlSW5mb0ID4EEDSgQIAxAESgQIBRAISgQICRAKSgQIChALSgQIDBANSgQIDhAPSgQIEBAUSgQIFhAXSgQIGRAaMpcCCg9BY3R1YXRvclNlcnZpY2UScwoPR2V0QWN0dWF0b3JJbmZvEiMuYnl0ZWJhc2UudjEuR2V0QWN0dWF0b3JJbmZvUmVxdWVzdBoZLmJ5dGViYXNlLnYxLkFjdHVhdG9ySW5mbyIg2kEAoOowAYLT5JMCExIRL3YxL2FjdHVhdG9yL2luZm8SjgEKC1NldHVwU2FtcGxlEh8uYnl0ZWJhc2UudjEuU2V0dXBTYW1wbGVSZXF1ZXN0GhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5IkaK6jASYmIucHJvamVjdHMuY3JlYXRlkOowAZjqMAGg6jAEqOowCYLT5JMCGiIYL3YxL2FjdHVhdG9yOnNldHVwU2FtcGxlQqoBCg9jb20uYnl0ZWJhc2UudjFCFEFjdHVhdG9yU2VydmljZVByb3RvUAFaNGdpdGh1Yi5jb20vYnl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_empty, file_google_protobuf_timestamp, file_v1_annotation]);--/**- * Describes the message bytebase.v1.SetupSampleRequest.- * Use `create(SetupSampleRequestSchema)` to create a new message.- */-export const SetupSampleRequestSchema = /*@__PURE__*/- messageDesc(file_v1_actuator_service, 0);+ fileDesc("Chl2MS9hY3R1YXRvcl9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSIYChZHZXRBY3R1YXRvckluZm9SZXF1ZXN0ItEBCgpTYW1wbGVJbmZvEhYKCWF2YWlsYWJsZRgBIAEoCEID4EEDEjgKCWluc3RhbmNlcxgCIAMoCzIgLmJ5dGViYXNlLnYxLlNhbXBsZUluZm8uSW5zdGFuY2VCA+BBAxpxCghJbnN0YW5jZRIvCghpbnN0YW5jZRgBIAEoCUId4EED+kEXChVieXRlYmFzZS5jb20vSW5zdGFuY2USNAoLZXhwaXJlX3RpbWUYAiABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wQgPgQQMisQQKDEFjdHVhdG9ySW5mbxIUCgd2ZXJzaW9uGAEgASgJQgPgQQMSFwoKZ2l0X2NvbW1pdBgCIAEoCUID4EEDEhEKBHNhYXMYBCABKAhCA+BBAxIZCgxleHRlcm5hbF91cmwYCCABKAlCA+BBAxI5ChBsYXN0X2FjdGl2ZV90aW1lGAsgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEhYKCXdvcmtzcGFjZRgNIAEoCUID4EEDEiAKE3VubGljZW5zZWRfZmVhdHVyZXMYDyADKAlCA+BBAxIlChhhY3RpdmF0ZWRfaW5zdGFuY2VfY291bnQYFCABKAVCA+BBAxIhChR0b3RhbF9pbnN0YW5jZV9jb3VudBgVIAEoBUID4EEDEiMKFmV4dGVybmFsX3VybF9mcm9tX2ZsYWcYFyABKAhCA+BBAxIaCg1yZXBsaWNhX2NvdW50GBggASgFQgPgQQMSHAoPZGVmYXVsdF9wcm9qZWN0GBogASgJQgPgQQMSHgoRdXNlcl9jb3VudF9pbl9pYW0YGyABKAVCA+BBAxIiChVhY3RpdmVfdmNzX3VzZXJfY291bnQYHCABKAVCA+BBAxIsCgZzYW1wbGUYHSABKAsyFy5ieXRlYmFzZS52MS5TYW1wbGVJbmZvQgPgQQNKBAgDEARKBAgFEAhKBAgJEApKBAgKEAtKBAgMEA1KBAgOEA9KBAgQEBRKBAgWEBdKBAgZEBoyhgEKD0FjdHVhdG9yU2VydmljZRJzCg9HZXRBY3R1YXRvckluZm8SIy5ieXRlYmFzZS52MS5HZXRBY3R1YXRvckluZm9SZXF1ZXN0GhkuYnl0ZWJhc2UudjEuQWN0dWF0b3JJbmZvIiDaQQCg6jABgtPkkwITEhEvdjEvYWN0dWF0b3IvaW5mb0KqAQoPY29tLmJ5dGViYXNlLnYxQhRBY3R1YXRvclNlcnZpY2VQcm90b1ABWjRnaXRodWIuY29tL2J5dGViYXNlL2J5dGViYXNlL2JhY2tlbmQvZ2VuZXJhdGVkLWdvL3YxogIDQlhYqgILQnl0ZWJhc2UuVjHKAgtCeXRlYmFzZVxWMeICF0J5dGViYXNlXFYxXEdQQk1ldGFkYXRh6gIMQnl0ZWJhc2U6OlYxYgZwcm90bzM", [file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_timestamp, file_v1_annotation]);/*** Describes the message bytebase.v1.GetActuatorInfoRequest.* Use `create(GetActuatorInfoRequestSchema)` to create a new message.*/export const GetActuatorInfoRequestSchema = /*@__PURE__*/- messageDesc(file_v1_actuator_service, 1);+ messageDesc(file_v1_actuator_service, 0);/*** Describes the message bytebase.v1.SampleInfo.* Use `create(SampleInfoSchema)` to create a new message.*/export const SampleInfoSchema = /*@__PURE__*/- messageDesc(file_v1_actuator_service, 2);+ messageDesc(file_v1_actuator_service, 1);/*** Describes the message bytebase.v1.SampleInfo.Instance.* Use `create(SampleInfo_InstanceSchema)` to create a new message.*/export const SampleInfo_InstanceSchema = /*@__PURE__*/- messageDesc(file_v1_actuator_service, 2, 0);+ messageDesc(file_v1_actuator_service, 1, 0);/*** Describes the message bytebase.v1.ActuatorInfo.* Use `create(ActuatorInfoSchema)` to create a new message.*/export const ActuatorInfoSchema = /*@__PURE__*/- messageDesc(file_v1_actuator_service, 3);+ messageDesc(file_v1_actuator_service, 2);/*** ActuatorService manages system health and operational information.diff --git a/frontend/tests/e2e/AGENTS.md b/frontend/tests/e2e/AGENTS.mdindex f9f976db49..ec3c344be0 100644--- a/frontend/tests/e2e/AGENTS.md+++ b/frontend/tests/e2e/AGENTS.md@@ -136,15 +136,13 @@ frontend/tests/e2e/The Bytebase query API is **read-only**. For DDL/DML, use the `execSql` helper (see `masking-exemption.spec.ts`) which shells out to `psql` via Unix socket to the sample Postgres instance.-**Port layout**: the disposable Bytebase server on `PORT` starts sample Postgres at:-- `PORT + 3` → `test-sample-instance` (hr_test)-- `PORT + 4` → `prod-sample-instance` (hr_prod)+**Port layout**: the disposable Bytebase server on `PORT` starts the project-scoped sample Postgres instance (`hr_test`) at `PORT + 3`.Get the correct port from `getInstance(env.instance)` rather than hardcoding the offset.## Known Constraints-- **Sample-data bootstrap**: tests run against data provisioned by `SetupSample` (called from `globalSetup`). The two sample Postgres instances (`test-sample-instance`, `prod-sample-instance`) come up on `PORT+3` / `PORT+4`.+- **Sample-data bootstrap**: `globalSetup` creates `project-sample` and calls `PrepareSampleProjectInstance`. The single project-scoped sample Postgres instance comes up on `PORT+3` with `hr_test`; the setup project adds `hr_prod` on that instance as an E2E-only multi-database fixture.- **License required**: the suite exercises enterprise-only features (masking, JIT, approval workflow, query-data-policy, database groups) and does NOT run on the free plan. Set `BYTEBASE_E2E_LICENSE` to a license JWT signed by Bytebase's license key (ask Bytebase ops for a dev/test license; not stored in this repo); `globalSetup` installs it via `PATCH /v1/subscription/license`. If the env var is absent the bootstrap throws and the whole run stops — there is no per-spec `test.skip` fallback.- **Serial execution**: `fullyParallel: false` + `workers: 1`. Tests within and across files are sequential.- **`psql` dependency**: must be on PATH for DDL/DML setup.diff --git a/frontend/tests/e2e/README.md b/frontend/tests/e2e/README.mdindex 2bf4f50722..ef9fb425a5 100644--- a/frontend/tests/e2e/README.md+++ b/frontend/tests/e2e/README.md@@ -118,8 +118,8 @@ frontend/tests/e2e/## How It Works-1. **`globalSetup`**: Cleans orphaned processes, starts Bytebase + embedded Postgres on a random high port, signs up the admin (`[email protected]` / `12345678`), and calls `SetupSample` to provision the sample project and instances on `PORT+3` / `PORT+4`.-2. **Setup project** (runs as a Playwright test before all others): Logs in as the admin, discovers instances/databases/projects, saves auth state to `.auth/state.json`.+1. **`globalSetup`**: Cleans orphaned processes, starts Bytebase + embedded Postgres on a random high port, signs up the admin (`[email protected]` / `12345678`), creates `project-sample`, and calls `PrepareSampleProjectInstance` to provision its instance on `PORT+3`.+2. **Setup project** (runs as a Playwright test before all others): Logs in as the admin, discovers the sample database, adds `hr_prod` on the same instance for multi-database coverage, and saves auth state to `.auth/state.json`.3. **Tests run**: Each spec file shares one browser context/page (see [AGENTS.md](./AGENTS.md)). Tests call `loadTestEnv()` to get the API client and env data, create their own test data, and run UI-driven verification.4. **`globalTeardown`**: Kills the server process group, removes temp data dir and PID file.diff --git a/frontend/tests/e2e/framework/api-client.ts b/frontend/tests/e2e/framework/api-client.tsindex a4089385f3..a930a436de 100644--- a/frontend/tests/e2e/framework/api-client.ts+++ b/frontend/tests/e2e/framework/api-client.ts@@ -84,8 +84,12 @@ export class BytebaseApiClient {}}- async setupSample(): Promise<void> {- await this.request<unknown>("POST", "/v1/actuator:setupSample", {});+ async prepareSampleProjectInstance(parent: string): Promise<{ name: string }> {+ return this.request<{ name: string }>(+ "POST",+ `/v1/${parent}/instances:prepareSampleProjectInstance`,+ {},+ );}// Generic workspace setting upsert. Mirrors the frontend store's@@ -264,8 +268,9 @@ export class BytebaseApiClient {}// Discovery- async listInstances() {- return this.request<{ instances: { name: string; engine: string; title: string }[] }>("GET", "/v1/instances?pageSize=100&showDeleted=false");+ async listInstances(parent?: string) {+ const collection = parent ? `/v1/${parent}/instances` : "/v1/instances";+ return this.request<{ instances: { name: string; engine: string; title: string }[] }>("GET", `${collection}?pageSize=100&showDeleted=false`);}async listDatabases(parent: string) {@@ -297,6 +302,17 @@ export class BytebaseApiClient {);}+ async updateDatabaseEnvironment(+ databaseFullName: string,+ environment: string,+ ) {+ return this.request<unknown>(+ "PATCH",+ `/v1/${databaseFullName}?updateMask=environment`,+ { name: databaseFullName, environment },+ );+ }+// Policiesasync getPolicy(policyName: string) {try {@@ -506,12 +522,9 @@ export class BytebaseApiClient {try { await this.request<unknown>("DELETE", `/v1/${name}`); } catch { /* ignore */ }}- // Locate a database by short name (e.g., "family_prod") across every- // instance reachable to the test user. Used by tests that need a database- // outside the env-discovered default (e.g., R7 needs both hr_prod and a- // MySQL family_prod).- async findDatabaseByShortName(shortName: string): Promise<{ database: string; instance: string; engine: string } | null> {- const { instances } = await this.listInstances();+ // Locate a database by short name across every instance owned by a project.+ async findDatabaseByShortName(shortName: string, parent: string): Promise<{ database: string; instance: string; engine: string } | null> {+ const { instances } = await this.listInstances(parent);for (const inst of instances) {const { databases } = await this.listDatabases(inst.name);const match = databases.find((d) => d.name.endsWith(`/${shortName}`));diff --git a/frontend/tests/e2e/framework/global-setup.ts b/frontend/tests/e2e/framework/global-setup.tsindex 56da78e05f..7851c7e502 100644--- a/frontend/tests/e2e/framework/global-setup.ts+++ b/frontend/tests/e2e/framework/global-setup.ts@@ -40,10 +40,10 @@ async function globalSetup() {throw err;}- const { baseURL, adminEmail, adminPassword } = server;+ const { baseURL, adminEmail, adminPassword, project, instance } = server;saveTestEnv({baseURL, adminEmail, adminPassword,- project: "", instance: "", instanceId: "", database: "", databaseId: "",+ project, instance, instanceId: instance.split("/").pop()!, database: "", databaseId: "",});}diff --git a/frontend/tests/e2e/framework/mode-start-new-bytebase.ts b/frontend/tests/e2e/framework/mode-start-new-bytebase.tsindex 4fc54b4e4d..1c74b0b745 100644--- a/frontend/tests/e2e/framework/mode-start-new-bytebase.ts+++ b/frontend/tests/e2e/framework/mode-start-new-bytebase.ts@@ -12,6 +12,8 @@ const DEFAULT_TIMEOUT = 300000; // 5 minutes — server startup includes embeddeconst ADMIN_EMAIL = "[email protected]";const ADMIN_PASSWORD = "12345678"; // NOSONAR: e2e fixtureconst ADMIN_TITLE = "Demo";+const SAMPLE_PROJECT_ID = "project-sample";+const SAMPLE_PROJECT_TITLE = "Sample Project";// DBA fixture used as the second approver by plan-detail approval specs.// Previously seeded by the demo dump; now provisioned explicitly post-signup.const DBA_EMAIL = "[email protected]";@@ -137,19 +139,18 @@ async function pollUntil(throw new Error(`${timeoutMessage} Last error: ${cause}`);}-// Bytebase allocates 4 ports based on the main --port value:+// Bytebase allocates 3 ports based on the main --port value:// PORT — main HTTP server// PORT + 2 — embedded metadata Postgres-// PORT + 3 — test-sample-instance Postgres (provisioned via SetupSample)-// PORT + 4 — prod-sample-instance Postgres (provisioned via SetupSample)-// All four must be free before we commit to a base port.+// PORT + 3 — project-scoped sample Postgres+// All three must be free before we commit to a base port.export async function findAvailablePort(): Promise<number> {let port = DEFAULT_PORT;- const offsets = [0, 2, 3, 4];+ const offsets = [0, 2, 3];for (let i = 0; i < 100; i++) {const checks = await Promise.all(offsets.map((o) => checkPort(port + o)));if (checks.every((free) => free)) return port;- port += 5; // skip past all 4 offsets to avoid re-checking conflicting slots+ port += 4; // skip past all 3 offsets to avoid re-checking conflicting slots}throw new Error("Could not find available port range for Bytebase");}@@ -158,6 +159,8 @@ export async function startServer(): Promise<{baseURL: string;adminEmail: string;adminPassword: string;+ project: string;+ instance: string;}> {// License is REQUIRED (the suite is enterprise-only). Verify it's present// BEFORE booting the server, so a missing license fails fast and never@@ -252,36 +255,34 @@ export async function startServer(): Promise<{await api.createUser(DBA_EMAIL, DBA_PASSWORD, DBA_TITLE);await api.addWorkspaceRoleMember(workspace, DBA_EMAIL, DBA_ROLE);- // Phase 4: Provision the sample project + instances on PORT+3 / PORT+4.- // SetupSample is async on the server but returns immediately; sample- // Postgres instances come up shortly after.- await api.setupSample();+ // Phase 4: Create the sample project and provision its instance on PORT+3.+ const sampleProject = await api.createProject(+ SAMPLE_PROJECT_ID,+ SAMPLE_PROJECT_TITLE,+ );+ const sampleInstance = await api.prepareSampleProjectInstance(+ sampleProject.name,+ );- // Wait for both sample instances to register before handing control back —- // tests rely on discovery finding them via listInstances().- const requiredInstances = new Set([- "instances/test-sample-instance",- "instances/prod-sample-instance",- ]);+ // Wait for the project-scoped sample instance to be visible before handing+ // control back. Its resource ID is generated by the sample manager.await pollUntil(async () => {- const { instances } = await api.listInstances();- const found = new Set(instances?.map((i) => i.name) ?? []);- const missing = [...requiredInstances].filter((name) => !found.has(name));- if (missing.length > 0) {- throw new Error(`Missing sample instances: ${missing.join(", ")}`);+ const { instances } = await api.listInstances(sampleProject.name);+ if (!instances?.some((instance) => instance.name === sampleInstance.name)) {+ throw new Error(`Missing sample instance: ${sampleInstance.name}`);}},deadline,500,- "Sample instances did not appear after SetupSample."+ "Sample instance did not appear after PrepareSampleProjectInstance.");// Phase 5: Wait for the sample Postgres backings to accept TCP connections.// listInstances() above only proves the metadata rows exist; the embedded// postgres processes come up shortly after. Tests that psql into these// instances race against startup without this probe.- const samplePorts = [port + 3, port + 4];+ const samplePorts = [port + 3];await pollUntil(async () => {const listening = await Promise.all(samplePorts.map(isPortListening));@@ -292,10 +293,16 @@ export async function startServer(): Promise<{},deadline,500,- "Sample Postgres instances did not start listening on PORT+3 / PORT+4."+ "Sample Postgres instance did not start listening on PORT+3.");- return { baseURL, adminEmail: ADMIN_EMAIL, adminPassword: ADMIN_PASSWORD };+ return {+ baseURL,+ adminEmail: ADMIN_EMAIL,+ adminPassword: ADMIN_PASSWORD,+ project: sampleProject.name,+ instance: sampleInstance.name,+ };}export function stopServer(): void {diff --git a/frontend/tests/e2e/framework/psql.ts b/frontend/tests/e2e/framework/psql.tsindex 3d31b8bd72..fdb94836ca 100644--- a/frontend/tests/e2e/framework/psql.ts+++ b/frontend/tests/e2e/framework/psql.ts@@ -3,8 +3,7 @@ import type { TestEnv } from "./env";import type { BytebaseApiClient } from "./api-client";// Resolve the Postgres port for the database's instance by reading the data-// source from the API. Avoids hardcoding PORT+3 / PORT+4 offsets which would-// break if discovery picks the "test" sample instance instead of "prod".+// source from the API instead of hardcoding the sample Postgres port.export async function getInstancePgPort(env: TestEnv & { api: BytebaseApiClient },): Promise<string> {@@ -35,6 +34,22 @@ export function execSql(dbName: string, port: string, sql: string): void {);}+// Execute a larger SQL script through stdin so it does not hit the operating+// system's command-line length limit.+export function execSqlScript(dbName: string, port: string, sql: string): void {+ execFileSync(+ "psql",+ [+ "-h", "/tmp",+ "-p", port,+ "-U", "bbsample",+ "-d", dbName,+ "-v", "ON_ERROR_STOP=1",+ ],+ { input: sql, stdio: ["pipe", "pipe", "pipe"] },+ );+}+// Run a read query and return the raw scalar/tuple output (tuples-only,// unaligned). Reads as the owner (bbsample), so it reflects the committed// table state — use it as a positive oracle that a write actually landed,diff --git a/frontend/tests/e2e/framework/seed-test-data.ts b/frontend/tests/e2e/framework/seed-test-data.tsindex a0f5a76103..3c9985f9db 100644--- a/frontend/tests/e2e/framework/seed-test-data.ts+++ b/frontend/tests/e2e/framework/seed-test-data.ts@@ -7,7 +7,7 @@ import { BytebaseApiClient } from "./api-client";const TEST_EXTERNAL_URL = "https://e2e.bytebase.test";/**- * Provisions WORKSPACE-LEVEL baseline data on top of `api.setupSample()`.+ * Provisions workspace-level baseline data after the project-scoped sample.* Called once per disposable server boot from setup-project.ts.** Scope is intentionally narrow: only changes that EVERY spec wants. Anydiff --git a/frontend/tests/e2e/framework/setup-project.ts b/frontend/tests/e2e/framework/setup-project.tsindex 825c391fca..5ea5c32d20 100644--- a/frontend/tests/e2e/framework/setup-project.ts+++ b/frontend/tests/e2e/framework/setup-project.ts@@ -2,15 +2,31 @@ import { test as setup, expect } from "@playwright/test";import * as fs from "fs";import * as path from "path";import { loadTestEnv, saveTestEnv } from "./env";+import { execSql, execSqlScript, getInstancePgPort, querySql } from "./psql";import { seedTestData } from "./seed-test-data";const AUTH_FILE = path.join(__dirname, "../../../.auth/state.json");+const SECONDARY_DATABASE_ID = "hr_prod";+const PROD_ENVIRONMENT = "environments/prod";++function loadSampleSeedData(): string {+ const seedDir = path.join(+ __dirname,+ "../../../../backend/component/sample/seed",+ );+ return fs+ .readdirSync(seedDir)+ .filter((file) => file.endsWith(".sql"))+ .sort()+ .map((file) => fs.readFileSync(path.join(seedDir, file), "utf8"))+ .join("\n");+}setup("authenticate and discover", async ({ page }) => {const env = loadTestEnv();await env.api.login(env.adminEmail, env.adminPassword);- // Provision baseline data on top of the new bootstrap's setupSample:+ // Provision baseline data on top of the project-scoped sample bootstrap:// silence the external-URL banner so its wrench-icon button doesn't// shadow the editor's admin wrench locator, and create a secondary// project so the project-switcher CUJ has an alternative target.@@ -40,35 +56,68 @@ setup("authenticate and discover", async ({ page }) => {);});- // Discovery: find first Postgres instance, database, and project- const { instances } = await env.api.listInstances();- const pgInstance = instances?.find(- (i: { engine: string; name: string }) =>- i.engine === "POSTGRES" &&- !i.name.includes("deleted") &&- !i.name.includes("bytebase-meta")- );- if (!pgInstance) {- throw new Error("Discovery failed: no Postgres instance found");- }-- const instance = pgInstance.name;- const instanceId = instance.split("/").pop()!;+ // The global bootstrap records the project-scoped sample instance because+ // the workspace-level ListInstances collection intentionally omits it.+ const { project, instance, instanceId } = env;const { databases } = await env.api.listDatabases(instance);- const db = databases?.find(- (d: { name: string }) =>- !d.name.includes("/postgres") &&- !d.name.includes("/template") &&- !d.name.includes("/bbdev")- ) ?? databases?.[0];+ const db = databases?.find((item) => item.name.endsWith("/hr_test"));if (!db) {- throw new Error(`Discovery failed: no suitable database in ${instance}`);+ throw new Error(`Discovery failed: no hr_test database in ${instance}`);}const database = db.name;const databaseId = database.split("/").pop()!;- const project = (db as { project?: string }).project ?? "";+ if ((db as { project?: string }).project !== project) {+ throw new Error(`Discovery failed: database ${database} is not in ${project}`);+ }++ // Multi-database and multi-stage specs own an explicit second database+ // fixture. The product sample itself remains one project-scoped instance+ // with one hr_test database.+ const pgPort = await getInstancePgPort(env);+ if (+ querySql(+ databaseId,+ pgPort,+ `SELECT 1 FROM pg_database WHERE datname = '${SECONDARY_DATABASE_ID}'`,+ ) !== "1"+ ) {+ execSql(+ databaseId,+ pgPort,+ `CREATE DATABASE ${SECONDARY_DATABASE_ID}`,+ );+ }+ if (+ querySql(+ SECONDARY_DATABASE_ID,+ pgPort,+ "SELECT to_regclass('public.employee')",+ ) !== "employee"+ ) {+ execSqlScript(+ SECONDARY_DATABASE_ID,+ pgPort,+ loadSampleSeedData(),+ );+ }+ await env.api.syncInstance(instance);+ const secondaryDatabase = `${instance}/databases/${SECONDARY_DATABASE_ID}`;+ await expect+ .poll(+ async () => {+ const result = await env.api.listDatabases(instance);+ return result.databases?.some((item) => item.name === secondaryDatabase);+ },+ { timeout: 60_000, message: `${SECONDARY_DATABASE_ID} should be synced` },+ )+ .toBe(true);+ await env.api.transferDatabaseToProject(secondaryDatabase, project);+ await env.api.updateDatabaseEnvironment(+ secondaryDatabase,+ PROD_ENVIRONMENT,+ );saveTestEnv({ ...env, project, instance, instanceId, database, databaseId });diff --git a/frontend/tests/e2e/plan-detail/plan-detail-checks.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-checks.spec.tsindex 9aec7d102f..26e893f2cf 100644--- a/frontend/tests/e2e/plan-detail/plan-detail-checks.spec.ts+++ b/frontend/tests/e2e/plan-detail/plan-detail-checks.spec.ts@@ -169,7 +169,7 @@ test.describe("WARNING-level review rule", () => {});test.describe("ERROR-level review rule with requirePlanCheckNoError=true", () => {- // Product contract observed on free-plan setupSample (2026-05):+ // Product contract observed on the free-plan sample setup (2026-05):// - ERROR check + requirePlanCheckNoError=true: rollout is BLOCKED.// DEPLOY surfaces "Checks must pass. Failed" with helper text// "Failed checks are blocking automatic rollout creation." NOdiff --git a/frontend/tests/e2e/plan-detail/plan-detail-lifecycle.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-lifecycle.spec.tsindex 379561262b..f69f927d07 100644--- a/frontend/tests/e2e/plan-detail/plan-detail-lifecycle.spec.ts+++ b/frontend/tests/e2e/plan-detail/plan-detail-lifecycle.spec.ts@@ -793,10 +793,10 @@ test.describe("A multi-stage rollout advances the header stage by stage to Deplotest.beforeAll(async () => {await setPermissive();const ts = Date.now();- const testDb = await env.api.findDatabaseByShortName("hr_test");- const prodDb = await env.api.findDatabaseByShortName("hr_prod");+ const testDb = await env.api.findDatabaseByShortName("hr_test", env.project);+ const prodDb = await env.api.findDatabaseByShortName("hr_prod", env.project);if (!testDb || !prodDb) {- throw new Error("multi-stage seed needs hr_test + hr_prod sample dbs");+ throw new Error("multi-stage seed needs the hr_test + hr_prod E2E databases");}const sheet = await env.api.createSheet(env.project,diff --git a/frontend/tests/e2e/schema-editor/schema-editor-helpers.ts b/frontend/tests/e2e/schema-editor/schema-editor-helpers.tsindex 2f66c5ed98..e795e8cec1 100644--- a/frontend/tests/e2e/schema-editor/schema-editor-helpers.ts+++ b/frontend/tests/e2e/schema-editor/schema-editor-helpers.ts@@ -10,7 +10,7 @@ export async function createSchemaEditorPlan(env: TestEnv & { api: BytebaseApiClient },prefix: string): Promise<{ projectId: string; planId: string; planName: string }> {- const pg = await env.api.findDatabaseByShortName("hr_test");+ const pg = await env.api.findDatabaseByShortName("hr_test", env.project);if (!pg) throw new Error("hr_test Postgres database not found");const ts = Date.now();diff --git a/frontend/tests/e2e/sql-editor/sql-editor-batch.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-batch.spec.tsindex 67b77deb68..e90c7bdb5a 100644--- a/frontend/tests/e2e/sql-editor/sql-editor-batch.spec.ts+++ b/frontend/tests/e2e/sql-editor/sql-editor-batch.spec.ts@@ -45,16 +45,15 @@ test.afterAll(async () => {});test.describe("Switching DB connection preserves editor content (C4)", () => {- // The disposable server provisions two HR sample databases (hr_prod- // on prod-sample-instance, hr_test on test-sample-instance). We use- // whichever DB env.database resolved to as the source and pick the- // other as the target — the contract is engine-/instance-agnostic.+ // The setup project adds hr_prod beside the hr_test sample database. We use+ // whichever DB env.database resolved to as the source and pick the other as+ // the target — the contract is engine-/instance-agnostic.test("typing into Monaco then switching DBs keeps the SQL body intact", async () => {const sourceShort = env.databaseId;const targetShort = sourceShort === "hr_prod" ? "hr_test" : "hr_prod";- const target = await env.api.findDatabaseByShortName(targetShort);+ const target = await env.api.findDatabaseByShortName(targetShort, env.project);test.skip(!target,`target DB ${targetShort} not present — needs both hr_prod and hr_test`,diff --git a/frontend/tests/e2e/sql-editor/sql-editor-tabs.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-tabs.spec.tsindex b5759f1927..b1b866d6ad 100644--- a/frontend/tests/e2e/sql-editor/sql-editor-tabs.spec.ts+++ b/frontend/tests/e2e/sql-editor/sql-editor-tabs.spec.ts@@ -45,9 +45,8 @@ test.describe("Active tab text tracks the live connection", () => {// - 01-tab-says-hrprod-actually-familyprod.png//// Test environment note: the QA evidence repro was hr_prod → family_prod- // (Postgres → MySQL across instances). The disposable test server's- // --demo seed includes only Postgres sample instances (hr_prod,- // hr_test). This test uses the available pair hr_prod → hr_test.+ // (Postgres → MySQL across instances). The E2E setup adds hr_prod beside the+ // hr_test sample database, so this test uses the pair hr_prod → hr_test.// The bug is engine-agnostic: the title binding has no engine-// specific code path.@@ -61,8 +60,14 @@ test.describe("Active tab text tracks the live connection", () => {let sourceSavedQuery = "";test.beforeAll(async () => {- const source = await env.api.findDatabaseByShortName(SOURCE_DB_SHORT);- const target = await env.api.findDatabaseByShortName(TARGET_DB_SHORT);+ const source = await env.api.findDatabaseByShortName(+ SOURCE_DB_SHORT,+ env.project,+ );+ const target = await env.api.findDatabaseByShortName(+ TARGET_DB_SHORT,+ env.project,+ );if (!source) {throw new Error(`Setup failed: no database named ${SOURCE_DB_SHORT} found in any instance`,diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yamlindex 0e056b9ec4..86bf1c812a 100644--- a/proto/gen/grpc-doc/openapi.yaml+++ b/proto/gen/grpc-doc/openapi.yaml@@ -141,22 +141,6 @@ paths:application/json:schema:$ref: '#/components/schemas/bytebase.v1.ActuatorInfo'- /v1/actuator:setupSample:- post:- tags:- - ActuatorService- summary: SetupSample- description: |-- Sets up sample data for demonstration and testing purposes.- Permissions required: bb.projects.create- operationId: ActuatorService_SetupSample- responses:- "200":- description: Success- content:- application/json:- schema:- $ref: '#/components/schemas/google.protobuf.Empty'/v1/ai/chat:post:tags:@@ -30758,11 +30742,6 @@ components:title: SettingValueadditionalProperties: falsedescription: The data in setting value.- bytebase.v1.SetupSampleRequest:- type: object- title: SetupSampleRequest- additionalProperties: false- description: Request message for setting up sample data.bytebase.v1.Sheet:type: objectproperties:diff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.mdindex c0b06608bb..1c6f12ec61 100644--- a/proto/gen/grpc-doc/store/README.md+++ b/proto/gen/grpc-doc/store/README.md@@ -4198,7 +4198,6 @@ The severity level for SQL review rules.| Field | Type | Label | Description || ----- | ---- | ----- | ----------- |-| database_project_id | [string](#string) | | || instances | [SelfHostSampleInstanceSetupPayload.Instance](#bytebase-store-SelfHostSampleInstanceSetupPayload-Instance) | repeated | |@@ -4220,6 +4219,7 @@ The severity level for SQL review rules.| port_offset | [int32](#int32) | | || database_name | [string](#string) | | || role_name | [string](#string) | | |+| project_id | [string](#string) | optional | |diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.htmlindex ad4a12416e..609579fc14 100644--- a/proto/gen/grpc-doc/store/index.html+++ b/proto/gen/grpc-doc/store/index.html@@ -177,15 +177,15 @@<li><a href="#store%2faccess_grant.proto">store/access_grant.proto</a><ul>-+<li><a href="#bytebase.store.AccessGrant"><span class="badge">M</span>AccessGrant</a></li>-+<li><a href="#bytebase.store.AccessGrantPayload"><span class="badge">M</span>AccessGrantPayload</a></li>-+<li><a href="#bytebase.store.AccessGrant.Status"><span class="badge">E</span>AccessGrant.Status</a>@@ -1693,7 +1693,7 @@<tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr></thead><tbody>-+<tr><td>issue_id</td><td><a href="#int64">int64</a></td>@@ -11862,13 +11862,6 @@ unreadable and the revision carries no sheet name. </p></td></thead><tbody>- <tr>- <td>database_project_id</td>- <td><a href="#string">string</a></td>- <td></td>- <td><p> </p></td>- </tr>-<tr><td>instances</td><td><a href="#bytebase.store.SelfHostSampleInstanceSetupPayload.Instance">SelfHostSampleInstanceSetupPayload.Instance</a></td>@@ -11892,7 +11885,7 @@ unreadable and the revision carries no sheet name. </p></td><tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr></thead><tbody>-+<tr><td>instance_id</td><td><a href="#string">string</a></td>@@ -11935,6 +11928,13 @@ unreadable and the revision carries no sheet name. </p></td><td><p> </p></td></tr>+ <tr>+ <td>project_id</td>+ <td><a href="#string">string</a></td>+ <td>optional</td>+ <td><p> </p></td>+ </tr>+</tbody></table>@@ -15839,4 +15839,3 @@ Used to auto-select workspace on next login instead of requiring a workspace pic</table></body></html>-diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.mdindex 06b9d5d835..3b1b799671 100644--- a/proto/gen/grpc-doc/v1/README.md+++ b/proto/gen/grpc-doc/v1/README.md@@ -37,7 +37,6 @@- [GetActuatorInfoRequest](#bytebase-v1-GetActuatorInfoRequest)- [SampleInfo](#bytebase-v1-SampleInfo)- [SampleInfo.Instance](#bytebase-v1-SampleInfo-Instance)- - [SetupSampleRequest](#bytebase-v1-SetupSampleRequest)- [ActuatorService](#bytebase-v1-ActuatorService)@@ -1221,16 +1220,6 @@ Instance describes one provisioned sample instance.--<a name="bytebase-v1-SetupSampleRequest"></a>--### SetupSampleRequest-Request message for setting up sample data.-----@@ -1246,7 +1235,6 @@ ActuatorService manages system health and operational information.| Method Name | Request Type | Response Type | Description || ----------- | ------------ | ------------- | ------------|| GetActuatorInfo | [GetActuatorInfoRequest](#bytebase-v1-GetActuatorInfoRequest) | [ActuatorInfo](#bytebase-v1-ActuatorInfo) | Gets system information and health status of the Bytebase instance. The workspace is resolved from the authenticated session. Permissions required: None (authentication required) |-| SetupSample | [SetupSampleRequest](#bytebase-v1-SetupSampleRequest) | [.google.protobuf.Empty](#google-protobuf-Empty) | Sets up sample data for demonstration and testing purposes. Permissions required: bb.projects.create |diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.htmlindex 38fe7a7c03..a78f4b668f 100644--- a/proto/gen/grpc-doc/v1/index.html+++ b/proto/gen/grpc-doc/v1/index.html@@ -304,10 +304,6 @@<a href="#bytebase.v1.SampleInfo.Instance"><span class="badge">M</span>SampleInfo.Instance</a></li>- <li>- <a href="#bytebase.v1.SetupSampleRequest"><span class="badge">M</span>SetupSampleRequest</a>- </li>-@@ -4415,13 +4411,6 @@ Format: instances/{instance} or projects/{project}/instances/{instance} </p></td- <h3 id="bytebase.v1.SetupSampleRequest">SetupSampleRequest</h3>- <p>Request message for setting up sample data.</p>-----@@ -4445,14 +4434,6 @@ The workspace is resolved from the authenticated session.Permissions required: None (authentication required)</p></td></tr>- <tr>- <td>SetupSample</td>- <td><a href="#bytebase.v1.SetupSampleRequest">SetupSampleRequest</a></td>- <td><a href="#google.protobuf.Empty">.google.protobuf.Empty</a></td>- <td><p>Sets up sample data for demonstration and testing purposes.-Permissions required: bb.projects.create</p></td>- </tr>-</tbody></table>@@ -4481,16 +4462,6 @@ Permissions required: bb.projects.create</p></td></tr>--- <tr>- <td>SetupSample</td>- <td>POST</td>- <td>/v1/actuator:setupSample</td>- <td></td>- </tr>--</tbody></table>diff --git a/proto/store/store/sample_instance.proto b/proto/store/store/sample_instance.protoindex 7ed6b3449a..f87ef72968 100644--- a/proto/store/store/sample_instance.proto+++ b/proto/store/store/sample_instance.proto@@ -21,8 +21,8 @@ message SelfHostSampleInstanceSetupPayload {int32 port_offset = 4;string database_name = 5;string role_name = 6;+ optional string project_id = 7;}- string database_project_id = 1;- repeated Instance instances = 2;+ repeated Instance instances = 1;}diff --git a/proto/v1/v1/actuator_service.proto b/proto/v1/v1/actuator_service.protoindex 741b7cb0dd..1ffe3b4cd7 100644--- a/proto/v1/v1/actuator_service.proto+++ b/proto/v1/v1/actuator_service.proto@@ -6,7 +6,6 @@ import "google/api/annotations.proto";import "google/api/client.proto";import "google/api/field_behavior.proto";import "google/api/resource.proto";-import "google/protobuf/empty.proto";import "google/protobuf/timestamp.proto";import "v1/annotation.proto";@@ -22,25 +21,8 @@ service ActuatorService {option (google.api.method_signature) = "";option (bytebase.v1.mcp_method_class) = READ;}-- // Sets up sample data for demonstration and testing purposes.- // Permissions required: bb.projects.create- rpc SetupSample(SetupSampleRequest) returns (google.protobuf.Empty) {- option (google.api.http) = {- post: "/v1/actuator:setupSample"- body: ""- };- option (bytebase.v1.permission) = "bb.projects.create";- option (bytebase.v1.auth_method) = IAM;- option (bytebase.v1.audit) = true;- option (bytebase.v1.mcp_method_class) = EXCLUDED;- option (bytebase.v1.mcp_denial_reason) = ADMINISTERS_THE_WORKSPACE;- }}-// Request message for setting up sample data.-message SetupSampleRequest {}-// Request message for getting actuator information.message GetActuatorInfoRequest {}