Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: support UI plan drafts on transactional review workflow (#20924)
p0nyd5674139325d
diff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yamlindex 3d4f0b2e3b..7db533a6ee 100644--- a/backend/api/mcp/gen/openapi.yaml+++ b/backend/api/mcp/gen/openapi.yaml@@ -12875,6 +12875,15 @@ components:title: plan_updaterequired:- planUpdate+ - type: object+ properties:+ reviewSubmission:+ title: review_submission+ description: Review submission event.+ $ref: '#/components/schemas/bytebase.v1.IssueComment.ReviewSubmission'+ title: review_submission+ required:+ - reviewSubmissiontitle: IssueCommentadditionalProperties: falsedescription: A comment on an issue.@@ -12961,6 +12970,11 @@ components:description: |-Plan update event information (snapshot of plan.config.specs beforeand after a PlanService.UpdatePlan call that mutated specs).+ bytebase.v1.IssueComment.ReviewSubmission:+ type: object+ title: ReviewSubmission+ additionalProperties: false+ description: Review submission event information.bytebase.v1.IssueStatus:type: stringtitle: IssueStatusdiff --git a/backend/api/v1/access_grant_service.go b/backend/api/v1/access_grant_service.goindex a6e4cf3d8e..68fe3dc23a 100644--- a/backend/api/v1/access_grant_service.go+++ b/backend/api/v1/access_grant_service.go@@ -260,7 +260,7 @@ func (s *AccessGrantService) CreateAccessGrant(ctx context.Context, request *conreturn nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to get project %v", projectID))}if project != nil {- issue, err := postCreateIssue(ctx, s.store, s.webhookManager, s.licenseService, s.bus, project, creatorEmail, creatorEmail, issue)+ issue, err := startIssueWorkflow(ctx, s.store, s.webhookManager, s.licenseService, s.bus, project, creatorEmail, creatorEmail, issue)if err != nil {return nil, connect.NewError(connect.CodeInternal, err)}diff --git a/backend/api/v1/issue_hook.go b/backend/api/v1/issue_hook.goindex 13a6cd92c4..6934ac7f3c 100644--- a/backend/api/v1/issue_hook.go+++ b/backend/api/v1/issue_hook.go@@ -17,8 +17,9 @@ import ("github.com/bytebase/bytebase/backend/utils")-// postCreateIssue runs post-creation logic for an issue: webhook, approval finding, and auto-approve.-func postCreateIssue(+// startIssueWorkflow starts webhook, approval-finding, and auto-approval work+// after direct creation or draft submission.+func startIssueWorkflow(ctx context.Context,stores *store.Store,webhookManager *webhook.Manager,@@ -29,18 +30,10 @@ func postCreateIssue(creatorEmail string,issue *store.IssueMessage,) (*store.IssueMessage, error) {- // Trigger ISSUE_CREATED webhook.- webhookManager.CreateEvent(ctx, &webhook.Event{- Type: storepb.Activity_ISSUE_CREATED,- Project: webhook.NewProject(project),- IssueCreated: &webhook.EventIssueCreated{- Creator: &webhook.User{- Name: creatorName,- Email: creatorEmail,- },- Issue: webhook.NewIssue(issue),- },- })+ if issue.Type == storepb.Issue_DATABASE_CHANGE {+ recordReviewSubmission(ctx, stores, creatorEmail, issue)+ }+ emitIssueCreated(ctx, webhookManager, project, creatorName, creatorEmail, issue)// Trigger approval finding based on issue type.switch issue.Type {@@ -90,6 +83,35 @@ func postCreateIssue(return issue, nil}+func recordReviewSubmission(ctx context.Context, stores *store.Store, creatorEmail string, issue *store.IssueMessage) {+ if _, err := stores.CreateIssueComments(ctx, creatorEmail, &store.IssueCommentMessage{+ ProjectID: issue.ProjectID,+ IssueUID: issue.UID,+ Payload: &storepb.IssueCommentPayload{+ Event: &storepb.IssueCommentPayload_ReviewSubmission_{+ ReviewSubmission: &storepb.IssueCommentPayload_ReviewSubmission{},+ },+ },+ }); err != nil {+ slog.Warn("failed to create review submission activity",+ slog.String("project", issue.ProjectID), slog.Int64("issue_uid", issue.UID), log.BBError(err))+ }+}++func emitIssueCreated(ctx context.Context, webhookManager *webhook.Manager, project *store.ProjectMessage, creatorName, creatorEmail string, issue *store.IssueMessage) {+ webhookManager.CreateEvent(ctx, &webhook.Event{+ Type: storepb.Activity_ISSUE_CREATED,+ Project: webhook.NewProject(project),+ IssueCreated: &webhook.EventIssueCreated{+ Creator: &webhook.User{+ Name: creatorName,+ Email: creatorEmail,+ },+ Issue: webhook.NewIssue(issue),+ },+ })+}+// completeAccessRequestIssue completes the ACCESS_GRANT/ROLE_GRANT issue.// For ROLE_GRANT issue: grant the privilege and update the status.// For ACCESS_GRANT issue: mark the status as ACTIVE.diff --git a/backend/api/v1/issue_service.go b/backend/api/v1/issue_service.goindex d7a3175a04..3350777b94 100644--- a/backend/api/v1/issue_service.go+++ b/backend/api/v1/issue_service.go@@ -418,33 +418,42 @@ func (s *IssueService) CreateIssue(ctx context.Context, req *connect.Request[v1p}created := falseissueToCreate := issue- existing, err := s.findLinkedIssueForCreate(ctx, issueToCreate)- if err != nil {- return nil, err- }- if existing != nil {- issue = existing+ if issueToCreate.Payload.GetDraft() {+ result, err := s.reviewWorkflow.CreateDraftIssue(ctx, review.CreateDraftIssueInput{+ Workspace: common.GetWorkspaceIDFromContext(ctx),+ Issue: issueToCreate,+ })+ if err != nil {+ return nil, mapDraftCreationError(err)+ }+ issue = result.Issue+ created = result.Created} else {- issue, err = s.store.CreateIssue(ctx, issueToCreate)+ existing, err := s.findLinkedIssueForCreate(ctx, issueToCreate)if err != nil {- if errors.Is(err, store.ErrPlanHasRollout) {- return nil, connect.NewError(connect.CodeFailedPrecondition, errors.New("cannot create a draft issue because the plan already has a rollout"))- }- existing, lookupErr := s.findLinkedIssueForCreate(ctx, issueToCreate)- if lookupErr != nil {- return nil, lookupErr- }- if existing == nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to create issue"))- }+ return nil, err+ }+ if existing != nil {issue = existing} else {- created = true+ issue, err = s.store.CreateIssue(ctx, issueToCreate)+ if err != nil {+ existing, lookupErr := s.findLinkedIssueForCreate(ctx, issueToCreate)+ if lookupErr != nil {+ return nil, lookupErr+ }+ if existing == nil {+ return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to create issue"))+ }+ issue = existing+ } else {+ created = true+ }}}if created && !issue.Payload.GetDraft() {- issue, err = postCreateIssue(ctx, s.store, s.webhookManager, s.licenseService, s.bus, project, user.Name, user.Email, issue)+ issue, err = startIssueWorkflow(ctx, s.store, s.webhookManager, s.licenseService, s.bus, project, user.Name, user.Email, issue)if err != nil {return nil, connect.NewError(connect.CodeInternal, err)}@@ -458,6 +467,25 @@ func (s *IssueService) CreateIssue(ctx context.Context, req *connect.Request[v1preturn connect.NewResponse(converted), nil}+func mapDraftCreationError(err error) error {+ var workflowErr *review.Error+ if !errors.As(err, &workflowErr) {+ return connect.NewError(connect.CodeInternal, err)+ }+ switch workflowErr.Code {+ case review.ErrorNotFound:+ return connect.NewError(connect.CodeNotFound, workflowErr)+ case review.ErrorInvalidAction:+ return connect.NewError(connect.CodeInvalidArgument, workflowErr)+ case review.ErrorFailedPrecondition:+ return connect.NewError(connect.CodeFailedPrecondition, workflowErr)+ case review.ErrorConflict:+ return connect.NewError(connect.CodeAlreadyExists, workflowErr)+ default:+ return connect.NewError(connect.CodeInternal, workflowErr)+ }+}+func (s *IssueService) findLinkedIssueForCreate(ctx context.Context, issue *store.IssueMessage) (*store.IssueMessage, error) {if issue.Type != storepb.Issue_DATABASE_CHANGE || issue.PlanUID == nil {return nil, nil@@ -586,14 +614,11 @@ func (s *IssueService) buildIssueMessage(ctx context.Context, project *store.Proif plan == nil {return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("plan %d not found in project %s", planID, project.ResourceID))}- if request.Issue.GetDraft() {- if err := validateDraftReviewPlan(plan); err != nil {- return nil, connect.NewError(connect.CodeInvalidArgument, err)- }- }- for _, spec := range plan.Config.GetSpecs() {- if spec.GetExportDataConfig() != nil {- return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("data export issue creation is no longer supported"))+ if !request.Issue.GetDraft() {+ for _, spec := range plan.Config.GetSpecs() {+ if spec.GetExportDataConfig() != nil {+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("data export issue creation is no longer supported"))+ }}}planUID = &plan.UID@@ -641,40 +666,6 @@ func (s *IssueService) buildIssueMessage(ctx context.Context, project *store.Proreturn issue, nil}-func validateDraftReviewPlan(plan *store.PlanMessage) error {- if plan.Deleted {- return errors.Errorf("draft issues require an active plan")- }- specs := plan.Config.GetSpecs()- if len(specs) == 0 {- return errors.Errorf("draft issues require a database plan")- }-- var kind string- for _, spec := range specs {- var specKind string- switch config := spec.Config.(type) {- case *storepb.PlanConfig_Spec_CreateDatabaseConfig:- specKind = "create database"- case *storepb.PlanConfig_Spec_ChangeDatabaseConfig:- if config.ChangeDatabaseConfig.GetRelease() != "" {- return errors.Errorf("draft issues are not supported for GitOps plans")- }- specKind = "change database"- case *storepb.PlanConfig_Spec_ExportDataConfig:- return errors.Errorf("draft issues are not supported for export plans")- default:- return errors.Errorf("draft issues require a database plan")- }- if kind == "" {- kind = specKind- } else if kind != specKind {- return errors.Errorf("draft issues are not supported for mixed plans")- }- }- return nil-}-func (s *IssueService) getSubmittedIssueForApprovalAction(ctx context.Context, name string) (*store.IssueMessage, error) {issue, err := s.getIssueMessage(ctx, name)if err != nil {@@ -687,7 +678,7 @@ func (s *IssueService) getSubmittedIssueForApprovalAction(ctx context.Context, n}// RetryIssueApproval re-runs approval-template finding for an issue stuck-// in CHECKING. The synchronous post-create path in `postCreateIssue`+// in CHECKING. The synchronous workflow-start path in `startIssueWorkflow`// swallows errors (e.g. CEL evaluation failure against a malformed// workspace approval rule), and there is no event-driven retry for// non-DATABASE_CHANGE issue types — once stuck, only this RPC (or a@@ -846,14 +837,40 @@ func (s *IssueService) UpdateIssue(ctx context.Context, req *connect.Request[v1preturn nil, connect.NewError(connect.CodeNotFound, errors.Errorf("project %s not found", issue.ProjectID))}+ submitting := false+ labelsForSubmission := store.CanonicalizeIssueLabels(issue.Payload.GetLabels())+ labelsSetForSubmission := false+ for _, path := range req.Msg.UpdateMask.Paths {+ switch path {+ case "labels":+ labelsForSubmission = store.CanonicalizeIssueLabels(req.Msg.Issue.Labels)+ labelsSetForSubmission = true+ case "draft":+ if req.Msg.Issue.GetDraft() {+ if !issue.Payload.GetDraft() {+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.New("a submitted issue cannot be changed back to draft"))+ }+ } else if issue.Payload.GetDraft() {+ submitting = true+ }+ default:+ // Other update paths do not affect draft submission preparation.+ }+ }++ expectedDraft := issue.Payload.GetDraft()metadataInput := review.UpdateIssueMetadataInput{- Workspace: common.GetWorkspaceIDFromContext(ctx),- ProjectID: issue.ProjectID,- IssueUID: issue.UID,+ Workspace: common.GetWorkspaceIDFromContext(ctx),+ ProjectID: issue.ProjectID,+ IssueUID: issue.UID,+ ExpectedDraft: &expectedDraft,}hasMetadataPatch := falsevar issueCommentCreates []*store.IssueCommentMessagefor _, path := range req.Msg.UpdateMask.Paths {+ if issue.Payload.GetDraft() && (path == "title" || path == "description") {+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("draft issue %s metadata must be updated through its Plan", req.Msg.Issue.Name))+ }switch path {case "title":trimmed := strings.TrimSpace(req.Msg.Issue.Title)@@ -868,10 +885,13 @@ func (s *IssueService) UpdateIssue(ctx context.Context, req *connect.Request[v1phasMetadataPatch = truecase "labels":- labels := append([]string(nil), req.Msg.Issue.Labels...)- metadataInput.Labels = &labels- hasMetadataPatch = true-+ if !submitting {+ labels := append([]string(nil), req.Msg.Issue.Labels...)+ metadataInput.Labels = &labels+ hasMetadataPatch = true+ }+ case "draft":+ // Submission is committed below through the review workflow.default:}}@@ -879,7 +899,7 @@ func (s *IssueService) UpdateIssue(ctx context.Context, req *connect.Request[v1pif hasMetadataPatch {result, err := s.reviewWorkflow.UpdateIssueMetadata(ctx, metadataInput)if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Wrap(err, "failed to update issue"))+ return nil, mapIssueSubmissionError(err)}issue = result.Issuefor _, event := range result.Events {@@ -928,6 +948,24 @@ func (s *IssueService) UpdateIssue(ctx context.Context, req *connect.Request[v1p}}+ var submissionResult *review.SubmitIssueResult+ if submitting {+ submissionResult, err = s.reviewWorkflow.SubmitIssue(ctx, review.SubmitIssueInput{+ Workspace: common.GetWorkspaceIDFromContext(ctx),+ ProjectID: issue.ProjectID,+ IssueUID: issue.UID,+ Labels: labelsForSubmission,+ LabelsSet: labelsSetForSubmission,+ })+ if err != nil {+ return nil, mapIssueSubmissionError(err)+ }+ issue = submissionResult.Issue+ if submissionResult.LabelsChanged {+ issueCommentCreates = append(issueCommentCreates, newIssueLabelsUpdateComment(issue.UID, submissionResult.PreviousLabels, labelsForSubmission))+ }+ }+for _, ic := range issueCommentCreates {ic.ProjectID = issue.ProjectID}@@ -935,6 +973,21 @@ func (s *IssueService) UpdateIssue(ctx context.Context, req *connect.Request[v1pslog.Warn("failed to create issue comments", "issue id", issue.UID, log.BBError(err))}+ if submissionResult != nil {+ for _, event := range submissionResult.Events {+ switch event.(type) {+ case review.SubmittedEvent:+ recordReviewSubmission(ctx, s.store, user.Email, issue)+ case review.IssueCreatedEvent:+ emitIssueCreated(ctx, s.webhookManager, submissionResult.Project, user.Name, user.Email, issue)+ case review.ApprovalCheckEvent:+ s.bus.ApprovalCheckChan <- bus.IssueRef{ProjectID: issue.ProjectID, UID: issue.UID}+ default:+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("unexpected submission event %T", event))+ }+ }+ }+issueV1, err := s.convertToIssue(issue)if err != nil {return nil, connect.NewError(connect.CodeInternal, errors.Wrapf(err, "failed to convert to issue"))@@ -942,6 +995,41 @@ func (s *IssueService) UpdateIssue(ctx context.Context, req *connect.Request[v1preturn connect.NewResponse(issueV1), nil}+func newIssueLabelsUpdateComment(issueUID int64, fromLabels, toLabels []string) *store.IssueCommentMessage {+ return &store.IssueCommentMessage{+ IssueUID: issueUID,+ Payload: &storepb.IssueCommentPayload{+ Event: &storepb.IssueCommentPayload_IssueUpdate_{+ IssueUpdate: &storepb.IssueCommentPayload_IssueUpdate{+ FromLabels: fromLabels,+ ToLabels: toLabels,+ },+ },+ },+ }+}++func mapIssueSubmissionError(err error) error {+ var workflowErr *review.Error+ if !errors.As(err, &workflowErr) {+ return connect.NewError(connect.CodeInternal, err)+ }+ switch workflowErr.Code {+ case review.ErrorNotFound:+ return connect.NewError(connect.CodeNotFound, workflowErr)+ case review.ErrorInvalidAction:+ return connect.NewError(connect.CodeInvalidArgument, workflowErr)+ case review.ErrorFailedPrecondition:+ return connect.NewError(connect.CodeFailedPrecondition, workflowErr)+ case review.ErrorPermissionDenied:+ return connect.NewError(connect.CodePermissionDenied, workflowErr)+ case review.ErrorConflict:+ return connect.NewError(connect.CodeAborted, workflowErr)+ default:+ return connect.NewError(connect.CodeInternal, workflowErr)+ }+}+// BatchUpdateIssuesStatus batch updates issues status.func (s *IssueService) BatchUpdateIssuesStatus(ctx context.Context, req *connect.Request[v1pb.BatchUpdateIssuesStatusRequest]) (*connect.Response[v1pb.BatchUpdateIssuesStatusResponse], error) {user, ok := GetUserFromContext(ctx)diff --git a/backend/api/v1/issue_service_converter.go b/backend/api/v1/issue_service_converter.goindex bac26dc3fc..bf26c5207d 100644--- a/backend/api/v1/issue_service_converter.go+++ b/backend/api/v1/issue_service_converter.go@@ -306,6 +306,10 @@ func convertToIssueComment(issueName string, ic *store.IssueCommentMessage) *v1pr.Event = convertToIssueCommentEventApproval(e)case *storepb.IssueCommentPayload_IssueUpdate_:r.Event = convertToIssueCommentEventIssueUpdate(e)+ case *storepb.IssueCommentPayload_ReviewSubmission_:+ r.Event = &v1pb.IssueComment_ReviewSubmission_{+ ReviewSubmission: &v1pb.IssueComment_ReviewSubmission{},+ }case *storepb.IssueCommentPayload_PlanUpdate_:projectID, _, _ := common.GetProjectIDIssueUID(issueName)r.Event = convertToIssueCommentEventPlanUpdate(projectID, e)diff --git a/backend/api/v1/issue_service_test.go b/backend/api/v1/issue_service_test.goindex e050973a5a..9006b66567 100644--- a/backend/api/v1/issue_service_test.go+++ b/backend/api/v1/issue_service_test.go@@ -2,9 +2,11 @@ package v1import ("context"+ "database/sql""fmt""sync""testing"+ "time""connectrpc.com/connect""github.com/stretchr/testify/assert"@@ -16,6 +18,7 @@ import ("github.com/bytebase/bytebase/backend/common/testcontainer""github.com/bytebase/bytebase/backend/component/bus""github.com/bytebase/bytebase/backend/component/review"+ "github.com/bytebase/bytebase/backend/component/webhook"storepb "github.com/bytebase/bytebase/backend/generated-go/store"v1pb "github.com/bytebase/bytebase/backend/generated-go/v1""github.com/bytebase/bytebase/backend/migrator"@@ -24,6 +27,107 @@ import (_ "github.com/bytebase/bytebase/backend/plugin/db/pg")+func TestDraftLabelUpdateConflictsWithConcurrentSubmission(t *testing.T) {+ ctx := issueServiceTestContext()+ stores := setupIssueServiceTestStore(ctx, t)+ service := newIssueServiceForTest(t, stores)+ draft := createReadyDraftForUpdateTest(ctx, t, stores, service, "label submission race")++ tx, err := stores.GetDB().BeginTx(ctx, nil)+ require.NoError(t, err)+ defer tx.Rollback()+ var lockedUID int64+ require.NoError(t, tx.QueryRowContext(ctx, `+ SELECT id FROM issue+ WHERE project = $1 AND id = $2+ FOR UPDATE`, draft.ProjectID, draft.UID).Scan(&lockedUID))++ updateResult := make(chan error, 1)+ go func() {+ _, err := service.UpdateIssue(ctx, connect.NewRequest(&v1pb.UpdateIssueRequest{+ Issue: &v1pb.Issue{+ Name: common.FormatIssue(draft.ProjectID, draft.UID), Labels: []string{"environment:staging"},+ },+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"labels"}},+ }))+ updateResult <- err+ }()+ waitForTransactionBlock(ctx, t, stores.GetDB(), tx)+ _, err = tx.ExecContext(ctx, `+ UPDATE issue+ SET payload = payload || jsonb_build_object('draft', false)+ WHERE project = $1 AND id = $2`, draft.ProjectID, draft.UID)+ require.NoError(t, err)+ require.NoError(t, tx.Commit())++ select {+ case err := <-updateResult:+ require.Equal(t, connect.CodeAborted, connect.CodeOf(err))+ case <-time.After(5 * time.Second):+ t.Fatal("draft label update did not return")+ }+ stored := getIssueForTest(ctx, t, stores, draft.UID)+ require.False(t, stored.Payload.GetDraft())+ require.Equal(t, []string{"team:database"}, stored.Payload.GetLabels())+ comments, err := stores.ListIssueComment(ctx, &store.FindIssueCommentMessage{+ ProjectID: draft.ProjectID, IssueUID: &draft.UID,+ })+ require.NoError(t, err)+ require.Empty(t, comments)+ require.Empty(t, service.bus.ApprovalCheckChan)+}++func TestConcurrentSubmissionWithLabelsWritesOneAuditComment(t *testing.T) {+ ctx := issueServiceTestContext()+ stores := setupIssueServiceTestStore(ctx, t)+ service := newIssueServiceForTest(t, stores)+ draft := createReadyDraftForUpdateTest(ctx, t, stores, service, "concurrent labels")++ type outcome struct {+ response *connect.Response[v1pb.Issue]+ err error+ }+ start := make(chan struct{})+ results := make(chan outcome, 2)+ var wg sync.WaitGroup+ for range 2 {+ wg.Go(func() {+ <-start+ response, err := service.UpdateIssue(ctx, connect.NewRequest(&v1pb.UpdateIssueRequest{+ Issue: &v1pb.Issue{+ Name: common.FormatIssue(draft.ProjectID, draft.UID), Labels: []string{"environment:prod"},+ },+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"labels", "draft"}},+ }))+ results <- outcome{response: response, err: err}+ })+ }+ close(start)+ wg.Wait()+ close(results)+ for result := range results {+ require.NoError(t, result.err)+ require.False(t, result.response.Msg.GetDraft())+ }+ comments, err := stores.ListIssueComment(ctx, &store.FindIssueCommentMessage{+ ProjectID: draft.ProjectID, IssueUID: &draft.UID,+ })+ require.NoError(t, err)+ var labelUpdates, submissions int+ for _, comment := range comments {+ switch comment.Payload.Event.(type) {+ case *storepb.IssueCommentPayload_IssueUpdate_:+ labelUpdates+++ case *storepb.IssueCommentPayload_ReviewSubmission_:+ submissions+++ default:+ }+ }+ require.Equal(t, 1, labelUpdates)+ require.Equal(t, 1, submissions)+ require.Len(t, service.bus.ApprovalCheckChan, 1)+}+func TestUpdateIssueLabelsResetsApprovalBeforeRollout(t *testing.T) {ctx := issueServiceTestContext()stores := setupIssueServiceTestStore(ctx, t)@@ -867,8 +971,8 @@ func TestCreateDraftIssueIsIdempotent(t *testing.T) {})require.NoError(t, err)require.Len(t, issues, 1)- require.Equal(t, "original title", issues[0].Title)- require.Equal(t, "original description", issues[0].Description)+ require.Equal(t, plan.Name, issues[0].Title)+ require.Equal(t, plan.Description, issues[0].Description)require.Equal(t, []string{"original"}, issues[0].Payload.GetLabels())concurrentPlan, err := stores.CreatePlan(ctx, &store.PlanMessage{@@ -1333,7 +1437,7 @@ func newIssueServiceForTest(t *testing.T, stores *store.Store) *IssueService {b, err := bus.New()require.NoError(t, err)- return NewIssueService(stores, nil, b, nil, nil)+ return NewIssueService(stores, webhook.NewManager(stores, nil), b, nil, nil)}func createIssueServiceApprovalIssue(ctx context.Context, t *testing.T, stores *store.Store) (*store.PlanMessage, *store.IssueMessage) {@@ -1462,3 +1566,71 @@ func getIssueForTest(ctx context.Context, t *testing.T, stores *store.Store, issrequire.NotNil(t, got)return got}++func createReadyDraftForUpdateTest(+ ctx context.Context,+ t *testing.T,+ stores *store.Store,+ service *IssueService,+ title string,+) *store.IssueMessage {+ t.Helper()+ plan, err := stores.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a", Name: title,+ Config: &storepb.PlanConfig{Specs: []*storepb.PlanConfig_Spec{{+ Config: &storepb.PlanConfig_Spec_ChangeDatabaseConfig{+ ChangeDatabaseConfig: &storepb.PlanConfig_ChangeDatabaseConfig{+ Targets: []string{"instances/prod/databases/app"}, SheetSha256: "sheet",+ },+ },+ }}},+ }, "[email protected]")+ require.NoError(t, err)+ response, err := service.CreateIssue(ctx, connect.NewRequest(&v1pb.CreateIssueRequest{+ Parent: "projects/project-a",+ Issue: &v1pb.Issue{+ Type: v1pb.Issue_DATABASE_CHANGE, Plan: common.FormatPlan("project-a", plan.UID),+ Labels: []string{"team:database"}, Draft: true,+ },+ }))+ require.NoError(t, err)+ _, issueUID, err := common.GetProjectIDIssueUID(response.Msg.GetName())+ require.NoError(t, err)+ created, err := stores.CreatePlanCheckRun(ctx, &store.PlanCheckRunMessage{+ ProjectID: plan.ProjectID, PlanUID: plan.UID,+ Result: &storepb.PlanCheckRunResult{ApprovalInputVersion: plan.Config.GetApprovalInputVersion()},+ })+ require.NoError(t, err)+ require.True(t, created)+ run, err := stores.GetPlanCheckRun(ctx, plan.ProjectID, plan.UID)+ require.NoError(t, err)+ require.NoError(t, stores.UpdatePlanCheckRun(ctx, plan.ProjectID, store.PlanCheckRunStatusDone, &storepb.PlanCheckRunResult{+ ApprovalInputVersion: plan.Config.GetApprovalInputVersion(),+ Results: []*storepb.PlanCheckRunResult_Result{{+ Type: storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_ADVISE, Status: storepb.Advice_SUCCESS,+ }},+ }, run.UID))+ return getIssueForTest(ctx, t, stores, issueUID)+}++func waitForTransactionBlock(ctx context.Context, t *testing.T, db *sql.DB, tx *sql.Tx) {+ t.Helper()+ var blockerPID int+ require.NoError(t, tx.QueryRowContext(ctx, "SELECT pg_backend_pid()").Scan(&blockerPID))+ deadline := time.Now().Add(5 * time.Second)+ for {+ var waiting int+ require.NoError(t, db.QueryRowContext(ctx, `+ SELECT count(*)+ FROM pg_stat_activity AS activity+ WHERE activity.pid <> pg_backend_pid()+ AND $1 = ANY(pg_blocking_pids(activity.pid))`, blockerPID).Scan(&waiting))+ if waiting >= 1 {+ return+ }+ if time.Now().After(deadline) {+ t.Fatalf("timed out waiting for a session blocked by transaction PID %d", blockerPID)+ }+ time.Sleep(10 * time.Millisecond)+ }+}diff --git a/backend/api/v1/plan_service.go b/backend/api/v1/plan_service.goindex 8075422247..90d24597af 100644--- a/backend/api/v1/plan_service.go+++ b/backend/api/v1/plan_service.go@@ -93,10 +93,11 @@ func (s *PlanService) ListPlans(ctx context.Context, request *connect.Request[v1limitPlusOne := offset.limit + 1find := &store.FindPlanMessage{- Workspace: common.GetWorkspaceIDFromContext(ctx),- Limit: &limitPlusOne,- Offset: &offset.offset,- ProjectID: projectID,+ Workspace: common.GetWorkspaceIDFromContext(ctx),+ Limit: &limitPlusOne,+ Offset: &offset.offset,+ ProjectID: projectID,+ ExcludeMalformedUIPlans: true,}if req.Filter != "" {@@ -295,7 +296,7 @@ func (s *PlanService) UpdatePlan(ctx context.Context, request *connect.Request[vreturn nil, connect.NewError(connect.CodePermissionDenied, errors.Errorf("permission denied to update plan"))}- planUpdate := &store.UpdatePlanMessage{UID: oldPlan.UID, ProjectID: oldPlan.ProjectID}+ planUpdate := &store.UpdatePlanMessage{}var specs []*storepb.PlanConfig_Specvar planCheckRunsTrigger bool@@ -336,33 +337,30 @@ func (s *PlanService) UpdatePlan(ctx context.Context, request *connect.Request[v}}- var updateResult *review.UpdatePlanSpecsResult- var updatedPlan *store.PlanMessage+ var specsUpdate *[]*storepb.PlanConfig_Specif planCheckRunsTrigger {- updateResult, err = s.reviewWorkflow.UpdatePlanSpecs(ctx, review.UpdatePlanSpecsInput{- Workspace: common.GetWorkspaceIDFromContext(ctx),- PlanUID: oldPlan.UID,- ProjectID: oldPlan.ProjectID,- Title: planUpdate.Name,- Description: planUpdate.Description,- Deleted: planUpdate.Deleted,- Specs: specs,- })- if err != nil {- var workflowErr *review.Error- if errors.As(err, &workflowErr) && workflowErr.Code == review.ErrorFailedPrecondition {- return nil, connect.NewError(connect.CodeFailedPrecondition, errors.Errorf("cannot update specs for plan that has a rollout"))- }- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to update plan %q: %v", req.Plan.Name, err))+ specsUpdate = &specs+ }+ updateResult, err := s.reviewWorkflow.UpdatePlan(ctx, review.UpdatePlanInput{+ Workspace: common.GetWorkspaceIDFromContext(ctx),+ PlanUID: oldPlan.UID,+ ProjectID: oldPlan.ProjectID,+ Title: planUpdate.Name,+ Description: planUpdate.Description,+ Deleted: planUpdate.Deleted,+ Specs: specsUpdate,+ })+ if err != nil {+ var workflowErr *review.Error+ if errors.As(err, &workflowErr) && workflowErr.Code == review.ErrorFailedPrecondition {+ return nil, connect.NewError(connect.CodeFailedPrecondition, workflowErr)}- updatedPlan = updateResult.Plan- } else {- updatedPlan, err = s.store.UpdatePlan(ctx, planUpdate)- if err != nil {- return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to update plan %q: %v", req.Plan.Name, err))+ if errors.As(err, &workflowErr) && workflowErr.Code == review.ErrorConflict {+ return nil, connect.NewError(connect.CodeAborted, workflowErr)}- updateResult = &review.UpdatePlanSpecsResult{Plan: updatedPlan}+ return nil, connect.NewError(connect.CodeInternal, errors.Errorf("failed to update plan %q: %v", req.Plan.Name, err))}+ updatedPlan := updateResult.Planvar planCheckRunCreated boolif planCheckRunsTrigger {@@ -912,7 +910,9 @@ func convertToPlans(ctx context.Context, s *store.Store, plans []*store.PlanMessif issue := issueByPlanKey[key]; issue != nil {v1Plan.Issue = common.FormatIssue(issue.ProjectID, issue.UID)- v1Plan.ApprovalStatus = computeApprovalStatus(issue.Payload.GetApproval())+ if !issue.Payload.GetDraft() {+ v1Plan.ApprovalStatus = computeApprovalStatus(issue.Payload.GetApproval())+ }}if planCheckRun := planCheckRunByPlanKey[key]; planCheckRun != nil {diff --git a/backend/api/v1/plan_service_test.go b/backend/api/v1/plan_service_test.goindex 2264ffa6db..254d794368 100644--- a/backend/api/v1/plan_service_test.go+++ b/backend/api/v1/plan_service_test.go@@ -16,7 +16,7 @@ import ("github.com/bytebase/bytebase/backend/store")-func TestPlanServiceListPlansKeepsIssueLessDraftsVisible(t *testing.T) {+func TestPlanServiceListPlansHidesIssueLessDatabaseDrafts(t *testing.T) {ctx := context.Background()stores := setupPlanServiceTestStore(ctx, t)service := NewPlanService(stores, nil, nil, nil, nil)@@ -53,7 +53,14 @@ func TestPlanServiceListPlansKeepsIssueLessDraftsVisible(t *testing.T) {for _, plan := range response.Msg.Plans {got = append(got, plan.Title)}- require.ElementsMatch(t, []string{changeDraft.Name, createDraft.Name}, got)+ require.Empty(t, got)+ for _, plan := range []*store.PlanMessage{changeDraft, createDraft} {+ gotPlan, err := service.GetPlan(ctx, connect.NewRequest(&v1pb.GetPlanRequest{+ Name: fmt.Sprintf("projects/project-a/plans/%d", plan.UID),+ }))+ require.NoError(t, err)+ require.Equal(t, plan.Name, gotPlan.Msg.Title)+ }}func TestPlanServiceCreatePlanRejectsMixedDatabaseSpecs(t *testing.T) {diff --git a/backend/component/review/approval.go b/backend/component/review/approval.goindex cd20ac620c..f2dd8ce8c6 100644--- a/backend/component/review/approval.go+++ b/backend/component/review/approval.go@@ -103,6 +103,7 @@ func (a *ApprovalEvaluator) ApplyApprovalTemplate(ctx context.Context, input Appreturn result, nil}observedLabels := store.CanonicalizeIssueLabels(issue.Payload.GetLabels())+ labelsAffectApproval := approvalDependsOnLabels(issue, observedPlan)evaluatedIssue := *issueevaluatedIssue.Payload = proto.CloneOf(issue.Payload)evaluate := a.evaluateApproval@@ -156,7 +157,7 @@ func (a *ApprovalEvaluator) ApplyApprovalTemplate(ctx context.Context, input Appreturn nil, err}if !approvalsEqual(lockedIssue.Payload.GetApproval(), observedApproval) ||- !slices.Equal(store.CanonicalizeIssueLabels(lockedIssue.Payload.GetLabels()), observedLabels) ||+ (labelsAffectApproval && !slices.Equal(store.CanonicalizeIssueLabels(lockedIssue.Payload.GetLabels()), observedLabels)) ||lockedIssue.Payload.GetDraft() != issue.Payload.GetDraft() ||lockedIssue.Type != issue.Type ||!sameInt64Pointer(lockedIssue.PlanUID, issue.PlanUID) {@@ -182,7 +183,7 @@ func (a *ApprovalEvaluator) ApplyApprovalTemplate(ctx context.Context, input Appif err := updateIssuePayload(ctx, tx, lockedIssue, &storepb.Issue{Approval: evaluatedApproval,RiskLevel: evaluatedRiskLevel,- }, false); err != nil {+ }, issuePayloadUpdateOptions{}); err != nil {return nil, workflowWrap(ErrorInternal, err, "failed to apply approval finding")}lockedIssue.Payload.Approval = evaluatedApproval@@ -196,6 +197,18 @@ func (a *ApprovalEvaluator) ApplyApprovalTemplate(ctx context.Context, input Appreturn result, nil}+func approvalDependsOnLabels(issue *store.IssueMessage, plan *store.PlanMessage) bool {+ if issue.Type != storepb.Issue_DATABASE_CHANGE || plan == nil {+ return false+ }+ for _, spec := range plan.Config.GetSpecs() {+ if spec.GetChangeDatabaseConfig() != nil {+ return true+ }+ }+ return false+}+func approvalsEqual(a, b *storepb.IssuePayloadApproval) bool {if a == nil || b == nil {return a == nil && b == nildiff --git a/backend/component/review/draft_creation_test.go b/backend/component/review/draft_creation_test.gonew file mode 100644index 0000000000..4dae06a0b7--- /dev/null+++ b/backend/component/review/draft_creation_test.go@@ -0,0 +1,132 @@+package review++import (+ "context"+ "errors"+ "testing"++ "github.com/stretchr/testify/require"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/store"+)++func TestCreateDraftIssueRevalidatesPlanAfterProposal(t *testing.T) {+ tests := []struct {+ name string+ mutate func(context.Context, *testing.T, *store.Store, *store.PlanMessage)+ errorCode ErrorCode+ }{+ {+ name: "Plan closed",+ mutate: func(ctx context.Context, t *testing.T, stores *store.Store, plan *store.PlanMessage) {+ deleted := true+ _, err := NewWorkflow(stores).UpdatePlan(ctx, UpdatePlanInput{+ Workspace: "default", ProjectID: plan.ProjectID, PlanUID: plan.UID, Deleted: &deleted,+ })+ require.NoError(t, err)+ },+ errorCode: ErrorFailedPrecondition,+ },+ {+ name: "Plan kind changed",+ mutate: func(ctx context.Context, t *testing.T, stores *store.Store, plan *store.PlanMessage) {+ specs := []*storepb.PlanConfig_Spec{{+ Config: &storepb.PlanConfig_Spec_ExportDataConfig{+ ExportDataConfig: &storepb.PlanConfig_ExportDataConfig{},+ },+ }}+ _, err := NewWorkflow(stores).UpdatePlan(ctx, UpdatePlanInput{+ Workspace: "default", ProjectID: plan.ProjectID, PlanUID: plan.UID, Specs: &specs,+ })+ require.NoError(t, err)+ },+ errorCode: ErrorInvalidAction,+ },+ {+ name: "rollout started",+ mutate: func(ctx context.Context, t *testing.T, stores *store.Store, plan *store.PlanMessage) {+ _, err := NewWorkflow(stores).CreateRollout(ctx, CreateRolloutInput{+ Workspace: "default", ProjectID: plan.ProjectID, PlanUID: plan.UID,+ BuildTasks: func(context.Context, *store.PlanMessage, *store.ProjectMessage) ([]*store.TaskMessage, error) {+ return nil, nil+ },+ })+ require.NoError(t, err)+ },+ errorCode: ErrorFailedPrecondition,+ },+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ ctx := context.Background()+ stores := setupWorkflowStore(ctx, t)+ plan, err := stores.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a", Name: "draft Plan", Description: "from Plan",+ Config: &storepb.PlanConfig{Specs: []*storepb.PlanConfig_Spec{{+ Config: &storepb.PlanConfig_Spec_ChangeDatabaseConfig{+ ChangeDatabaseConfig: &storepb.PlanConfig_ChangeDatabaseConfig{},+ },+ }}},+ }, "[email protected]")+ require.NoError(t, err)+ workflow := NewWorkflow(stores)+ workflow.beforeCreateDraft = func() { test.mutate(ctx, t, stores, plan) }++ result, err := workflow.CreateDraftIssue(ctx, CreateDraftIssueInput{+ Workspace: "default",+ Issue: &store.IssueMessage{+ ProjectID: plan.ProjectID, CreatorEmail: "[email protected]", PlanUID: &plan.UID,+ Title: "stale request title", Type: storepb.Issue_DATABASE_CHANGE,+ Payload: &storepb.Issue{Draft: true, Approval: &storepb.IssuePayloadApproval{}},+ },+ })+ require.Nil(t, result)+ var workflowErr *Error+ require.True(t, errors.As(err, &workflowErr))+ require.Equal(t, test.errorCode, workflowErr.Code)+ issue, getErr := stores.GetIssue(ctx, &store.FindIssueMessage{+ ProjectIDs: []string{plan.ProjectID}, PlanUID: &plan.UID,+ })+ require.NoError(t, getErr)+ require.Nil(t, issue)+ })+ }+}++func TestCreateDraftIssueUsesLockedPlanMetadata(t *testing.T) {+ ctx := context.Background()+ stores := setupWorkflowStore(ctx, t)+ plan, err := stores.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a", Name: "Plan title", Description: "Plan description",+ Config: &storepb.PlanConfig{Specs: []*storepb.PlanConfig_Spec{{+ Config: &storepb.PlanConfig_Spec_CreateDatabaseConfig{+ CreateDatabaseConfig: &storepb.PlanConfig_CreateDatabaseConfig{},+ },+ }}},+ }, "[email protected]")+ require.NoError(t, err)+ workflow := NewWorkflow(stores)+ workflow.beforeCreateDraft = func() {+ title := "Updated Plan title"+ description := "Updated Plan description"+ _, updateErr := NewWorkflow(stores).UpdatePlan(ctx, UpdatePlanInput{+ Workspace: "default", ProjectID: plan.ProjectID, PlanUID: plan.UID,+ Title: &title, Description: &description,+ })+ require.NoError(t, updateErr)+ }+ result, err := workflow.CreateDraftIssue(ctx, CreateDraftIssueInput{+ Workspace: "default",+ Issue: &store.IssueMessage{+ ProjectID: plan.ProjectID, CreatorEmail: "[email protected]", PlanUID: &plan.UID,+ Title: "request title", Description: "request description", Type: storepb.Issue_DATABASE_CHANGE,+ Payload: &storepb.Issue{Draft: true, Approval: &storepb.IssuePayloadApproval{}},+ },+ })+ require.NoError(t, err)+ require.True(t, result.Created)+ require.Equal(t, "Updated Plan title", result.Issue.Title)+ require.Equal(t, "Updated Plan description", result.Issue.Description)+}diff --git a/backend/component/review/metadata.go b/backend/component/review/metadata.goindex 04c53331a2..1022c95804 100644--- a/backend/component/review/metadata.go+++ b/backend/component/review/metadata.go@@ -17,6 +17,9 @@ type UpdateIssueMetadataInput struct {Title *stringDescription *stringLabels *[]string+ // ExpectedDraft is the lifecycle state observed by the adapter. When set,+ // the mutation conflicts instead of changing semantics after a race.+ ExpectedDraft *bool}// UpdateIssueMetadataResult is the committed metadata and review state.@@ -51,6 +54,9 @@ func (w *Workflow) UpdateIssueMetadata(ctx context.Context, input UpdateIssueMetif issue == nil {return nil, workflowError(ErrorNotFound, "issue %d not found in project %s", input.IssueUID, input.ProjectID)}+ if input.ExpectedDraft != nil && issue.Payload.GetDraft() != *input.ExpectedDraft {+ return nil, workflowError(ErrorConflict, "issue draft state changed while metadata was being updated")+ }result := &UpdateIssueMetadataResult{Issue: issue}patch := &store.UpdateIssueMessage{}if input.Title != nil && *input.Title != issue.Title {diff --git a/backend/component/review/plan.go b/backend/component/review/plan.goindex e581a821ca..021dce724e 100644--- a/backend/component/review/plan.go+++ b/backend/component/review/plan.go@@ -15,28 +15,56 @@ import ("github.com/bytebase/bytebase/backend/store")-// UpdatePlanSpecsInput describes a review-affecting Plan spec mutation. Metadata-// is accepted only so a mixed API update remains atomic with the spec change.-type UpdatePlanSpecsInput struct {+// UpdatePlanInput describes a Plan mutation. The workflow keeps a linked draft+// issue's metadata and lifecycle synchronized with the Plan and resets review+// state when submitted Plan specs change.+type UpdatePlanInput struct {Workspace stringProjectID stringPlanUID int64Title *stringDescription *stringDeleted *bool- Specs []*storepb.PlanConfig_Spec+ Specs *[]*storepb.PlanConfig_Spec}-// UpdatePlanSpecsResult is the committed Plan and linked review state.-type UpdatePlanSpecsResult struct {+// UpdatePlanResult is the committed Plan and linked review state.+type UpdatePlanResult struct {Plan *store.PlanMessageIssue *store.IssueMessageApprovalReset boolEvents []Event}-// UpdatePlanSpecs commits a Plan spec mutation and any linked approval reset atomically.+// UpdatePlanSpecsInput is retained for callers performing a spec mutation.+type UpdatePlanSpecsInput struct {+ Workspace string+ ProjectID string+ PlanUID int64+ Title *string+ Description *string+ Deleted *bool+ Specs []*storepb.PlanConfig_Spec+}++// UpdatePlanSpecsResult is the result of a spec mutation.+type UpdatePlanSpecsResult = UpdatePlanResult++// UpdatePlanSpecs commits a Plan spec mutation through UpdatePlan.func (w *Workflow) UpdatePlanSpecs(ctx context.Context, input UpdatePlanSpecsInput) (*UpdatePlanSpecsResult, error) {+ return w.UpdatePlan(ctx, UpdatePlanInput{+ Workspace: input.Workspace,+ ProjectID: input.ProjectID,+ PlanUID: input.PlanUID,+ Title: input.Title,+ Description: input.Description,+ Deleted: input.Deleted,+ Specs: &input.Specs,+ })+}++// UpdatePlan commits a Plan mutation and its linked review changes atomically.+func (w *Workflow) UpdatePlan(ctx context.Context, input UpdatePlanInput) (*UpdatePlanResult, error) {if w.beforePlanCommit != nil {w.beforePlanCommit()}@@ -61,14 +89,16 @@ func (w *Workflow) UpdatePlanSpecs(ctx context.Context, input UpdatePlanSpecsInpif plan == nil {return nil, workflowError(ErrorNotFound, "plan %d not found in project %s", input.PlanUID, input.ProjectID)}- if plan.Config.GetHasRollout() {+ if input.Specs != nil && plan.Config.GetHasRollout() {return nil, workflowError(ErrorFailedPrecondition, "cannot update specs for plan that has a rollout")}oldSpecs := plan.Config.GetSpecs()updatedConfig := proto.CloneOf(plan.Config)- updatedConfig.Specs = input.Specs- updatedConfig.ApprovalInputVersion = plan.Config.GetApprovalInputVersion() + 1+ if input.Specs != nil {+ updatedConfig.Specs = *input.Specs+ updatedConfig.ApprovalInputVersion = plan.Config.GetApprovalInputVersion() + 1+ }config, err := protojson.Marshal(updatedConfig)if err != nil {return nil, workflowWrap(ErrorInternal, err, "failed to marshal Plan config")@@ -89,7 +119,7 @@ func (w *Workflow) UpdatePlanSpecs(ctx context.Context, input UpdatePlanSpecsInpinput.Title != nil, stringValue(input.Title),input.Description != nil, stringValue(input.Description),input.Deleted != nil, boolValue(input.Deleted),- true, config,+ input.Specs != nil, config,input.ProjectID, input.PlanUID,).Scan(&plan.UpdatedAt); err != nil {return nil, workflowWrap(ErrorInternal, err, "failed to update Plan")@@ -105,22 +135,60 @@ func (w *Workflow) UpdatePlanSpecs(ctx context.Context, input UpdatePlanSpecsInp}plan.Config = updatedConfig- result := &UpdatePlanSpecsResult{Plan: plan, Issue: issue}- if issue != nil && !issue.Payload.GetDraft() {+ result := &UpdatePlanResult{Plan: plan, Issue: issue}+ if issue != nil && issue.Payload.GetDraft() {+ status := issue.Status+ if input.Deleted != nil {+ status = storepb.Issue_OPEN+ if *input.Deleted {+ status = storepb.Issue_CANCELED+ }+ }+ title := issue.Title+ if input.Title != nil {+ title = *input.Title+ }+ description := issue.Description+ if input.Description != nil {+ description = *input.Description+ }+ if err := tx.QueryRowContext(ctx, `+ UPDATE issue+ SET updated_at = $1,+ name = $2,+ description = $3,+ status = $4,+ ts_vector = $5+ WHERE project = $6+ AND id = $7+ AND COALESCE((payload->>'draft')::boolean, false)+ RETURNING updated_at`,+ time.Now(), title, description, status.String(), store.IssueSearchVector(title, description),+ input.ProjectID, issue.UID,+ ).Scan(&issue.UpdatedAt); err != nil {+ if errors.Is(err, sql.ErrNoRows) {+ return nil, workflowError(ErrorConflict, "linked draft issue was submitted while the Plan was being updated")+ }+ return nil, workflowWrap(ErrorInternal, err, "failed to synchronize linked draft issue")+ }+ issue.Title = title+ issue.Description = description+ issue.Status = status+ } else if issue != nil && input.Specs != nil {approval := &storepb.IssuePayloadApproval{ApprovalFindingDone: false,ApprovalInputVersion: updatedConfig.GetApprovalInputVersion(),}- if err := updateIssuePayload(ctx, tx, issue, &storepb.Issue{Approval: approval}, false); err != nil {+ if err := updateIssuePayload(ctx, tx, issue, &storepb.Issue{Approval: approval}, issuePayloadUpdateOptions{}); err != nil {return nil, workflowWrap(ErrorInternal, err, "failed to reset issue approval")}issue.Payload.Approval = approvalresult.ApprovalReset = true}- if issue != nil && !planSpecsEqualSet(oldSpecs, input.Specs) {+ if issue != nil && input.Specs != nil && !planSpecsEqualSet(oldSpecs, *input.Specs) {result.Events = append(result.Events, PlanUpdatedEvent{FromSpecs: oldSpecs,- ToSpecs: input.Specs,+ ToSpecs: *input.Specs,})}diff --git a/backend/component/review/submission.go b/backend/component/review/submission.gonew file mode 100644index 0000000000..5c6a829a88--- /dev/null+++ b/backend/component/review/submission.go@@ -0,0 +1,399 @@+package review++import (+ "context"+ "database/sql"+ "fmt"+ "slices"+ "strconv"+ "strings"++ "github.com/pkg/errors"+ "google.golang.org/protobuf/encoding/protojson"+ "google.golang.org/protobuf/proto"++ "github.com/bytebase/bytebase/backend/common"+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/store"+)++// SubmittedEvent requests a submission timeline entry.+type SubmittedEvent struct{}++func (SubmittedEvent) isReviewEvent() {}++// IssueCreatedEvent requests the legacy issue-created webhook at submission.+type IssueCreatedEvent struct{}++func (IssueCreatedEvent) isReviewEvent() {}++// CreateDraftIssueInput describes a draft review issue linked to a Plan.+type CreateDraftIssueInput struct {+ Workspace string+ Issue *store.IssueMessage+}++// CreateDraftIssueResult is the current linked draft and whether this call created it.+type CreateDraftIssueResult struct {+ Issue *store.IssueMessage+ Created bool+}++// CreateDraftIssue creates a valid draft from current Plan state under the Plan lock.+func (w *Workflow) CreateDraftIssue(ctx context.Context, input CreateDraftIssueInput) (*CreateDraftIssueResult, error) {+ if input.Issue == nil || input.Issue.Type != storepb.Issue_DATABASE_CHANGE || input.Issue.PlanUID == nil || !input.Issue.Payload.GetDraft() {+ return nil, workflowError(ErrorInvalidAction, "draft review issue must have a database Plan")+ }+ if w.beforeCreateDraft != nil {+ w.beforeCreateDraft()+ }++ issue := *input.Issue+ issue.Payload = proto.CloneOf(input.Issue.Payload)+ issue.Payload.Labels = store.CanonicalizeIssueLabels(issue.Payload.GetLabels())+ issue.Status = storepb.Issue_OPEN++ tx, err := w.store.GetDB().BeginTx(ctx, nil)+ if err != nil {+ return nil, workflowWrap(ErrorInternal, err, "failed to begin draft creation transaction")+ }+ defer tx.Rollback()+ key := issue.ProjectID + "/" + strconv.FormatInt(*issue.PlanUID, 10)+ if err := store.AcquireAdvisoryXactLockWithStringKey(ctx, tx, store.AdvisoryLockKeyPlanIssueRollout, key); err != nil {+ return nil, workflowWrap(ErrorInternal, err, "failed to acquire Plan review lock")+ }+ existing, err := lockIssueByPlan(ctx, tx, issue.ProjectID, *issue.PlanUID)+ if err != nil {+ return nil, err+ }+ if existing != nil {+ if existing.Payload.GetDraft() && existing.CreatorEmail == issue.CreatorEmail {+ return &CreateDraftIssueResult{Issue: existing}, nil+ }+ return nil, workflowError(ErrorConflict, "Plan already has a review issue")+ }+ plan, err := lockPlan(ctx, tx, input.Workspace, issue.ProjectID, *issue.PlanUID)+ if err != nil {+ return nil, err+ }+ if plan == nil {+ return nil, workflowError(ErrorNotFound, "Plan not found")+ }+ if plan.Deleted {+ return nil, workflowError(ErrorFailedPrecondition, "cannot create a draft issue for a closed Plan")+ }+ if plan.Config.GetHasRollout() {+ return nil, workflowError(ErrorFailedPrecondition, "cannot create a draft issue because the Plan already has a rollout")+ }+ if _, err := classifyReviewPlan(plan); err != nil {+ return nil, err+ }+ issue.Title = plan.Name+ issue.Description = plan.Description+ if _, err := tx.ExecContext(ctx, `+ SELECT 1 FROM project+ WHERE workspace = $1 AND resource_id = $2+ FOR UPDATE`, input.Workspace, issue.ProjectID); err != nil {+ return nil, workflowWrap(ErrorInternal, err, "failed to lock project for draft creation")+ }+ if err := tx.QueryRowContext(ctx, `+ SELECT GREATEST(COALESCE(MAX(id), 0) + 1, 101)+ FROM issue+ WHERE project = $1`, issue.ProjectID).Scan(&issue.UID); err != nil {+ return nil, workflowWrap(ErrorInternal, err, "failed to allocate issue ID")+ }+ payload, err := protojson.Marshal(issue.Payload)+ if err != nil {+ return nil, workflowWrap(ErrorInternal, err, "failed to marshal draft issue payload")+ }+ if err := tx.QueryRowContext(ctx, `+ INSERT INTO issue (+ id, creator, project, plan_id, name, status, type, description, payload, ts_vector+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)+ RETURNING created_at, updated_at`,+ issue.UID, issue.CreatorEmail, issue.ProjectID, issue.PlanUID, issue.Title,+ issue.Status.String(), issue.Type.String(), issue.Description, payload,+ store.IssueSearchVector(issue.Title, issue.Description),+ ).Scan(&issue.CreatedAt, &issue.UpdatedAt); err != nil {+ return nil, workflowWrap(ErrorInternal, err, "failed to insert draft issue")+ }+ if err := tx.Commit(); err != nil {+ return nil, workflowWrap(ErrorInternal, err, "failed to commit draft creation")+ }+ return &CreateDraftIssueResult{Issue: &issue, Created: true}, nil+}++// SubmitIssueInput identifies a draft issue submission.+type SubmitIssueInput struct {+ Workspace string+ ProjectID string+ IssueUID int64+ Labels []string+ LabelsSet bool+}++// SubmitIssueResult is the committed issue and its post-commit effects.+type SubmitIssueResult struct {+ Issue *store.IssueMessage+ Project *store.ProjectMessage+ Submitted bool+ LabelsChanged bool+ PreviousLabels []string+ Events []Event+}++// SubmitIssue validates and atomically submits a draft review issue.+func (w *Workflow) SubmitIssue(ctx context.Context, input SubmitIssueInput) (*SubmitIssueResult, error) {+ project, err := w.store.GetProject(ctx, &store.FindProjectMessage{+ Workspace: input.Workspace, ResourceID: &input.ProjectID,+ })+ if err != nil {+ return nil, workflowWrap(ErrorInternal, err, "failed to get project")+ }+ if project == nil {+ return nil, workflowError(ErrorNotFound, "project %s not found", input.ProjectID)+ }+ observedIssue, err := w.store.GetIssue(ctx, &store.FindIssueMessage{+ Workspace: input.Workspace, ProjectIDs: []string{input.ProjectID}, UID: &input.IssueUID,+ })+ if err != nil {+ return nil, workflowWrap(ErrorInternal, err, "failed to get issue")+ }+ if observedIssue == nil {+ return nil, workflowError(ErrorNotFound, "issue %d not found in project %s", input.IssueUID, input.ProjectID)+ }+ if !observedIssue.Payload.GetDraft() {+ return &SubmitIssueResult{Issue: observedIssue, Project: project}, nil+ }+ if observedIssue.Type != storepb.Issue_DATABASE_CHANGE || observedIssue.PlanUID == nil {+ return nil, workflowError(ErrorFailedPrecondition, "draft review issue must have a database Plan")+ }+ if w.beforeSubmit != nil {+ w.beforeSubmit()+ }++ tx, err := w.store.GetDB().BeginTx(ctx, nil)+ if err != nil {+ return nil, workflowWrap(ErrorInternal, err, "failed to begin issue submission transaction")+ }+ defer tx.Rollback()++ key := input.ProjectID + "/" + strconv.FormatInt(*observedIssue.PlanUID, 10)+ if err := store.AcquireAdvisoryXactLockWithStringKey(ctx, tx, store.AdvisoryLockKeyPlanIssueRollout, key); err != nil {+ return nil, workflowWrap(ErrorInternal, err, "failed to acquire Plan review lock")+ }+ issue, err := lockIssue(ctx, tx, input.ProjectID, input.IssueUID)+ if err != nil {+ return nil, err+ }+ if issue == nil {+ return nil, workflowError(ErrorNotFound, "issue %d not found in project %s", input.IssueUID, input.ProjectID)+ }+ if !issue.Payload.GetDraft() {+ return &SubmitIssueResult{Issue: issue, Project: project}, nil+ }+ if issue.Type != storepb.Issue_DATABASE_CHANGE || issue.PlanUID == nil || *issue.PlanUID != *observedIssue.PlanUID {+ return nil, workflowError(ErrorFailedPrecondition, "draft review issue must have a database Plan")+ }+ plan, err := lockIssuePlan(ctx, tx, issue)+ if err != nil {+ return nil, err+ }+ if plan == nil {+ return nil, workflowError(ErrorNotFound, "plan not found")+ }++ labels := store.CanonicalizeIssueLabels(issue.Payload.GetLabels())+ previousLabels := labels+ if input.LabelsSet {+ labels = store.CanonicalizeIssueLabels(input.Labels)+ }+ if err := validateSubmissionState(project, issue, plan, labels); err != nil {+ return nil, err+ }+ if reviewPlanRequiresChecks(plan) {+ planCheckRun, err := lockPlanCheckRun(ctx, tx, input.ProjectID, plan.UID)+ if err != nil {+ return nil, err+ }+ if err := validatePlanCheckRun(project, plan, planCheckRun); err != nil {+ return nil, err+ }+ }++ if err := submitIssuePayload(ctx, tx, issue, labels); err != nil {+ return nil, workflowWrap(ErrorInternal, err, "failed to submit issue")+ }+ issue.Payload.Draft = false+ issue.Payload.Labels = labels+ if err := tx.Commit(); err != nil {+ return nil, workflowWrap(ErrorInternal, err, "failed to commit issue submission")+ }+ return &SubmitIssueResult{+ Issue: issue,+ Project: project,+ Submitted: true,+ LabelsChanged: !slices.Equal(previousLabels, labels),+ PreviousLabels: previousLabels,+ Events: []Event{SubmittedEvent{}, IssueCreatedEvent{}, ApprovalCheckEvent{}},+ }, nil+}++type reviewPlanKind int++const (+ reviewPlanCreateDatabase reviewPlanKind = iota+ reviewPlanChangeDatabase+)++func validateSubmissionState(project *store.ProjectMessage, issue *store.IssueMessage, plan *store.PlanMessage, labels []string) error {+ if issue.Status != storepb.Issue_OPEN {+ return workflowError(ErrorConflict, "draft issue status changed while it was being submitted")+ }+ if strings.TrimSpace(issue.Title) == "" || strings.TrimSpace(plan.Name) == "" {+ return workflowError(ErrorInvalidAction, "issue and Plan title are required")+ }+ if project.Setting.GetForceIssueLabels() && len(labels) == 0 {+ return workflowError(ErrorInvalidAction, "require issue labels")+ }+ if plan.Deleted {+ return workflowError(ErrorFailedPrecondition, "cannot submit an issue for a closed Plan")+ }+ if plan.Config.GetHasRollout() {+ return workflowError(ErrorFailedPrecondition, "cannot submit an issue after rollout has started")+ }+ kind, err := classifyReviewPlan(plan)+ if err != nil {+ return err+ }+ for index, spec := range plan.Config.GetSpecs() {+ if err := validateReviewPlanSpecReady(spec, index, kind); err != nil {+ return err+ }+ }+ return nil+}++func classifyReviewPlan(plan *store.PlanMessage) (reviewPlanKind, error) {+ var kind reviewPlanKind+ for index, spec := range plan.Config.GetSpecs() {+ if spec == nil {+ return 0, workflowError(ErrorInvalidAction, "draft issues require a database Plan")+ }+ var current reviewPlanKind+ switch config := spec.Config.(type) {+ case *storepb.PlanConfig_Spec_CreateDatabaseConfig:+ current = reviewPlanCreateDatabase+ case *storepb.PlanConfig_Spec_ChangeDatabaseConfig:+ if config.ChangeDatabaseConfig.GetRelease() != "" {+ return 0, workflowError(ErrorInvalidAction, "draft issues are not supported for GitOps Plans")+ }+ current = reviewPlanChangeDatabase+ default:+ return 0, workflowError(ErrorInvalidAction, "draft issues require a database Plan")+ }+ if index > 0 && current != kind {+ return 0, workflowError(ErrorInvalidAction, "draft issues are not supported for mixed Plans")+ }+ kind = current+ }+ if len(plan.Config.GetSpecs()) == 0 {+ return 0, workflowError(ErrorInvalidAction, "draft issues require a database Plan")+ }+ return kind, nil+}++func validateReviewPlanSpecReady(spec *storepb.PlanConfig_Spec, index int, kind reviewPlanKind) error {+ reference := fmt.Sprintf("Plan spec at index %d", index)+ if id := spec.GetId(); id != "" {+ reference = fmt.Sprintf("Plan spec %q", id)+ }+ switch kind {+ case reviewPlanCreateDatabase:+ config := spec.GetCreateDatabaseConfig()+ if strings.TrimSpace(config.GetTarget()) == "" {+ return workflowError(ErrorInvalidAction, "%s is missing create target", reference)+ }+ if strings.TrimSpace(config.GetDatabase()) == "" {+ return workflowError(ErrorInvalidAction, "%s is missing create database name", reference)+ }+ case reviewPlanChangeDatabase:+ config := spec.GetChangeDatabaseConfig()+ if len(config.GetTargets()) == 0 {+ return workflowError(ErrorInvalidAction, "%s is missing change targets", reference)+ }+ if config.GetSheetSha256() == "" {+ return workflowError(ErrorInvalidAction, "%s is missing sheet", reference)+ }+ default:+ return workflowError(ErrorInternal, "unsupported review Plan kind %d", kind)+ }+ return nil+}++func reviewPlanRequiresChecks(plan *store.PlanMessage) bool {+ for _, spec := range plan.Config.GetSpecs() {+ config := spec.GetChangeDatabaseConfig()+ if config != nil && config.GetRelease() == "" && len(config.GetTargets()) > 0 {+ return true+ }+ }+ return false+}++func lockPlanCheckRun(ctx context.Context, tx *sql.Tx, projectID string, planUID int64) (*store.PlanCheckRunMessage, error) {+ run := &store.PlanCheckRunMessage{Result: &storepb.PlanCheckRunResult{}}+ var result []byte+ err := tx.QueryRowContext(ctx, `+ SELECT id, created_at, updated_at, project, plan_id, status, result+ FROM plan_check_run+ WHERE project = $1 AND plan_id = $2+ FOR UPDATE`, projectID, planUID).Scan(+ &run.UID, &run.CreatedAt, &run.UpdatedAt, &run.ProjectID, &run.PlanUID, &run.Status, &result,+ )+ if errors.Is(err, sql.ErrNoRows) {+ return nil, nil+ }+ if err != nil {+ return nil, workflowWrap(ErrorInternal, err, "failed to lock Plan check run")+ }+ if err := common.ProtojsonUnmarshaler.Unmarshal(result, run.Result); err != nil {+ return nil, workflowWrap(ErrorInternal, err, "failed to unmarshal Plan check result")+ }+ return run, nil+}++func validatePlanCheckRun(project *store.ProjectMessage, plan *store.PlanMessage, run *store.PlanCheckRunMessage) error {+ if run == nil {+ return workflowError(ErrorFailedPrecondition, "Plan checks have not run")+ }+ if run.Result.GetApprovalInputVersion() != plan.Config.GetApprovalInputVersion() {+ return workflowError(ErrorFailedPrecondition, "Plan checks are stale")+ }+ switch run.Status {+ case store.PlanCheckRunStatusAvailable, store.PlanCheckRunStatusRunning:+ return workflowError(ErrorFailedPrecondition, "Plan checks are still running")+ case store.PlanCheckRunStatusCanceled, store.PlanCheckRunStatusFailed:+ return workflowError(ErrorFailedPrecondition, "Plan checks did not pass")+ case store.PlanCheckRunStatusDone:+ default:+ return workflowError(ErrorFailedPrecondition, "Plan checks are not complete")+ }+ for _, result := range run.Result.GetResults() {+ if result.GetStatus() != storepb.Advice_ERROR {+ continue+ }+ if project.Setting.GetEnforceSqlReview() && result.GetType() == storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_ADVISE {+ return workflowError(ErrorFailedPrecondition, "Plan checks did not pass")+ }+ }+ return nil+}++func submitIssuePayload(ctx context.Context, tx *sql.Tx, issue *store.IssueMessage, labels []string) error {+ patch := &storepb.Issue{Labels: labels}+ return updateIssuePayload(ctx, tx, issue, patch, issuePayloadUpdateOptions{+ removeLabels: len(labels) == 0,+ submitDraft: true,+ })+}diff --git a/backend/component/review/submission_test.go b/backend/component/review/submission_test.gonew file mode 100644index 0000000000..261d811aba--- /dev/null+++ b/backend/component/review/submission_test.go@@ -0,0 +1,307 @@+package review++import (+ "context"+ "errors"+ "sync"+ "testing"++ "github.com/stretchr/testify/require"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ "github.com/bytebase/bytebase/backend/store"+)++func TestSubmitIssueRejectsStateChangedAfterProposal(t *testing.T) {+ tests := []struct {+ name string+ configure func(context.Context, *testing.T, *store.Store)+ mutate func(context.Context, *testing.T, *store.Store, *store.PlanMessage, *store.IssueMessage)+ errorCode ErrorCode+ withLabels bool+ }{+ {+ name: "required labels removed",+ configure: func(ctx context.Context, t *testing.T, stores *store.Store) {+ require.NoError(t, stores.UpdateProjects(ctx, &store.UpdateProjectMessage{+ Workspace: "default", ResourceID: "project-a",+ Setting: &storepb.Project{ForceIssueLabels: true},+ }))+ },+ mutate: func(ctx context.Context, t *testing.T, stores *store.Store, _ *store.PlanMessage, issue *store.IssueMessage) {+ labels := []string(nil)+ _, err := NewWorkflow(stores).UpdateIssueMetadata(ctx, UpdateIssueMetadataInput{+ Workspace: "default", ProjectID: "project-a", IssueUID: issue.UID, Labels: &labels,+ })+ require.NoError(t, err)+ },+ errorCode: ErrorInvalidAction,+ withLabels: true,+ },+ {+ name: "Plan closed",+ mutate: func(ctx context.Context, t *testing.T, stores *store.Store, plan *store.PlanMessage, _ *store.IssueMessage) {+ deleted := true+ _, err := NewWorkflow(stores).UpdatePlan(ctx, UpdatePlanInput{+ Workspace: "default", ProjectID: "project-a", PlanUID: plan.UID, Deleted: &deleted,+ })+ require.NoError(t, err)+ },+ errorCode: ErrorConflict,+ },+ {+ name: "Plan title cleared",+ mutate: func(ctx context.Context, t *testing.T, stores *store.Store, plan *store.PlanMessage, _ *store.IssueMessage) {+ title := ""+ _, err := NewWorkflow(stores).UpdatePlan(ctx, UpdatePlanInput{+ Workspace: "default", ProjectID: "project-a", PlanUID: plan.UID, Title: &title,+ })+ require.NoError(t, err)+ },+ errorCode: ErrorInvalidAction,+ },+ {+ name: "issue status changed",+ mutate: func(ctx context.Context, t *testing.T, stores *store.Store, _ *store.PlanMessage, issue *store.IssueMessage) {+ status := storepb.Issue_CANCELED+ _, err := stores.UpdateIssue(ctx, issue.ProjectID, issue.UID, &store.UpdateIssueMessage{Status: &status})+ require.NoError(t, err)+ },+ errorCode: ErrorConflict,+ },+ {+ name: "Plan checks rerun",+ mutate: func(ctx context.Context, t *testing.T, stores *store.Store, plan *store.PlanMessage, _ *store.IssueMessage) {+ created, err := stores.CreatePlanCheckRun(ctx, &store.PlanCheckRunMessage{+ ProjectID: "project-a", PlanUID: plan.UID,+ Result: &storepb.PlanCheckRunResult{ApprovalInputVersion: plan.Config.GetApprovalInputVersion()},+ })+ require.NoError(t, err)+ require.True(t, created)+ },+ errorCode: ErrorFailedPrecondition,+ },+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ ctx := context.Background()+ stores := setupWorkflowStore(ctx, t)+ if test.configure != nil {+ test.configure(ctx, t, stores)+ }+ plan, issue := createReadyDraft(ctx, t, stores, test.withLabels)+ workflow := NewWorkflow(stores)+ workflow.beforeSubmit = func() { test.mutate(ctx, t, stores, plan, issue) }++ _, err := workflow.SubmitIssue(ctx, SubmitIssueInput{+ Workspace: "default", ProjectID: "project-a", IssueUID: issue.UID,+ })+ var workflowErr *Error+ require.True(t, errors.As(err, &workflowErr))+ require.Equal(t, test.errorCode, workflowErr.Code)+ got, getErr := stores.GetIssue(ctx, &store.FindIssueMessage{ProjectIDs: []string{"project-a"}, UID: &issue.UID})+ require.NoError(t, getErr)+ require.True(t, got.Payload.GetDraft())+ })+ }+}++func TestSubmitIssueAllowsPlanCheckErrorsRequiredOnlyForRollout(t *testing.T) {+ ctx := context.Background()+ stores := setupWorkflowStore(ctx, t)+ require.NoError(t, stores.UpdateProjects(ctx, &store.UpdateProjectMessage{+ Workspace: "default", ResourceID: "project-a",+ Setting: &storepb.Project{+ RequirePlanCheckNoError: true,+ EnforceSqlReview: false,+ },+ }))+ plan, issue := createReadyDraft(ctx, t, stores, false)+ run, err := stores.GetPlanCheckRun(ctx, "project-a", plan.UID)+ require.NoError(t, err)+ require.NoError(t, stores.UpdatePlanCheckRun(ctx, "project-a", store.PlanCheckRunStatusDone, &storepb.PlanCheckRunResult{+ ApprovalInputVersion: plan.Config.GetApprovalInputVersion(),+ Results: []*storepb.PlanCheckRunResult_Result{{+ Status: storepb.Advice_ERROR,+ Type: storepb.PlanCheckType_PLAN_CHECK_TYPE_STATEMENT_ADVISE,+ }},+ }, run.UID))++ result, err := NewWorkflow(stores).SubmitIssue(ctx, SubmitIssueInput{+ Workspace: "default", ProjectID: "project-a", IssueUID: issue.UID,+ })+ require.NoError(t, err)+ require.True(t, result.Submitted)+ require.False(t, result.Issue.Payload.GetDraft())+}++func TestConcurrentSubmitIssueEmitsEffectsOnce(t *testing.T) {+ ctx := context.Background()+ stores := setupWorkflowStore(ctx, t)+ _, issue := createReadyDraft(ctx, t, stores, false)+ workflow := NewWorkflow(stores)+ var ready sync.WaitGroup+ ready.Add(2)+ release := make(chan struct{})+ workflow.beforeSubmit = func() {+ ready.Done()+ <-release+ }++ type outcome struct {+ result *SubmitIssueResult+ err error+ }+ outcomes := make(chan outcome, 2)+ var calls sync.WaitGroup+ for range 2 {+ calls.Go(func() {+ result, err := workflow.SubmitIssue(ctx, SubmitIssueInput{+ Workspace: "default", ProjectID: "project-a", IssueUID: issue.UID,+ })+ outcomes <- outcome{result: result, err: err}+ })+ }+ ready.Wait()+ close(release)+ calls.Wait()+ close(outcomes)++ var effects int+ for outcome := range outcomes {+ require.NoError(t, outcome.err)+ effects += len(outcome.result.Events)+ }+ require.Equal(t, 3, effects)+}++func TestUpdatePlanSynchronizesDraftMetadata(t *testing.T) {+ ctx := context.Background()+ stores := setupWorkflowStore(ctx, t)+ plan, issue := createReadyDraft(ctx, t, stores, false)+ title := "renamed draft"+ description := "updated description"+ deleted := true+ result, err := NewWorkflow(stores).UpdatePlan(ctx, UpdatePlanInput{+ Workspace: "default", ProjectID: "project-a", PlanUID: plan.UID,+ Title: &title, Description: &description, Deleted: &deleted,+ })+ require.NoError(t, err)+ require.Equal(t, issue.UID, result.Issue.UID)+ require.Equal(t, title, result.Issue.Title)+ require.Equal(t, description, result.Issue.Description)+ require.Equal(t, storepb.Issue_CANCELED, result.Issue.Status)+ require.True(t, result.Issue.Payload.GetDraft())+}++func TestApprovalFindingLabelFreshnessMatrix(t *testing.T) {+ tests := []struct {+ name string+ spec *storepb.PlanConfig_Spec+ expectConflict bool+ }{+ {+ name: "change database depends on labels",+ spec: &storepb.PlanConfig_Spec{Config: &storepb.PlanConfig_Spec_ChangeDatabaseConfig{+ ChangeDatabaseConfig: &storepb.PlanConfig_ChangeDatabaseConfig{},+ }},+ expectConflict: true,+ },+ {+ name: "create database ignores labels",+ spec: &storepb.PlanConfig_Spec{Config: &storepb.PlanConfig_Spec_CreateDatabaseConfig{+ CreateDatabaseConfig: &storepb.PlanConfig_CreateDatabaseConfig{},+ }},+ },+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ ctx := context.Background()+ stores := setupWorkflowStore(ctx, t)+ plan, err := stores.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a", Name: "database Plan",+ Config: &storepb.PlanConfig{ApprovalInputVersion: 2, Specs: []*storepb.PlanConfig_Spec{test.spec}},+ }, "[email protected]")+ require.NoError(t, err)+ issue, err := stores.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a", CreatorEmail: "[email protected]", Title: plan.Name,+ Type: storepb.Issue_DATABASE_CHANGE, PlanUID: &plan.UID,+ Payload: &storepb.Issue{+ Labels: []string{"before"},+ Approval: &storepb.IssuePayloadApproval{ApprovalInputVersion: 2},+ },+ })+ require.NoError(t, err)++ evaluator := &ApprovalEvaluator{workflow: NewWorkflow(stores)}+ evaluator.evaluateApproval = func(_ context.Context, issue *store.IssueMessage, _ *store.ProjectMessage, _ *storepb.WorkspaceApprovalSetting) error {+ issue.Payload.Approval = &storepb.IssuePayloadApproval{ApprovalFindingDone: true, ApprovalInputVersion: 2}+ return nil+ }+ evaluator.beforeCommit = func() {+ labels := []string{"after"}+ _, updateErr := NewWorkflow(stores).UpdateIssueMetadata(ctx, UpdateIssueMetadataInput{+ Workspace: "default", ProjectID: "project-a", IssueUID: issue.UID, Labels: &labels,+ })+ require.NoError(t, updateErr)+ }+ result, err := evaluator.ApplyApprovalTemplate(ctx, ApplyApprovalTemplateInput{+ Workspace: "default", ProjectID: "project-a", IssueUID: issue.UID,+ })+ if test.expectConflict {+ var workflowErr *Error+ require.True(t, errors.As(err, &workflowErr))+ require.Equal(t, ErrorConflict, workflowErr.Code)+ require.Nil(t, result)+ return+ }+ require.NoError(t, err)+ require.True(t, result.Applied)+ require.Equal(t, []string{"after"}, result.Issue.Payload.GetLabels())+ })+ }+}++func createReadyDraft(ctx context.Context, t *testing.T, stores *store.Store, withLabels bool) (*store.PlanMessage, *store.IssueMessage) {+ t.Helper()+ plan, err := stores.CreatePlan(ctx, &store.PlanMessage{+ ProjectID: "project-a",+ Name: "change database",+ Config: &storepb.PlanConfig{+ ApprovalInputVersion: 2,+ Specs: []*storepb.PlanConfig_Spec{{+ Id: "change",+ Config: &storepb.PlanConfig_Spec_ChangeDatabaseConfig{+ ChangeDatabaseConfig: &storepb.PlanConfig_ChangeDatabaseConfig{+ Targets: []string{"instances/instance-a/databases/database-a"},+ SheetSha256: "sha256",+ },+ },+ }},+ },+ }, "[email protected]")+ require.NoError(t, err)+ labels := []string(nil)+ if withLabels {+ labels = []string{"environment:prod"}+ }+ issue, err := stores.CreateIssue(ctx, &store.IssueMessage{+ ProjectID: "project-a", CreatorEmail: "[email protected]", Title: plan.Name,+ Type: storepb.Issue_DATABASE_CHANGE, PlanUID: &plan.UID,+ Payload: &storepb.Issue{Draft: true, Labels: labels, Approval: &storepb.IssuePayloadApproval{}},+ })+ require.NoError(t, err)+ created, err := stores.CreatePlanCheckRun(ctx, &store.PlanCheckRunMessage{+ ProjectID: "project-a", PlanUID: plan.UID,+ Result: &storepb.PlanCheckRunResult{ApprovalInputVersion: 2},+ })+ require.NoError(t, err)+ require.True(t, created)+ run, err := stores.GetPlanCheckRun(ctx, "project-a", plan.UID)+ require.NoError(t, err)+ require.NoError(t, stores.UpdatePlanCheckRun(ctx, "project-a", store.PlanCheckRunStatusDone, &storepb.PlanCheckRunResult{+ ApprovalInputVersion: 2,+ }, run.UID))+ return plan, issue+}diff --git a/backend/component/review/workflow.go b/backend/component/review/workflow.goindex 1be5687ace..09ad5cb596 100644--- a/backend/component/review/workflow.go+++ b/backend/component/review/workflow.go@@ -160,9 +160,11 @@ type IssueResult struct {// Workflow owns transactional Bytebase Issue and Plan review transitions.type Workflow struct {- store *store.Store- beforeCommit func()- beforePlanCommit func()+ store *store.Store+ beforeCommit func()+ beforePlanCommit func()+ beforeSubmit func()+ beforeCreateDraft func()}// NewWorkflow creates a review workflow.@@ -265,7 +267,7 @@ func (w *Workflow) ReviewIssue(ctx context.Context, input IssueInput) (*IssueResreturn nil, workflowError(ErrorConflict, "approval finding is stale")}- if err := updateIssuePayload(ctx, tx, lockedIssue, &storepb.Issue{Approval: updatedApproval}, false); err != nil {+ if err := updateIssuePayload(ctx, tx, lockedIssue, &storepb.Issue{Approval: updatedApproval}, issuePayloadUpdateOptions{}); err != nil {return nil, workflowWrap(ErrorInternal, err, "failed to update issue approval")}lockedIssue.Payload.Approval = updatedApproval@@ -298,7 +300,12 @@ func (w *Workflow) ReviewIssue(ctx context.Context, input IssueInput) (*IssueRes}, nil}-func updateIssuePayload(ctx context.Context, tx *sql.Tx, issue *store.IssueMessage, patch *storepb.Issue, removeLabels bool) error {+type issuePayloadUpdateOptions struct {+ removeLabels bool+ submitDraft bool+}++func updateIssuePayload(ctx context.Context, tx *sql.Tx, issue *store.IssueMessage, patch *storepb.Issue, options issuePayloadUpdateOptions) error {payload, err := protojson.Marshal(patch)if err != nil {return errors.Wrap(err, "failed to marshal issue payload")@@ -306,11 +313,13 @@ func updateIssuePayload(ctx context.Context, tx *sql.Tx, issue *store.IssueMessareturn tx.QueryRowContext(ctx, `UPDATE issueSET updated_at = $1,- payload = payload || $2::jsonb || CASE WHEN $5 THEN jsonb_build_object('labels', NULL) ELSE '{}'::jsonb END+ payload = payload || $2::jsonb+ || CASE WHEN $5 THEN jsonb_build_object('labels', NULL) ELSE '{}'::jsonb END+ || CASE WHEN $6 THEN jsonb_build_object('draft', false) ELSE '{}'::jsonb ENDWHERE project = $3AND id = $4RETURNING updated_at`,- time.Now(), payload, issue.ProjectID, issue.UID, removeLabels,+ time.Now(), payload, issue.ProjectID, issue.UID, options.removeLabels, options.submitDraft,).Scan(&issue.UpdatedAt)}diff --git a/backend/generated-go/store/issue_comment.pb.go b/backend/generated-go/store/issue_comment.pb.goindex 8c298a9a6f..0c83c4f61c 100644--- a/backend/generated-go/store/issue_comment.pb.go+++ b/backend/generated-go/store/issue_comment.pb.go@@ -29,6 +29,7 @@ type IssueCommentPayload struct {// *IssueCommentPayload_Approval_// *IssueCommentPayload_IssueUpdate_// *IssueCommentPayload_PlanUpdate_+ // *IssueCommentPayload_ReviewSubmission_Event isIssueCommentPayload_Event `protobuf_oneof:"event"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache@@ -105,6 +106,15 @@ func (x *IssueCommentPayload) GetPlanUpdate() *IssueCommentPayload_PlanUpdate {return nil}+func (x *IssueCommentPayload) GetReviewSubmission() *IssueCommentPayload_ReviewSubmission {+ if x != nil {+ if x, ok := x.Event.(*IssueCommentPayload_ReviewSubmission_); ok {+ return x.ReviewSubmission+ }+ }+ return nil+}+type isIssueCommentPayload_Event interface {isIssueCommentPayload_Event()}@@ -121,12 +131,18 @@ type IssueCommentPayload_PlanUpdate_ struct {PlanUpdate *IssueCommentPayload_PlanUpdate `protobuf:"bytes,7,opt,name=plan_update,json=planUpdate,proto3,oneof"`}+type IssueCommentPayload_ReviewSubmission_ struct {+ ReviewSubmission *IssueCommentPayload_ReviewSubmission `protobuf:"bytes,8,opt,name=review_submission,json=reviewSubmission,proto3,oneof"`+}+func (*IssueCommentPayload_Approval_) isIssueCommentPayload_Event() {}func (*IssueCommentPayload_IssueUpdate_) isIssueCommentPayload_Event() {}func (*IssueCommentPayload_PlanUpdate_) isIssueCommentPayload_Event() {}+func (*IssueCommentPayload_ReviewSubmission_) isIssueCommentPayload_Event() {}+type IssueCommentPayload_Approval struct {state protoimpl.MessageState `protogen:"open.v1"`Status IssuePayloadApproval_Approver_Status `protobuf:"varint,1,opt,name=status,proto3,enum=bytebase.store.IssuePayloadApproval_Approver_Status" json:"status,omitempty"`@@ -271,6 +287,43 @@ func (x *IssueCommentPayload_IssueUpdate) GetToLabels() []string {return nil}+// ReviewSubmission records that an issue entered review.+type IssueCommentPayload_ReviewSubmission struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *IssueCommentPayload_ReviewSubmission) Reset() {+ *x = IssueCommentPayload_ReviewSubmission{}+ mi := &file_store_issue_comment_proto_msgTypes[3]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *IssueCommentPayload_ReviewSubmission) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*IssueCommentPayload_ReviewSubmission) ProtoMessage() {}++func (x *IssueCommentPayload_ReviewSubmission) ProtoReflect() protoreflect.Message {+ mi := &file_store_issue_comment_proto_msgTypes[3]+ 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 IssueCommentPayload_ReviewSubmission.ProtoReflect.Descriptor instead.+func (*IssueCommentPayload_ReviewSubmission) Descriptor() ([]byte, []int) {+ return file_store_issue_comment_proto_rawDescGZIP(), []int{0, 2}+}+// PlanUpdate carries before/after snapshots of plan.config.specs,// emitted once per PlanService.UpdatePlan call whose specs branch// produces a non-cosmetic diff. The renderer computes per-spec@@ -285,7 +338,7 @@ type IssueCommentPayload_PlanUpdate struct {func (x *IssueCommentPayload_PlanUpdate) Reset() {*x = IssueCommentPayload_PlanUpdate{}- mi := &file_store_issue_comment_proto_msgTypes[3]+ mi := &file_store_issue_comment_proto_msgTypes[4]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -297,7 +350,7 @@ func (x *IssueCommentPayload_PlanUpdate) String() string {func (*IssueCommentPayload_PlanUpdate) ProtoMessage() {}func (x *IssueCommentPayload_PlanUpdate) ProtoReflect() protoreflect.Message {- mi := &file_store_issue_comment_proto_msgTypes[3]+ mi := &file_store_issue_comment_proto_msgTypes[4]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -310,7 +363,7 @@ func (x *IssueCommentPayload_PlanUpdate) ProtoReflect() protoreflect.Message {// Deprecated: Use IssueCommentPayload_PlanUpdate.ProtoReflect.Descriptor instead.func (*IssueCommentPayload_PlanUpdate) Descriptor() ([]byte, []int) {- return file_store_issue_comment_proto_rawDescGZIP(), []int{0, 2}+ return file_store_issue_comment_proto_rawDescGZIP(), []int{0, 3}}func (x *IssueCommentPayload_PlanUpdate) GetFromSpecs() []*PlanConfig_Spec {@@ -331,13 +384,14 @@ var File_store_issue_comment_proto protoreflect.FileDescriptorconst file_store_issue_comment_proto_rawDesc = "" +"\n" +- "\x19store/issue_comment.proto\x12\x0ebytebase.store\x1a\x14store/approval.proto\x1a\x11store/issue.proto\x1a\x10store/plan.proto\"\xe6\a\n" ++ "\x19store/issue_comment.proto\x12\x0ebytebase.store\x1a\x14store/approval.proto\x1a\x11store/issue.proto\x1a\x10store/plan.proto\"\xdf\b\n" +"\x13IssueCommentPayload\x12\x18\n" +"\acomment\x18\x01 \x01(\tR\acomment\x12J\n" +"\bapproval\x18\x02 \x01(\v2,.bytebase.store.IssueCommentPayload.ApprovalH\x00R\bapproval\x12T\n" +"\fissue_update\x18\x03 \x01(\v2/.bytebase.store.IssueCommentPayload.IssueUpdateH\x00R\vissueUpdate\x12Q\n" +"\vplan_update\x18\a \x01(\v2..bytebase.store.IssueCommentPayload.PlanUpdateH\x00R\n" +- "planUpdate\x1aX\n" ++ "planUpdate\x12c\n" ++ "\x11review_submission\x18\b \x01(\v24.bytebase.store.IssueCommentPayload.ReviewSubmissionH\x00R\x10reviewSubmission\x1aX\n" +"\bApproval\x12L\n" +"\x06status\x18\x01 \x01(\x0e24.bytebase.store.IssuePayloadApproval.Approver.StatusR\x06status\x1a\xd1\x03\n" +"\vIssueUpdate\x12\"\n" +@@ -358,7 +412,8 @@ const file_store_issue_comment_proto_rawDesc = "" +"\x0f_to_descriptionB\x0e\n" +"\f_from_statusB\f\n" +"\n" +- "_to_status\x1a\x88\x01\n" ++ "_to_status\x1a\x12\n" ++ "\x10ReviewSubmission\x1a\x88\x01\n" +"\n" +"PlanUpdate\x12>\n" +"\n" +@@ -379,30 +434,32 @@ func file_store_issue_comment_proto_rawDescGZIP() []byte {return file_store_issue_comment_proto_rawDescData}-var file_store_issue_comment_proto_msgTypes = make([]protoimpl.MessageInfo, 4)+var file_store_issue_comment_proto_msgTypes = make([]protoimpl.MessageInfo, 5)var file_store_issue_comment_proto_goTypes = []any{- (*IssueCommentPayload)(nil), // 0: bytebase.store.IssueCommentPayload- (*IssueCommentPayload_Approval)(nil), // 1: bytebase.store.IssueCommentPayload.Approval- (*IssueCommentPayload_IssueUpdate)(nil), // 2: bytebase.store.IssueCommentPayload.IssueUpdate- (*IssueCommentPayload_PlanUpdate)(nil), // 3: bytebase.store.IssueCommentPayload.PlanUpdate- (IssuePayloadApproval_Approver_Status)(0), // 4: bytebase.store.IssuePayloadApproval.Approver.Status- (Issue_Status)(0), // 5: bytebase.store.Issue.Status- (*PlanConfig_Spec)(nil), // 6: bytebase.store.PlanConfig.Spec+ (*IssueCommentPayload)(nil), // 0: bytebase.store.IssueCommentPayload+ (*IssueCommentPayload_Approval)(nil), // 1: bytebase.store.IssueCommentPayload.Approval+ (*IssueCommentPayload_IssueUpdate)(nil), // 2: bytebase.store.IssueCommentPayload.IssueUpdate+ (*IssueCommentPayload_ReviewSubmission)(nil), // 3: bytebase.store.IssueCommentPayload.ReviewSubmission+ (*IssueCommentPayload_PlanUpdate)(nil), // 4: bytebase.store.IssueCommentPayload.PlanUpdate+ (IssuePayloadApproval_Approver_Status)(0), // 5: bytebase.store.IssuePayloadApproval.Approver.Status+ (Issue_Status)(0), // 6: bytebase.store.Issue.Status+ (*PlanConfig_Spec)(nil), // 7: bytebase.store.PlanConfig.Spec}var file_store_issue_comment_proto_depIdxs = []int32{1, // 0: bytebase.store.IssueCommentPayload.approval:type_name -> bytebase.store.IssueCommentPayload.Approval2, // 1: bytebase.store.IssueCommentPayload.issue_update:type_name -> bytebase.store.IssueCommentPayload.IssueUpdate- 3, // 2: bytebase.store.IssueCommentPayload.plan_update:type_name -> bytebase.store.IssueCommentPayload.PlanUpdate- 4, // 3: bytebase.store.IssueCommentPayload.Approval.status:type_name -> bytebase.store.IssuePayloadApproval.Approver.Status- 5, // 4: bytebase.store.IssueCommentPayload.IssueUpdate.from_status:type_name -> bytebase.store.Issue.Status- 5, // 5: bytebase.store.IssueCommentPayload.IssueUpdate.to_status:type_name -> bytebase.store.Issue.Status- 6, // 6: bytebase.store.IssueCommentPayload.PlanUpdate.from_specs:type_name -> bytebase.store.PlanConfig.Spec- 6, // 7: bytebase.store.IssueCommentPayload.PlanUpdate.to_specs:type_name -> bytebase.store.PlanConfig.Spec- 8, // [8:8] is the sub-list for method output_type- 8, // [8:8] is the sub-list for method input_type- 8, // [8:8] is the sub-list for extension type_name- 8, // [8:8] is the sub-list for extension extendee- 0, // [0:8] is the sub-list for field type_name+ 4, // 2: bytebase.store.IssueCommentPayload.plan_update:type_name -> bytebase.store.IssueCommentPayload.PlanUpdate+ 3, // 3: bytebase.store.IssueCommentPayload.review_submission:type_name -> bytebase.store.IssueCommentPayload.ReviewSubmission+ 5, // 4: bytebase.store.IssueCommentPayload.Approval.status:type_name -> bytebase.store.IssuePayloadApproval.Approver.Status+ 6, // 5: bytebase.store.IssueCommentPayload.IssueUpdate.from_status:type_name -> bytebase.store.Issue.Status+ 6, // 6: bytebase.store.IssueCommentPayload.IssueUpdate.to_status:type_name -> bytebase.store.Issue.Status+ 7, // 7: bytebase.store.IssueCommentPayload.PlanUpdate.from_specs:type_name -> bytebase.store.PlanConfig.Spec+ 7, // 8: bytebase.store.IssueCommentPayload.PlanUpdate.to_specs:type_name -> bytebase.store.PlanConfig.Spec+ 9, // [9:9] is the sub-list for method output_type+ 9, // [9:9] is the sub-list for method input_type+ 9, // [9:9] is the sub-list for extension type_name+ 9, // [9:9] is the sub-list for extension extendee+ 0, // [0:9] is the sub-list for field type_name}func init() { file_store_issue_comment_proto_init() }@@ -417,6 +474,7 @@ func file_store_issue_comment_proto_init() {(*IssueCommentPayload_Approval_)(nil),(*IssueCommentPayload_IssueUpdate_)(nil),(*IssueCommentPayload_PlanUpdate_)(nil),+ (*IssueCommentPayload_ReviewSubmission_)(nil),}file_store_issue_comment_proto_msgTypes[2].OneofWrappers = []any{}type x struct{}@@ -425,7 +483,7 @@ func file_store_issue_comment_proto_init() {GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_store_issue_comment_proto_rawDesc), len(file_store_issue_comment_proto_rawDesc)),NumEnums: 0,- NumMessages: 4,+ NumMessages: 5,NumExtensions: 0,NumServices: 0,},diff --git a/backend/generated-go/store/issue_comment_equal.pb.go b/backend/generated-go/store/issue_comment_equal.pb.goindex 5382872d66..ee81fd40ca 100644--- a/backend/generated-go/store/issue_comment_equal.pb.go+++ b/backend/generated-go/store/issue_comment_equal.pb.go@@ -60,6 +60,16 @@ func (x *IssueCommentPayload_IssueUpdate) Equal(y *IssueCommentPayload_IssueUpdareturn true}+func (x *IssueCommentPayload_ReviewSubmission) Equal(y *IssueCommentPayload_ReviewSubmission) bool {+ if x == y {+ return true+ }+ if x == nil || y == nil {+ return x == nil && y == nil+ }+ return true+}+func (x *IssueCommentPayload_PlanUpdate) Equal(y *IssueCommentPayload_PlanUpdate) bool {if x == y {return true@@ -105,5 +115,8 @@ func (x *IssueCommentPayload) Equal(y *IssueCommentPayload) bool {if !x.GetPlanUpdate().Equal(y.GetPlanUpdate()) {return false}+ if !x.GetReviewSubmission().Equal(y.GetReviewSubmission()) {+ return false+ }return true}diff --git a/backend/generated-go/v1/common.pb.go b/backend/generated-go/v1/common.pb.goindex ad6bf3c096..29738774c4 100644--- a/backend/generated-go/v1/common.pb.go+++ b/backend/generated-go/v1/common.pb.go@@ -346,7 +346,7 @@ func (ExportFormat) EnumDescriptor() ([]byte, []int) {type ApprovalStatus int32const (- // Unspecified approval status.+ // No approval workflow has started, including for a linked draft issue.ApprovalStatus_APPROVAL_STATUS_UNSPECIFIED ApprovalStatus = 0// Approval checks are being evaluated.ApprovalStatus_CHECKING ApprovalStatus = 1diff --git a/backend/generated-go/v1/issue_service.pb.go b/backend/generated-go/v1/issue_service.pb.goindex 27c2fcf325..e1b411d7d9 100644--- a/backend/generated-go/v1/issue_service.pb.go+++ b/backend/generated-go/v1/issue_service.pb.go@@ -1744,6 +1744,7 @@ type IssueComment struct {// *IssueComment_Approval_// *IssueComment_IssueUpdate_// *IssueComment_PlanUpdate_+ // *IssueComment_ReviewSubmission_Event isIssueComment_Event `protobuf_oneof:"event"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache@@ -1855,6 +1856,15 @@ func (x *IssueComment) GetPlanUpdate() *IssueComment_PlanUpdate {return nil}+func (x *IssueComment) GetReviewSubmission() *IssueComment_ReviewSubmission {+ if x != nil {+ if x, ok := x.Event.(*IssueComment_ReviewSubmission_); ok {+ return x.ReviewSubmission+ }+ }+ return nil+}+type isIssueComment_Event interface {isIssueComment_Event()}@@ -1874,12 +1884,19 @@ type IssueComment_PlanUpdate_ struct {PlanUpdate *IssueComment_PlanUpdate `protobuf:"bytes,12,opt,name=plan_update,json=planUpdate,proto3,oneof"`}+type IssueComment_ReviewSubmission_ struct {+ // Review submission event.+ ReviewSubmission *IssueComment_ReviewSubmission `protobuf:"bytes,13,opt,name=review_submission,json=reviewSubmission,proto3,oneof"`+}+func (*IssueComment_Approval_) isIssueComment_Event() {}func (*IssueComment_IssueUpdate_) isIssueComment_Event() {}func (*IssueComment_PlanUpdate_) isIssueComment_Event() {}+func (*IssueComment_ReviewSubmission_) isIssueComment_Event() {}+// Approvers and their approval status for the issue.type Issue_Approver struct {state protoimpl.MessageState `protogen:"open.v1"`@@ -2082,6 +2099,43 @@ func (x *IssueComment_IssueUpdate) GetToLabels() []string {return nil}+// Review submission event information.+type IssueComment_ReviewSubmission struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *IssueComment_ReviewSubmission) Reset() {+ *x = IssueComment_ReviewSubmission{}+ mi := &file_v1_issue_service_proto_msgTypes[25]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *IssueComment_ReviewSubmission) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*IssueComment_ReviewSubmission) ProtoMessage() {}++func (x *IssueComment_ReviewSubmission) ProtoReflect() protoreflect.Message {+ mi := &file_v1_issue_service_proto_msgTypes[25]+ 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 IssueComment_ReviewSubmission.ProtoReflect.Descriptor instead.+func (*IssueComment_ReviewSubmission) Descriptor() ([]byte, []int) {+ return file_v1_issue_service_proto_rawDescGZIP(), []int{21, 2}+}+// Plan update event information (snapshot of plan.config.specs before// and after a PlanService.UpdatePlan call that mutated specs).type IssueComment_PlanUpdate struct {@@ -2094,7 +2148,7 @@ type IssueComment_PlanUpdate struct {func (x *IssueComment_PlanUpdate) Reset() {*x = IssueComment_PlanUpdate{}- mi := &file_v1_issue_service_proto_msgTypes[25]+ mi := &file_v1_issue_service_proto_msgTypes[26]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)}@@ -2106,7 +2160,7 @@ func (x *IssueComment_PlanUpdate) String() string {func (*IssueComment_PlanUpdate) ProtoMessage() {}func (x *IssueComment_PlanUpdate) ProtoReflect() protoreflect.Message {- mi := &file_v1_issue_service_proto_msgTypes[25]+ mi := &file_v1_issue_service_proto_msgTypes[26]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {@@ -2119,7 +2173,7 @@ func (x *IssueComment_PlanUpdate) ProtoReflect() protoreflect.Message {// Deprecated: Use IssueComment_PlanUpdate.ProtoReflect.Descriptor instead.func (*IssueComment_PlanUpdate) Descriptor() ([]byte, []int) {- return file_v1_issue_service_proto_rawDescGZIP(), []int{21, 2}+ return file_v1_issue_service_proto_rawDescGZIP(), []int{21, 3}}func (x *IssueComment_PlanUpdate) GetFromSpecs() []*Plan_Spec {@@ -2272,7 +2326,8 @@ const file_v1_issue_service_proto_rawDesc = "" +"\rissue_comment\x18\x02 \x01(\v2\x19.bytebase.v1.IssueCommentR\fissueComment\x12@\n" +"\vupdate_mask\x18\x03 \x01(\v2\x1a.google.protobuf.FieldMaskB\x03\xe0A\x02R\n" +"updateMask\x12#\n" +- "\rallow_missing\x18\x04 \x01(\bR\fallowMissing\"\xc3\t\n" ++ "\rallow_missing\x18\x04 \x01(\bR\fallowMissing\"\xb2\n" ++ "\n" +"\fIssueComment\x12\x12\n" +"\x04name\x18\x01 \x01(\tR\x04name\x12#\n" +"\acomment\x18\x02 \x01(\tB\t\xbaH\x06r\x04\x18\x80\x80\x04R\acomment\x12\x18\n" +@@ -2285,7 +2340,8 @@ const file_v1_issue_service_proto_rawDesc = "" +"\bapproval\x18\a \x01(\v2\".bytebase.v1.IssueComment.ApprovalH\x00R\bapproval\x12J\n" +"\fissue_update\x18\b \x01(\v2%.bytebase.v1.IssueComment.IssueUpdateH\x00R\vissueUpdate\x12G\n" +"\vplan_update\x18\f \x01(\v2$.bytebase.v1.IssueComment.PlanUpdateH\x00R\n" +- "planUpdate\x1a\x98\x01\n" ++ "planUpdate\x12Y\n" ++ "\x11review_submission\x18\r \x01(\v2*.bytebase.v1.IssueComment.ReviewSubmissionH\x00R\x10reviewSubmission\x1a\x98\x01\n" +"\bApproval\x12A\n" +"\x06status\x18\x01 \x01(\x0e2).bytebase.v1.IssueComment.Approval.StatusR\x06status\"I\n" +"\x06Status\x12\x16\n" +@@ -2311,7 +2367,8 @@ const file_v1_issue_service_proto_rawDesc = "" +"\x0f_to_descriptionB\x0e\n" +"\f_from_statusB\f\n" +"\n" +- "_to_status\x1av\n" ++ "_to_status\x1a\x12\n" ++ "\x10ReviewSubmission\x1av\n" +"\n" +"PlanUpdate\x125\n" +"\n" +@@ -2353,7 +2410,7 @@ func file_v1_issue_service_proto_rawDescGZIP() []byte {}var file_v1_issue_service_proto_enumTypes = make([]protoimpl.EnumInfo, 4)-var file_v1_issue_service_proto_msgTypes = make([]protoimpl.MessageInfo, 26)+var file_v1_issue_service_proto_msgTypes = make([]protoimpl.MessageInfo, 27)var file_v1_issue_service_proto_goTypes = []any{(IssueStatus)(0), // 0: bytebase.v1.IssueStatus(Issue_Type)(0), // 1: bytebase.v1.Issue.Type@@ -2384,80 +2441,82 @@ var file_v1_issue_service_proto_goTypes = []any{(*Issue_Approver)(nil), // 26: bytebase.v1.Issue.Approver(*IssueComment_Approval)(nil), // 27: bytebase.v1.IssueComment.Approval(*IssueComment_IssueUpdate)(nil), // 28: bytebase.v1.IssueComment.IssueUpdate- (*IssueComment_PlanUpdate)(nil), // 29: bytebase.v1.IssueComment.PlanUpdate- (*fieldmaskpb.FieldMask)(nil), // 30: google.protobuf.FieldMask- (*timestamppb.Timestamp)(nil), // 31: google.protobuf.Timestamp- (RiskLevel)(0), // 32: bytebase.v1.RiskLevel- (ApprovalStatus)(0), // 33: bytebase.v1.ApprovalStatus- (*expr.Expr)(nil), // 34: google.type.Expr- (*durationpb.Duration)(nil), // 35: google.protobuf.Duration- (*Plan_Spec)(nil), // 36: bytebase.v1.Plan.Spec+ (*IssueComment_ReviewSubmission)(nil), // 29: bytebase.v1.IssueComment.ReviewSubmission+ (*IssueComment_PlanUpdate)(nil), // 30: bytebase.v1.IssueComment.PlanUpdate+ (*fieldmaskpb.FieldMask)(nil), // 31: google.protobuf.FieldMask+ (*timestamppb.Timestamp)(nil), // 32: google.protobuf.Timestamp+ (RiskLevel)(0), // 33: bytebase.v1.RiskLevel+ (ApprovalStatus)(0), // 34: bytebase.v1.ApprovalStatus+ (*expr.Expr)(nil), // 35: google.type.Expr+ (*durationpb.Duration)(nil), // 36: google.protobuf.Duration+ (*Plan_Spec)(nil), // 37: bytebase.v1.Plan.Spec}var file_v1_issue_service_proto_depIdxs = []int32{17, // 0: bytebase.v1.CreateIssueRequest.issue:type_name -> bytebase.v1.Issue17, // 1: bytebase.v1.ListIssuesResponse.issues:type_name -> bytebase.v1.Issue17, // 2: bytebase.v1.SearchIssuesResponse.issues:type_name -> bytebase.v1.Issue17, // 3: bytebase.v1.UpdateIssueRequest.issue:type_name -> bytebase.v1.Issue- 30, // 4: bytebase.v1.UpdateIssueRequest.update_mask:type_name -> google.protobuf.FieldMask+ 31, // 4: bytebase.v1.UpdateIssueRequest.update_mask:type_name -> google.protobuf.FieldMask0, // 5: bytebase.v1.BatchUpdateIssuesStatusRequest.status:type_name -> bytebase.v1.IssueStatus1, // 6: bytebase.v1.Issue.type:type_name -> bytebase.v1.Issue.Type0, // 7: bytebase.v1.Issue.status:type_name -> bytebase.v1.IssueStatus26, // 8: bytebase.v1.Issue.approvers:type_name -> bytebase.v1.Issue.Approver19, // 9: bytebase.v1.Issue.approval_template:type_name -> bytebase.v1.ApprovalTemplate- 31, // 10: bytebase.v1.Issue.create_time:type_name -> google.protobuf.Timestamp- 31, // 11: bytebase.v1.Issue.update_time:type_name -> google.protobuf.Timestamp+ 32, // 10: bytebase.v1.Issue.create_time:type_name -> google.protobuf.Timestamp+ 32, // 11: bytebase.v1.Issue.update_time:type_name -> google.protobuf.Timestamp18, // 12: bytebase.v1.Issue.role_grant:type_name -> bytebase.v1.RoleGrant- 32, // 13: bytebase.v1.Issue.risk_level:type_name -> bytebase.v1.RiskLevel- 33, // 14: bytebase.v1.Issue.approval_status:type_name -> bytebase.v1.ApprovalStatus- 34, // 15: bytebase.v1.RoleGrant.condition:type_name -> google.type.Expr- 35, // 16: bytebase.v1.RoleGrant.expiration:type_name -> google.protobuf.Duration+ 33, // 13: bytebase.v1.Issue.risk_level:type_name -> bytebase.v1.RiskLevel+ 34, // 14: bytebase.v1.Issue.approval_status:type_name -> bytebase.v1.ApprovalStatus+ 35, // 15: bytebase.v1.RoleGrant.condition:type_name -> google.type.Expr+ 36, // 16: bytebase.v1.RoleGrant.expiration:type_name -> google.protobuf.Duration20, // 17: bytebase.v1.ApprovalTemplate.flow:type_name -> bytebase.v1.ApprovalFlow25, // 18: bytebase.v1.ListIssueCommentsResponse.issue_comments:type_name -> bytebase.v1.IssueComment25, // 19: bytebase.v1.CreateIssueCommentRequest.issue_comment:type_name -> bytebase.v1.IssueComment25, // 20: bytebase.v1.UpdateIssueCommentRequest.issue_comment:type_name -> bytebase.v1.IssueComment- 30, // 21: bytebase.v1.UpdateIssueCommentRequest.update_mask:type_name -> google.protobuf.FieldMask- 31, // 22: bytebase.v1.IssueComment.create_time:type_name -> google.protobuf.Timestamp- 31, // 23: bytebase.v1.IssueComment.update_time:type_name -> google.protobuf.Timestamp+ 31, // 21: bytebase.v1.UpdateIssueCommentRequest.update_mask:type_name -> google.protobuf.FieldMask+ 32, // 22: bytebase.v1.IssueComment.create_time:type_name -> google.protobuf.Timestamp+ 32, // 23: bytebase.v1.IssueComment.update_time:type_name -> google.protobuf.Timestamp27, // 24: bytebase.v1.IssueComment.approval:type_name -> bytebase.v1.IssueComment.Approval28, // 25: bytebase.v1.IssueComment.issue_update:type_name -> bytebase.v1.IssueComment.IssueUpdate- 29, // 26: bytebase.v1.IssueComment.plan_update:type_name -> bytebase.v1.IssueComment.PlanUpdate- 2, // 27: bytebase.v1.Issue.Approver.status:type_name -> bytebase.v1.Issue.Approver.Status- 3, // 28: bytebase.v1.IssueComment.Approval.status:type_name -> bytebase.v1.IssueComment.Approval.Status- 0, // 29: bytebase.v1.IssueComment.IssueUpdate.from_status:type_name -> bytebase.v1.IssueStatus- 0, // 30: bytebase.v1.IssueComment.IssueUpdate.to_status:type_name -> bytebase.v1.IssueStatus- 36, // 31: bytebase.v1.IssueComment.PlanUpdate.from_specs:type_name -> bytebase.v1.Plan.Spec- 36, // 32: bytebase.v1.IssueComment.PlanUpdate.to_specs:type_name -> bytebase.v1.Plan.Spec- 4, // 33: bytebase.v1.IssueService.GetIssue:input_type -> bytebase.v1.GetIssueRequest- 5, // 34: bytebase.v1.IssueService.CreateIssue:input_type -> bytebase.v1.CreateIssueRequest- 6, // 35: bytebase.v1.IssueService.ListIssues:input_type -> bytebase.v1.ListIssuesRequest- 8, // 36: bytebase.v1.IssueService.SearchIssues:input_type -> bytebase.v1.SearchIssuesRequest- 10, // 37: bytebase.v1.IssueService.UpdateIssue:input_type -> bytebase.v1.UpdateIssueRequest- 21, // 38: bytebase.v1.IssueService.ListIssueComments:input_type -> bytebase.v1.ListIssueCommentsRequest- 23, // 39: bytebase.v1.IssueService.CreateIssueComment:input_type -> bytebase.v1.CreateIssueCommentRequest- 24, // 40: bytebase.v1.IssueService.UpdateIssueComment:input_type -> bytebase.v1.UpdateIssueCommentRequest- 11, // 41: bytebase.v1.IssueService.BatchUpdateIssuesStatus:input_type -> bytebase.v1.BatchUpdateIssuesStatusRequest- 13, // 42: bytebase.v1.IssueService.ApproveIssue:input_type -> bytebase.v1.ApproveIssueRequest- 14, // 43: bytebase.v1.IssueService.RejectIssue:input_type -> bytebase.v1.RejectIssueRequest- 15, // 44: bytebase.v1.IssueService.RequestIssue:input_type -> bytebase.v1.RequestIssueRequest- 16, // 45: bytebase.v1.IssueService.RetryIssueApproval:input_type -> bytebase.v1.RetryIssueApprovalRequest- 17, // 46: bytebase.v1.IssueService.GetIssue:output_type -> bytebase.v1.Issue- 17, // 47: bytebase.v1.IssueService.CreateIssue:output_type -> bytebase.v1.Issue- 7, // 48: bytebase.v1.IssueService.ListIssues:output_type -> bytebase.v1.ListIssuesResponse- 9, // 49: bytebase.v1.IssueService.SearchIssues:output_type -> bytebase.v1.SearchIssuesResponse- 17, // 50: bytebase.v1.IssueService.UpdateIssue:output_type -> bytebase.v1.Issue- 22, // 51: bytebase.v1.IssueService.ListIssueComments:output_type -> bytebase.v1.ListIssueCommentsResponse- 25, // 52: bytebase.v1.IssueService.CreateIssueComment:output_type -> bytebase.v1.IssueComment- 25, // 53: bytebase.v1.IssueService.UpdateIssueComment:output_type -> bytebase.v1.IssueComment- 12, // 54: bytebase.v1.IssueService.BatchUpdateIssuesStatus:output_type -> bytebase.v1.BatchUpdateIssuesStatusResponse- 17, // 55: bytebase.v1.IssueService.ApproveIssue:output_type -> bytebase.v1.Issue- 17, // 56: bytebase.v1.IssueService.RejectIssue:output_type -> bytebase.v1.Issue- 17, // 57: bytebase.v1.IssueService.RequestIssue:output_type -> bytebase.v1.Issue- 17, // 58: bytebase.v1.IssueService.RetryIssueApproval:output_type -> bytebase.v1.Issue- 46, // [46:59] is the sub-list for method output_type- 33, // [33:46] is the sub-list for method input_type- 33, // [33:33] is the sub-list for extension type_name- 33, // [33:33] is the sub-list for extension extendee- 0, // [0:33] is the sub-list for field type_name+ 30, // 26: bytebase.v1.IssueComment.plan_update:type_name -> bytebase.v1.IssueComment.PlanUpdate+ 29, // 27: bytebase.v1.IssueComment.review_submission:type_name -> bytebase.v1.IssueComment.ReviewSubmission+ 2, // 28: bytebase.v1.Issue.Approver.status:type_name -> bytebase.v1.Issue.Approver.Status+ 3, // 29: bytebase.v1.IssueComment.Approval.status:type_name -> bytebase.v1.IssueComment.Approval.Status+ 0, // 30: bytebase.v1.IssueComment.IssueUpdate.from_status:type_name -> bytebase.v1.IssueStatus+ 0, // 31: bytebase.v1.IssueComment.IssueUpdate.to_status:type_name -> bytebase.v1.IssueStatus+ 37, // 32: bytebase.v1.IssueComment.PlanUpdate.from_specs:type_name -> bytebase.v1.Plan.Spec+ 37, // 33: bytebase.v1.IssueComment.PlanUpdate.to_specs:type_name -> bytebase.v1.Plan.Spec+ 4, // 34: bytebase.v1.IssueService.GetIssue:input_type -> bytebase.v1.GetIssueRequest+ 5, // 35: bytebase.v1.IssueService.CreateIssue:input_type -> bytebase.v1.CreateIssueRequest+ 6, // 36: bytebase.v1.IssueService.ListIssues:input_type -> bytebase.v1.ListIssuesRequest+ 8, // 37: bytebase.v1.IssueService.SearchIssues:input_type -> bytebase.v1.SearchIssuesRequest+ 10, // 38: bytebase.v1.IssueService.UpdateIssue:input_type -> bytebase.v1.UpdateIssueRequest+ 21, // 39: bytebase.v1.IssueService.ListIssueComments:input_type -> bytebase.v1.ListIssueCommentsRequest+ 23, // 40: bytebase.v1.IssueService.CreateIssueComment:input_type -> bytebase.v1.CreateIssueCommentRequest+ 24, // 41: bytebase.v1.IssueService.UpdateIssueComment:input_type -> bytebase.v1.UpdateIssueCommentRequest+ 11, // 42: bytebase.v1.IssueService.BatchUpdateIssuesStatus:input_type -> bytebase.v1.BatchUpdateIssuesStatusRequest+ 13, // 43: bytebase.v1.IssueService.ApproveIssue:input_type -> bytebase.v1.ApproveIssueRequest+ 14, // 44: bytebase.v1.IssueService.RejectIssue:input_type -> bytebase.v1.RejectIssueRequest+ 15, // 45: bytebase.v1.IssueService.RequestIssue:input_type -> bytebase.v1.RequestIssueRequest+ 16, // 46: bytebase.v1.IssueService.RetryIssueApproval:input_type -> bytebase.v1.RetryIssueApprovalRequest+ 17, // 47: bytebase.v1.IssueService.GetIssue:output_type -> bytebase.v1.Issue+ 17, // 48: bytebase.v1.IssueService.CreateIssue:output_type -> bytebase.v1.Issue+ 7, // 49: bytebase.v1.IssueService.ListIssues:output_type -> bytebase.v1.ListIssuesResponse+ 9, // 50: bytebase.v1.IssueService.SearchIssues:output_type -> bytebase.v1.SearchIssuesResponse+ 17, // 51: bytebase.v1.IssueService.UpdateIssue:output_type -> bytebase.v1.Issue+ 22, // 52: bytebase.v1.IssueService.ListIssueComments:output_type -> bytebase.v1.ListIssueCommentsResponse+ 25, // 53: bytebase.v1.IssueService.CreateIssueComment:output_type -> bytebase.v1.IssueComment+ 25, // 54: bytebase.v1.IssueService.UpdateIssueComment:output_type -> bytebase.v1.IssueComment+ 12, // 55: bytebase.v1.IssueService.BatchUpdateIssuesStatus:output_type -> bytebase.v1.BatchUpdateIssuesStatusResponse+ 17, // 56: bytebase.v1.IssueService.ApproveIssue:output_type -> bytebase.v1.Issue+ 17, // 57: bytebase.v1.IssueService.RejectIssue:output_type -> bytebase.v1.Issue+ 17, // 58: bytebase.v1.IssueService.RequestIssue:output_type -> bytebase.v1.Issue+ 17, // 59: bytebase.v1.IssueService.RetryIssueApproval:output_type -> bytebase.v1.Issue+ 47, // [47:60] is the sub-list for method output_type+ 34, // [34:47] is the sub-list for method input_type+ 34, // [34:34] is the sub-list for extension type_name+ 34, // [34:34] is the sub-list for extension extendee+ 0, // [0:34] is the sub-list for field type_name}func init() { file_v1_issue_service_proto_init() }@@ -2472,6 +2531,7 @@ func file_v1_issue_service_proto_init() {(*IssueComment_Approval_)(nil),(*IssueComment_IssueUpdate_)(nil),(*IssueComment_PlanUpdate_)(nil),+ (*IssueComment_ReviewSubmission_)(nil),}file_v1_issue_service_proto_msgTypes[24].OneofWrappers = []any{}type x struct{}@@ -2480,7 +2540,7 @@ func file_v1_issue_service_proto_init() {GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_v1_issue_service_proto_rawDesc), len(file_v1_issue_service_proto_rawDesc)),NumEnums: 4,- NumMessages: 26,+ NumMessages: 27,NumExtensions: 0,NumServices: 1,},diff --git a/backend/generated-go/v1/issue_service_equal.pb.go b/backend/generated-go/v1/issue_service_equal.pb.goindex 08e42905ae..036c2d862d 100644--- a/backend/generated-go/v1/issue_service_equal.pb.go+++ b/backend/generated-go/v1/issue_service_equal.pb.go@@ -547,6 +547,16 @@ func (x *IssueComment_IssueUpdate) Equal(y *IssueComment_IssueUpdate) bool {return true}+func (x *IssueComment_ReviewSubmission) Equal(y *IssueComment_ReviewSubmission) bool {+ if x == y {+ return true+ }+ if x == nil || y == nil {+ return x == nil && y == nil+ }+ return true+}+func (x *IssueComment_PlanUpdate) Equal(y *IssueComment_PlanUpdate) bool {if x == y {return true@@ -607,5 +617,8 @@ func (x *IssueComment) Equal(y *IssueComment) bool {if !x.GetPlanUpdate().Equal(y.GetPlanUpdate()) {return false}+ if !x.GetReviewSubmission().Equal(y.GetReviewSubmission()) {+ return false+ }return true}diff --git a/backend/store/issue.go b/backend/store/issue.goindex e4d2351942..cb309fda43 100644--- a/backend/store/issue.go+++ b/backend/store/issue.go@@ -497,8 +497,13 @@ func (s *Store) BatchUpdateIssueStatuses(ctx context.Context, projectID string,}defer tx.Rollback()- // Fetch current issues to validate project membership and get old statuses.- fetchQuery := qb.Q().Space("SELECT id, status FROM issue WHERE id = ANY(?) AND project = ?", issueUIDs, projectID)+ // Lock current issues to serialize status changes with draft submission.+ fetchQuery := qb.Q().Space(`+ SELECT id, status, COALESCE((payload->>'draft')::boolean, false)+ FROM issue+ WHERE id = ANY(?) AND project = ?+ ORDER BY id+ FOR UPDATE`, issueUIDs, projectID)fetchSQL, fetchArgs, err := fetchQuery.ToSQL()if err != nil {return nil, errors.Wrapf(err, "failed to build fetch sql")@@ -514,7 +519,8 @@ func (s *Store) BatchUpdateIssueStatuses(ctx context.Context, projectID string,for rows.Next() {var issueID int64var statusString string- if err := rows.Scan(&issueID, &statusString); err != nil {+ var draft bool+ if err := rows.Scan(&issueID, &statusString, &draft); err != nil {return nil, errors.Wrapf(err, "failed to scan issue")}statusValue, ok := storepb.Issue_Status_value[statusString]@@ -522,6 +528,9 @@ func (s *Store) BatchUpdateIssueStatuses(ctx context.Context, projectID string,return nil, errors.Errorf("invalid status string: %s", statusString)}issueStatus := storepb.Issue_Status(statusValue)+ if draft {+ return nil, &common.Error{Code: common.Invalid, Err: errors.Errorf("cannot change status for draft issue %d; submit the issue first", issueID)}+ }// Prevent changing status from DONE to other statuses.if issueStatus == storepb.Issue_DONE && newStatus != storepb.Issue_DONE {@@ -569,6 +578,11 @@ func getTSVector(text string) string {return tsVector.String()}+// IssueSearchVector builds the stored search vector for issue metadata.+func IssueSearchVector(title, description string) string {+ return getTSVector(fmt.Sprintf("%s %s", title, description))+}+func getTSQuery(text string) string {seg := getSegmenter()parts := seg.Trim(seg.CutSearch(text))diff --git a/backend/store/plan.go b/backend/store/plan.goindex aa5c5c4e0b..d29829ec07 100644--- a/backend/store/plan.go+++ b/backend/store/plan.go@@ -44,6 +44,9 @@ type FindPlanMessage struct {ProjectID stringHasRollout *bool+ // ExcludeMalformedUIPlans excludes active issue-less database plans, except+ // homogeneous release-backed change database plans.+ ExcludeMalformedUIPlans boolLimit *intOffset *int@@ -163,6 +166,35 @@ func (s *Store) ListPlans(ctx context.Context, find *FindPlanMessage) ([]*PlanMeq.And("(plan.config->>'hasRollout' IS NULL OR plan.config->>'hasRollout' = ?)", "false")}}+ if find.ExcludeMalformedUIPlans {+ q.And(`(+ plan.deleted+ OR EXISTS (+ SELECT 1+ FROM issue+ WHERE issue.project = plan.project+ AND issue.plan_id = plan.id+ )+ OR NOT EXISTS (+ SELECT 1+ FROM jsonb_array_elements(plan.config->'specs') AS spec+ WHERE spec->'createDatabaseConfig' IS NOT NULL+ OR spec->'changeDatabaseConfig' IS NOT NULL+ )+ OR (+ NOT EXISTS (+ SELECT 1+ FROM jsonb_array_elements(plan.config->'specs') AS spec+ WHERE spec->'changeDatabaseConfig' IS NULL+ )+ AND EXISTS (+ SELECT 1+ FROM jsonb_array_elements(plan.config->'specs') AS spec+ WHERE NULLIF(spec->'changeDatabaseConfig'->>'release', '') IS NOT NULL+ )+ )+ )`)+ }q.Space("ORDER BY id DESC")if v := find.Limit; v != nil {diff --git a/backend/store/plan_check_run.go b/backend/store/plan_check_run.goindex 434349fffb..fb5a036118 100644--- a/backend/store/plan_check_run.go+++ b/backend/store/plan_check_run.go@@ -2,6 +2,7 @@ package storeimport ("context"+ "database/sql""time""github.com/pkg/errors"@@ -69,6 +70,20 @@ func (s *Store) CreatePlanCheckRun(ctx context.Context, create *PlanCheckRunMessreturn false, errors.Wrapf(err, "failed to begin tx")}defer tx.Rollback()+ if err := acquirePlanIssueRolloutAdvisoryLock(ctx, tx, create.ProjectID, create.PlanUID); err != nil {+ return false, errors.Wrap(err, "failed to acquire Plan review lock for Plan check run")+ }+ var lockedPlanUID int64+ if err := tx.QueryRowContext(ctx, `+ SELECT id+ FROM plan+ WHERE project = $1 AND id = $2+ FOR UPDATE`, create.ProjectID, create.PlanUID).Scan(&lockedPlanUID); err != nil {+ if errors.Is(err, sql.ErrNoRows) {+ return false, nil+ }+ return false, errors.Wrap(err, "failed to lock Plan for Plan check run")+ }nextID, err := nextProjectID(ctx, tx, "plan_check_run", create.ProjectID)if err != nil {diff --git a/backend/tests/plan_draft_collision_test.go b/backend/tests/plan_draft_collision_test.gonew file mode 100644index 0000000000..860bb26f75--- /dev/null+++ b/backend/tests/plan_draft_collision_test.go@@ -0,0 +1,86 @@+package tests++import (+ "context"+ "testing"+ "time"++ "connectrpc.com/connect"+ "github.com/google/uuid"+ "github.com/stretchr/testify/require"+ "google.golang.org/protobuf/types/known/fieldmaskpb"++ "github.com/bytebase/bytebase/backend/common"+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"+)++func TestCollision_PlanDraftMetadataSync(t *testing.T) {+ t.Parallel()+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ defer cancel()+ ctl := &controller{}+ ctx, err := ctl.StartServerWithExternalPg(ctx)+ require.NoError(t, err)+ defer ctl.Close(ctx)++ fixture := setupCollidingProjects(ctx, t, ctl)+ createDraft := func(project *v1pb.Project, database *v1pb.Database, title string) (*v1pb.Plan, *v1pb.Issue) {+ t.Helper()+ sheet, err := ctl.sheetServiceClient.CreateSheet(ctx, connect.NewRequest(&v1pb.CreateSheetRequest{+ Parent: project.Name,+ Sheet: &v1pb.Sheet{Content: []byte("SELECT 1;")},+ }))+ require.NoError(t, err)+ plan, err := ctl.planServiceClient.CreatePlan(ctx, connect.NewRequest(&v1pb.CreatePlanRequest{+ Parent: project.Name,+ Plan: &v1pb.Plan{+ Title: title,+ Specs: []*v1pb.Plan_Spec{{+ Id: uuid.NewString(),+ Config: &v1pb.Plan_Spec_ChangeDatabaseConfig{+ ChangeDatabaseConfig: &v1pb.Plan_ChangeDatabaseConfig{+ Targets: []string{database.Name},+ Sheet: sheet.Msg.Name,+ },+ },+ }},+ },+ }))+ require.NoError(t, err)+ issue, err := ctl.issueServiceClient.CreateIssue(ctx, connect.NewRequest(&v1pb.CreateIssueRequest{+ Parent: project.Name,+ Issue: &v1pb.Issue{+ Title: title,+ Type: v1pb.Issue_DATABASE_CHANGE,+ Plan: plan.Msg.Name,+ Draft: true,+ },+ }))+ require.NoError(t, err)+ return plan.Msg, issue.Msg+ }++ planA, issueA := createDraft(fixture.ProjectA, fixture.DatabaseA, "Draft A")+ _, issueB := createDraft(fixture.ProjectB, fixture.DatabaseB, "Draft B")+ beforeB := snapshotProject(ctx, t, ctl, fixture.ProjectB)++ const updatedTitle = "Updated draft A"+ _, err = ctl.planServiceClient.UpdatePlan(ctx, connect.NewRequest(&v1pb.UpdatePlanRequest{+ Plan: &v1pb.Plan{Name: planA.Name, Title: updatedTitle},+ UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{"title"}},+ }))+ require.NoError(t, err)++ updatedIssueA, err := ctl.issueServiceClient.GetIssue(ctx, connect.NewRequest(&v1pb.GetIssueRequest{Name: issueA.Name}))+ require.NoError(t, err)+ require.Equal(t, updatedTitle, updatedIssueA.Msg.Title)+ require.True(t, updatedIssueA.Msg.Draft)+ _, issueAUID, err := common.GetProjectIDIssueUID(issueA.Name)+ require.NoError(t, err)+ _, issueBUID, err := common.GetProjectIDIssueUID(issueB.Name)+ require.NoError(t, err)+ require.Equal(t, issueAUID, issueBUID, "draft issue IDs must collide across projects")++ afterB := snapshotProject(ctx, t, ctl, fixture.ProjectB)+ assertProjectUnchanged(t, beforeB, afterB, "project B after Plan A draft metadata sync")+}diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 3c54d38441..c482f0527a 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1520,7 +1520,6 @@"plan": {"add-spec": "Add Change","add-spec-pending-draft": "Save or discard the pending change before adding another",- "cannot-create": "Cannot create plan","checks": {"completed": "Plan checks completed","failed-to-run": "Failed to run plan checks",@@ -1533,6 +1532,7 @@"description": {"placeholder": "Add description"},+ "draft-update-permission-required": "You can view this draft, but you need bb.issues.update to edit labels or submit it for review.","editor": {"save-changes-before-continuing": "Please save or cancel your changes before continuing"},@@ -1564,6 +1564,7 @@"gate-review-approved": "Changes approved","gate-review-pending": "Review in progress","gate-review-rejected": "Changes requested",+ "incomplete": "Incomplete","preparing-rollout": "Preparing rollout…","rejected": "Rejected","rerun": "Rerun",@@ -1660,6 +1661,11 @@"title": "Rejected by {{user}}"}},+ "rollback": {+ "description_one": "Roll back 1 selected task from rollout #{{rolloutId}}.",+ "description_other": "Roll back {{count}} selected tasks from rollout #{{rolloutId}}.",+ "title": "Rollback rollout #{{rolloutId}}"+ },"run": "Run checks","select-isolation-level": "Select isolation level","select-targets": "Select Targets",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 4535ef6188..069c4310b6 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -1520,7 +1520,6 @@"plan": {"add-spec": "Agregar cambio","add-spec-pending-draft": "Guarda o descarta el cambio pendiente antes de agregar otro",- "cannot-create": "No se puede crear el plan","checks": {"completed": "Se completaron las verificaciones del plan","failed-to-run": "No se pudieron ejecutar las verificaciones del plan",@@ -1533,6 +1532,7 @@"description": {"placeholder": "Agregar descripción"},+ "draft-update-permission-required": "Puedes ver este borrador, pero necesitas bb.issues.update para editar etiquetas o enviarlo a revisión.","editor": {"save-changes-before-continuing": "Guarde o cancele sus cambios antes de continuar."},@@ -1564,6 +1564,7 @@"gate-review-approved": "Cambios aprobados","gate-review-pending": "Revisión en curso","gate-review-rejected": "Cambios solicitados",+ "incomplete": "Incompleto","preparing-rollout": "Preparando despliegue…","rejected": "Rechazado","rerun": "Reejecutar",@@ -1660,6 +1661,11 @@"title": "Rechazado por {{user}}"}},+ "rollback": {+ "description_one": "Revertir 1 tarea seleccionada del rollout #{{rolloutId}}.",+ "description_other": "Revertir {{count}} tareas seleccionadas del rollout #{{rolloutId}}.",+ "title": "Revertir rollout #{{rolloutId}}"+ },"run": "Volver a verificar","select-isolation-level": "Seleccionar nivel de aislamiento","select-targets": "Seleccionar destinos",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex d41ad5f7e6..00813266ba 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -1520,7 +1520,6 @@"plan": {"add-spec": "変更を追加","add-spec-pending-draft": "新しい変更を追加する前に、保留中の変更を保存または破棄してください",- "cannot-create": "プランを作成できません","checks": {"completed": "プランチェックが完了しました","failed-to-run": "プランチェックの実行に失敗しました",@@ -1533,6 +1532,7 @@"description": {"placeholder": "説明を追加"},+ "draft-update-permission-required": "この下書きは表示できますが、ラベルの編集やレビューへの提出には bb.issues.update が必要です。","editor": {"save-changes-before-continuing": "続行する前に変更を保存またはキャンセルしてください"},@@ -1564,6 +1564,7 @@"gate-review-approved": "変更が承認されました","gate-review-pending": "レビュー中","gate-review-rejected": "変更がリクエストされました",+ "incomplete": "未完了","preparing-rollout": "ロールアウトを準備中…","rejected": "却下されました","rerun": "再実行",@@ -1660,6 +1661,11 @@"title": "{{user}} に却下されました"}},+ "rollback": {+ "description_one": "ロールアウト #{{rolloutId}} の選択したタスク 1 件をロールバックします。",+ "description_other": "ロールアウト #{{rolloutId}} の選択したタスク {{count}} 件をロールバックします。",+ "title": "ロールアウト #{{rolloutId}} のロールバック"+ },"run": "再チェック","select-isolation-level": "分離レベルを選択","select-targets": "対象を選択",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 75ed87a541..96b7dfa779 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -1520,7 +1520,6 @@"plan": {"add-spec": "Thêm thay đổi","add-spec-pending-draft": "Lưu hoặc hủy thay đổi đang chờ trước khi thêm thay đổi khác",- "cannot-create": "Không thể tạo kế hoạch","checks": {"completed": "Đã hoàn thành kiểm tra kế hoạch","failed-to-run": "Không thể chạy kiểm tra kế hoạch",@@ -1533,6 +1532,7 @@"description": {"placeholder": "Thêm mô tả"},+ "draft-update-permission-required": "Bạn có thể xem bản nháp này, nhưng cần bb.issues.update để chỉnh sửa nhãn hoặc gửi đi xem xét.","editor": {"save-changes-before-continuing": "Vui lòng lưu hoặc hủy thay đổi của bạn trước khi tiếp tục"},@@ -1564,6 +1564,7 @@"gate-review-approved": "Đã duyệt thay đổi","gate-review-pending": "Đang xem xét","gate-review-rejected": "Yêu cầu thay đổi",+ "incomplete": "Chưa hoàn tất","preparing-rollout": "Đang chuẩn bị triển khai…","rejected": "Đã từ chối","rerun": "Chạy lại",@@ -1660,6 +1661,11 @@"title": "Bị {{user}} từ chối"}},+ "rollback": {+ "description_one": "Hoàn tác 1 tác vụ đã chọn từ bản triển khai #{{rolloutId}}.",+ "description_other": "Hoàn tác {{count}} tác vụ đã chọn từ bản triển khai #{{rolloutId}}.",+ "title": "Hoàn tác bản triển khai #{{rolloutId}}"+ },"run": "Kiểm tra lại","select-isolation-level": "Chọn mức độ cô lập","select-targets": "Chọn mục tiêu",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex b07952e2db..a3a08613e6 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1520,7 +1520,6 @@"plan": {"add-spec": "添加变更","add-spec-pending-draft": "请先保存或放弃当前的待处理变更,然后再添加新变更",- "cannot-create": "无法创建变更计划","checks": {"completed": "已完成计划检查","failed-to-run": "运行计划检查失败",@@ -1533,6 +1532,7 @@"description": {"placeholder": "添加描述"},+ "draft-update-permission-required": "你可以查看此草稿,但需要 bb.issues.update 才能编辑标签或提交审批。","editor": {"save-changes-before-continuing": "请保存或取消更改,然后再继续"},@@ -1564,6 +1564,7 @@"gate-review-approved": "变更已批准","gate-review-pending": "审批中","gate-review-rejected": "请求变更",+ "incomplete": "不完整","preparing-rollout": "正在准备发布…","rejected": "已拒绝","rerun": "重新执行",@@ -1660,6 +1661,11 @@"title": "被 {{user}} 拒绝"}},+ "rollback": {+ "description_one": "回滚发布 #{{rolloutId}} 中选中的 1 个任务。",+ "description_other": "回滚发布 #{{rolloutId}} 中选中的 {{count}} 个任务。",+ "title": "回滚发布 #{{rolloutId}}"+ },"run": "重新检查","select-isolation-level": "选择隔离级别","select-targets": "选择目标",diff --git a/frontend/src/react/components/database/CreateDatabaseSheet.test.tsx b/frontend/src/react/components/database/CreateDatabaseSheet.test.tsxindex ec307744e4..d4aaa62895 100644--- a/frontend/src/react/components/database/CreateDatabaseSheet.test.tsx+++ b/frontend/src/react/components/database/CreateDatabaseSheet.test.tsx@@ -3,7 +3,7 @@ import type {InputHTMLAttributes,ReactNode,} from "react";-import { act, createElement } from "react";+import { act, createElement, useSyncExternalStore } from "react";import { createRoot } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { Engine } from "@/types/proto-es/v1/common_pb";@@ -23,7 +23,7 @@ vi.mock("@/react/components/InstanceSelect", () => ({"data-portal": String(Boolean(props.portal)),value: props.value,onChange: (e: React.ChangeEvent<HTMLInputElement>) =>- props.onChange(e.target.value, undefined),+ props.onChange(e.target.value, mocks.instancesByName[e.target.value]),}),}));@@ -56,6 +56,14 @@ vi.mock("@/react/components/ui/button", () => ({createElement("button", { disabled, onClick }, children),}));+vi.mock("@/react/components/PermissionGuard", () => ({+ PermissionGuard: ({ children }: { children: ReactNode }) => children,+ usePermissionCheck: (permissions: string[]) => [+ permissions.every((permission) => mocks.permissions[permission] !== false),+ undefined,+ ],+}));+vi.mock("@/react/components/ui/input", () => ({Input: ({ className: _c, ...props }: InputHTMLAttributes<HTMLInputElement>) =>createElement("input", props),@@ -104,52 +112,90 @@ vi.mock("@/types/proto-es/v1/plan_service_pb", () => ({Plan_CreateDatabaseConfigSchema: {},Plan_SpecSchema: {},PlanSchema: {},+ CreatePlanRequestSchema: {},}));vi.mock("@/types/proto-es/v1/issue_service_pb", () => ({Issue_Type: { DATABASE_CHANGE: 1 },+ IssueStatus: { OPEN: 1 },+ CreateIssueRequestSchema: {},IssueSchema: {},}));const mocks = vi.hoisted(() => ({- getOrFetchProjectByName: vi.fn(),- getProjectByName: vi.fn(),- getOrFetchInstanceByName: vi.fn(),- experimentalCreateIssueByPlan: vi.fn(),+ createIssue: vi.fn(),+ createPlan: vi.fn(),currentUser: { name: "users/[email protected]", email: "[email protected]" },+ getOrFetchInstanceByName: vi.fn(),+ getOrFetchProjectByName: vi.fn(),+ instancesByName: {} as Record<string, unknown>,+ permissions: {} as Record<string, boolean>,+ pushNotification: vi.fn(),+ routerPush: vi.fn(),}));vi.mock("@/store", () => ({- pushNotification: vi.fn(),+ pushNotification: mocks.pushNotification,}));-// The app store exposes both a callable selector form-// (`useAppStore((s) => s.projectsByName)`) and an imperative-// `useAppStore.getState()` form. The project methods that previously lived on-// the Pinia `useProjectV1Store` now live here.+const UNKNOWN_PROJECT = {+ name: "projects/-1",+ enforceIssueTitle: true,+ issueLabels: [],+ forceIssueLabels: false,+};+const storeListeners = new Set<() => void>();const appStoreState = {- get getOrFetchProjectByName() {- return mocks.getOrFetchProjectByName;+ environmentList: [] as { name: string; title: string }[],+ fetchProjectList: vi.fn().mockResolvedValue({ projects: [] }),+ get getOrFetchInstanceByName() {+ return mocks.getOrFetchInstanceByName;},- get getProjectByName() {- return mocks.getProjectByName;+ getOrFetchProjectByName: async (name: string) => {+ const cached = appStoreState.getProjectByName(name);+ if (cached.name === name) return cached;+ const project = await mocks.getOrFetchProjectByName(name);+ if (project.name === name) {+ appStoreState.projectsByName = {+ ...appStoreState.projectsByName,+ [name]: project,+ };+ for (const listener of storeListeners) listener();+ }+ return project;},- getOrFetchInstanceByName: mocks.getOrFetchInstanceByName,- fetchProjectList: vi.fn().mockResolvedValue({ projects: [] }),- projectsByName: {},- environmentList: [],+ getProjectByName: (name: string) =>+ appStoreState.projectsByName[name] ?? UNKNOWN_PROJECT,+ projectsByName: {} as Record<+ string,+ {+ name: string;+ enforceIssueTitle: boolean;+ issueLabels: { value: string }[];+ forceIssueLabels: boolean;+ }+ >,};vi.mock("@/react/stores/app", () => ({useAppStore: Object.assign(- (selector: (state: unknown) => unknown) => selector(appStoreState),+ (selector: (state: typeof appStoreState) => unknown) =>+ useSyncExternalStore(+ (listener) => {+ storeListeners.add(listener);+ return () => storeListeners.delete(listener);+ },+ () => selector(appStoreState),+ () => selector(appStoreState)+ ),{getState: () => appStoreState,}),}));-vi.mock("@/react/stores/app/issue", () => ({- experimentalCreateIssueByPlan: mocks.experimentalCreateIssueByPlan,+vi.mock("@/connect", () => ({+ issueServiceClientConnect: { createIssue: mocks.createIssue },+ planServiceClientConnect: { createPlan: mocks.createPlan },}));vi.mock("@/react/hooks/useAppState", () => ({@@ -160,14 +206,15 @@ vi.mock("react-i18next", () => ({useTranslation: () => ({ t: (key: string) => key }),}));-vi.mock("@/react/router", async (importOriginal) => ({- ...(await importOriginal<typeof import("@/react/router")>()),- router: { push: vi.fn() },+vi.mock("@/react/router", () => ({+ router: { push: mocks.routerPush },}));vi.mock("@/types", () => ({isValidProjectName: (name: string) =>- typeof name === "string" && name.startsWith("projects/"),+ typeof name === "string" &&+ name.startsWith("projects/") &&+ name !== "projects/-1",isValidInstanceName: (name: string) =>typeof name === "string" && name.startsWith("instances/"),defaultCharsetOfEngineV1: () => "utf8",@@ -176,8 +223,9 @@ vi.mock("@/types", () => ({vi.mock("@/utils", () => ({enginesSupportCreateDatabase: () => [],+ extractPlanUID: (name: string) => name.split("/").at(-1) ?? "",+ extractProjectResourceName: (name: string) => name.split("/")[1] ?? "",getDefaultPagination: () => 20,- getIssueRoute: vi.fn(() => "/issues/1"),instanceV1HasCollationAndCharacterSet: () => false,normalizeTitle: (s: string) => s.trim(),}));@@ -199,6 +247,19 @@ beforeEach(() => {container = document.createElement("div");document.body.appendChild(container);root = createRoot(container);+ appStoreState.environmentList = [];+ appStoreState.projectsByName = {};+ mocks.instancesByName = {};+ mocks.permissions = {};+ mocks.createPlan.mockResolvedValue({+ name: "projects/foo/plans/123",+ title: "Create database 'widgets'",+ });+ mocks.createIssue.mockResolvedValue({+ name: "projects/foo/issues/456",+ draft: true,+ plan: "projects/foo/plans/123",+ });});afterEach(() => {@@ -209,16 +270,13 @@ afterEach(() => {});function setupProjectMock(enforceIssueTitle: boolean) {- mocks.getProjectByName.mockReturnValue({+ mocks.getOrFetchProjectByName.mockImplementation(async (name: string) => ({+ name,enforceIssueTitle,issueLabels: [],forceIssueLabels: false,- });- mocks.getOrFetchProjectByName.mockResolvedValue({- enforceIssueTitle,- issueLabels: [],- forceIssueLabels: false,- });+ }));+ mocks.instancesByName[TEST_INSTANCE.name] = TEST_INSTANCE;mocks.getOrFetchInstanceByName.mockResolvedValue(TEST_INSTANCE);}@@ -250,12 +308,12 @@ async function renderSheetWithoutFixedProject(): Promise<void> {});}-async function fillInstance(): Promise<void> {+async function fillInstance(name = TEST_INSTANCE.name): Promise<void> {const input = container.querySelector("[data-testid='instance-select']") as HTMLInputElement;await act(async () => {- nativeChange(input, TEST_INSTANCE.name);+ nativeChange(input, name);});}@@ -302,6 +360,134 @@ describe("CreateDatabaseSheet — enforceIssueTitle (BYT-9310)", () => {expect(instanceSelect.dataset.portal).toBe("true");});+ it("hydrates a fixed project only when an always-mounted sheet opens", async () => {+ setupProjectMock(false);+ await act(async () => {+ root.render(+ createElement(CreateDatabaseSheet, {+ open: false,+ onClose: () => {},+ projectName: "projects/foo",+ })+ );+ await Promise.resolve();+ await Promise.resolve();+ });++ expect(mocks.getOrFetchProjectByName).not.toHaveBeenCalled();++ await act(async () => {+ root.render(+ createElement(CreateDatabaseSheet, {+ open: true,+ onClose: () => {},+ projectName: "projects/foo",+ })+ );+ await Promise.resolve();+ await Promise.resolve();+ });+ await fillInstance();+ await fillDatabaseName("widgets");+ await flush();++ expect(mocks.getOrFetchProjectByName).toHaveBeenCalledOnce();+ expect(mocks.getOrFetchProjectByName).toHaveBeenCalledWith("projects/foo");+ expect(getCreateButton().disabled).toBe(false);+ });++ it("clears the inherited environment when switching to an instance without one", async () => {+ setupProjectMock(false);+ const emptyEnvironmentInstance = {+ name: "instances/no-environment",+ engine: Engine.MYSQL,+ environment: "",+ };+ mocks.instancesByName[emptyEnvironmentInstance.name] =+ emptyEnvironmentInstance;+ await renderSheet(false);++ await fillInstance(TEST_INSTANCE.name);+ const environmentInput = container.querySelector(+ "input[placeholder='common.environment']"+ ) as HTMLInputElement;+ expect(environmentInput.value).toBe("environments/dev");++ await fillInstance(emptyEnvironmentInstance.name);+ expect(environmentInput.value).toBe("");+ });++ it("catches an owner-role fetch failure and leaves creation safely disabled", async () => {+ setupProjectMock(false);+ const postgres = {+ name: "instances/postgres",+ engine: Engine.POSTGRES,+ environment: "environments/dev",+ };+ mocks.instancesByName[postgres.name] = postgres;+ await renderSheet(false);+ mocks.getOrFetchInstanceByName.mockRejectedValue(+ new Error("role lookup failed")+ );++ await fillInstance(postgres.name);+ await fillDatabaseName("widgets");+ await flush();++ expect(getCreateButton().disabled).toBe(true);+ expect(mocks.pushNotification).toHaveBeenCalledWith(+ expect.objectContaining({+ description: "role lookup failed",+ style: "CRITICAL",+ })+ );+ });++ it("invalidates a stale owner-role failure after selecting a non-owner instance", async () => {+ setupProjectMock(false);+ const postgres = {+ name: "instances/postgres",+ engine: Engine.POSTGRES,+ environment: "environments/dev",+ };+ mocks.instancesByName[postgres.name] = postgres;+ await renderSheet(false);+ const roles = Promise.withResolvers<typeof postgres>();+ mocks.getOrFetchInstanceByName.mockReturnValue(roles.promise);++ await fillInstance(postgres.name);+ await fillInstance(TEST_INSTANCE.name);+ roles.reject(new Error("stale role lookup failed"));+ await flush();++ expect(mocks.pushNotification).not.toHaveBeenCalled();+ });++ it("portals owner and environment dropdowns from the sheet body", async () => {+ setupProjectMock(false);+ const postgres = {+ name: "instances/postgres",+ engine: Engine.POSTGRES,+ environment: "environments/dev",+ roles: [{ name: "instances/postgres/roles/app", roleName: "app" }],+ };+ mocks.instancesByName[postgres.name] = postgres;+ await renderSheet(false);+ mocks.getOrFetchInstanceByName.mockResolvedValue(postgres);++ await fillInstance(postgres.name);+ await flush();++ const ownerInput = container.querySelector(+ "input[placeholder='create-db.database-owner-name']"+ ) as HTMLInputElement;+ const environmentInput = container.querySelector(+ "input[placeholder='common.environment']"+ ) as HTMLInputElement;+ expect(ownerInput.dataset.portal).toBe("true");+ expect(environmentInput.dataset.portal).toBe("true");+ });+it("auto-fills title from database name when enforceIssueTitle is false", async () => {await renderSheet(false);await fillInstance();@@ -418,14 +604,15 @@ describe("CreateDatabaseSheet — enforceIssueTitle (BYT-9310)", () => {expect(getCreateButton().disabled).toBe(false);});- it("keeps Create disabled during project hydration even with all fields filled (BYT-9310 governance race)", async () => {- let resolveHydration!: (value: unknown) => void;- const hydrationPromise = new Promise((resolve) => {- resolveHydration = resolve;- });-- mocks.getProjectByName.mockReturnValue(undefined);- mocks.getOrFetchProjectByName.mockReturnValue(hydrationPromise);+ it("keeps Create disabled until project hydration updates the reactive cache", async () => {+ const hydration = Promise.withResolvers<{+ name: string;+ enforceIssueTitle: boolean;+ issueLabels: never[];+ forceIssueLabels: boolean;+ }>();+ mocks.getOrFetchProjectByName.mockReturnValue(hydration.promise);+ mocks.instancesByName[TEST_INSTANCE.name] = TEST_INSTANCE;mocks.getOrFetchInstanceByName.mockResolvedValue(TEST_INSTANCE);await act(async () => {@@ -438,7 +625,6 @@ describe("CreateDatabaseSheet — enforceIssueTitle (BYT-9310)", () => {);await Promise.resolve();});-await fillInstance();await fillDatabaseName("widgets");await flush();@@ -446,12 +632,8 @@ describe("CreateDatabaseSheet — enforceIssueTitle (BYT-9310)", () => {expect(getCreateButton().disabled).toBe(true);await act(async () => {- resolveHydration({- enforceIssueTitle: false,- issueLabels: [],- forceIssueLabels: false,- });- mocks.getProjectByName.mockReturnValue({+ hydration.resolve({+ name: "projects/foo",enforceIssueTitle: false,issueLabels: [],forceIssueLabels: false,@@ -460,27 +642,16 @@ describe("CreateDatabaseSheet — enforceIssueTitle (BYT-9310)", () => {await Promise.resolve();});- // After hydration resolves with enforceIssueTitle: false, the auto-fill- // effect triggers (db name "widgets" was typed earlier), setting title to- // the generated string. Create must now be enabled, proving that- // projectHydrated flipped from false to true (the hydration gate opened).+ expect(appStoreState.projectsByName["projects/foo"]?.name).toBe(+ "projects/foo"+ );expect(getCreateButton().disabled).toBe(false);});- it("recovers from project fetch failure — Create not permanently disabled (BYT-9310 hydration-failed cell)", async () => {- // Design-cell lock: the projectHydrated gate was modeled as 2-state- // (loading → hydrated). A rejected getOrFetchProjectByName would leave- // hydration permanently stuck and Create permanently disabled with no- // recovery path. This test locks the third state (hydration-failed):- // projectHydrated must still flip true, governance still applies via- // the sentinel's enforceIssueTitle=true default, user can type a title- // to proceed.- mocks.getProjectByName.mockReturnValue(undefined);- mocks.getOrFetchProjectByName.mockRejectedValue(- new Error("simulated network failure")- );+ it("does not treat an unknown-project fetch result as a creatable project", async () => {+ mocks.getOrFetchProjectByName.mockResolvedValue(UNKNOWN_PROJECT);+ mocks.instancesByName[TEST_INSTANCE.name] = TEST_INSTANCE;mocks.getOrFetchInstanceByName.mockResolvedValue(TEST_INSTANCE);-await act(async () => {root.render(createElement(CreateDatabaseSheet, {@@ -492,27 +663,237 @@ describe("CreateDatabaseSheet — enforceIssueTitle (BYT-9310)", () => {await Promise.resolve();await Promise.resolve();});+ await fillInstance();+ await fillDatabaseName("widgets");+ await act(async () => {+ nativeChange(getTitleInput(), "Create widgets");+ });++ expect(getCreateButton().disabled).toBe(true);+ expect(mocks.createPlan).not.toHaveBeenCalled();+ });++ it("resets the form and hydrates again when the fixed project changes", async () => {+ setupProjectMock(false);+ await renderSheet(false);+ await fillInstance();+ await fillDatabaseName("widgets");+ await flush();+ expect(getCreateButton().disabled).toBe(false);++ await act(async () => {+ root.render(+ createElement(CreateDatabaseSheet, {+ open: true,+ onClose: () => {},+ projectName: "projects/bar",+ })+ );+ await Promise.resolve();+ await Promise.resolve();+ });++ const databaseInput = container.querySelector(+ "input[placeholder='create-db.new-database-name']"+ ) as HTMLInputElement;+ const instanceInput = container.querySelector(+ "[data-testid='instance-select']"+ ) as HTMLInputElement;+ expect(databaseInput.value).toBe("");+ expect(instanceInput.value).toBe("");+ expect(mocks.getOrFetchProjectByName).toHaveBeenCalledWith("projects/bar");+ expect(getCreateButton().disabled).toBe(true);+ });+ it("creates one Plan and one linked draft Issue with the exact payload", async () => {+ mocks.getOrFetchProjectByName.mockImplementation(async (name: string) => ({+ name,+ enforceIssueTitle: false,+ issueLabels: [{ value: "required" }],+ forceIssueLabels: true,+ }));+ mocks.instancesByName[TEST_INSTANCE.name] = TEST_INSTANCE;+ mocks.getOrFetchInstanceByName.mockResolvedValue(TEST_INSTANCE);+ await act(async () => {+ root.render(+ createElement(CreateDatabaseSheet, {+ open: true,+ onClose: () => {},+ projectName: "projects/foo",+ })+ );+ await Promise.resolve();+ await Promise.resolve();+ });await fillInstance();await fillDatabaseName("widgets");await flush();- // With hydration failed and sentinel projectReactive=undefined,- // enforceIssueTitle = projectHydrated && (undefined ?? false) = false.- // The auto-fill effect then runs, populating the title, so Create is- // reachable. The critical assertion is the button is NOT stuck disabled.expect(getCreateButton().disabled).toBe(false);+ await act(async () => {+ getCreateButton().click();+ await Promise.resolve();+ await Promise.resolve();+ });++ expect(mocks.createPlan).toHaveBeenCalledOnce();+ expect(mocks.createPlan).toHaveBeenCalledWith({+ parent: "projects/foo",+ plan: {+ creator: "users/[email protected]",+ specs: [+ {+ config: {+ case: "createDatabaseConfig",+ value: {+ characterSet: "utf8",+ cluster: "",+ collation: "utf8_general_ci",+ database: "widgets",+ environment: "environments/dev",+ owner: "",+ table: "",+ target: "instances/test-instance",+ },+ },+ id: expect.any(String),+ },+ ],+ title: "quick-action.create-db 'widgets'",+ },+ });+ expect(mocks.createIssue).toHaveBeenCalledOnce();+ expect(mocks.createIssue).toHaveBeenCalledWith({+ issue: {+ creator: "users/[email protected]",+ description: undefined,+ draft: true,+ labels: [],+ plan: "projects/foo/plans/123",+ status: 1,+ title: "Create database 'widgets'",+ type: 1,+ },+ parent: "projects/foo",+ });+ expect(mocks.routerPush).toHaveBeenCalledWith({+ name: "workspace.project.plan.detail",+ params: { planId: "123", projectId: "foo" },+ });+ });- // Clear the auto-fill to confirm the gate would still fire on empty- // input under whatever enforcement policy applies (defensive check that- // the recovery path didn't silently bypass title gating).+ it("ignores a stale create completion after close, reopen, and project switch", async () => {+ setupProjectMock(false);+ const onClose = vi.fn();+ const plan = Promise.withResolvers<{ name: string; title: string }>();+ mocks.createPlan.mockReturnValue(plan.promise);await act(async () => {- nativeChange(getTitleInput(), "");+ root.render(+ createElement(CreateDatabaseSheet, {+ open: true,+ onClose,+ projectName: "projects/foo",+ })+ );+ await Promise.resolve();+ await Promise.resolve();});- // With enforceIssueTitle=false (sentinel + hydrated), an empty title- // is allowed — `effectiveTitle` fallback will fire server-side. The- // backend remains the source of truth and will apply the real project's- // setting on submit.+ await fillInstance();+ await fillDatabaseName("widgets");+ await flush();+ await act(async () => {+ getCreateButton().click();+ await Promise.resolve();+ });+ expect(mocks.createPlan).toHaveBeenCalledOnce();++ await act(async () => {+ root.render(+ createElement(CreateDatabaseSheet, {+ open: false,+ onClose,+ projectName: "projects/foo",+ })+ );+ await Promise.resolve();+ });+ await act(async () => {+ root.render(+ createElement(CreateDatabaseSheet, {+ open: true,+ onClose,+ projectName: "projects/bar",+ })+ );+ await Promise.resolve();+ await Promise.resolve();+ });++ plan.resolve({+ name: "projects/foo/plans/old",+ title: "Create database 'widgets'",+ });+ await flush();+ await flush();++ expect(mocks.createIssue).toHaveBeenCalledOnce();+ expect(onClose).not.toHaveBeenCalled();+ expect(mocks.routerPush).not.toHaveBeenCalled();+ expect(getCreateButton().disabled).toBe(true);+ });++ it("routes to the malformed Plan and surfaces the Issue error without retrying", async () => {+ const failure = new Error("draft issue failed");+ mocks.createIssue.mockRejectedValue(failure);+ await renderSheet(false);+ await fillInstance();+ await fillDatabaseName("widgets");+ await flush();++ await act(async () => {+ getCreateButton().click();+ await Promise.resolve();+ await Promise.resolve();+ });++ expect(mocks.createPlan).toHaveBeenCalledOnce();+ expect(mocks.createIssue).toHaveBeenCalledOnce();+ expect(mocks.routerPush).toHaveBeenCalledWith({+ name: "workspace.project.plan.detail",+ params: { planId: "123", projectId: "foo" },+ });+ expect(mocks.pushNotification).toHaveBeenCalledWith(+ expect.objectContaining({+ description: "Error: draft issue failed",+ style: "CRITICAL",+ })+ );+ });++ it("requires both create permissions but only warns when issue-update is missing", async () => {+ mocks.permissions["bb.issues.update"] = false;+ await renderSheet(false);+ await fillInstance();+ await fillDatabaseName("widgets");+ await flush();+expect(getCreateButton().disabled).toBe(false);+ const permissionAlert = container.querySelector("[role='alert']");+ expect(permissionAlert?.textContent).toContain(+ "plan.draft-update-permission-required"+ );++ mocks.permissions["bb.issues.create"] = false;+ await act(async () => {+ root.render(+ createElement(CreateDatabaseSheet, {+ open: true,+ onClose: () => {},+ projectName: "projects/foo",+ })+ );+ await Promise.resolve();+ });+ expect(getCreateButton().disabled).toBe(true);});});diff --git a/frontend/src/react/components/database/CreateDatabaseSheet.tsx b/frontend/src/react/components/database/CreateDatabaseSheet.tsxindex 5f5ec37de6..a8e9017717 100644--- a/frontend/src/react/components/database/CreateDatabaseSheet.tsx+++ b/frontend/src/react/components/database/CreateDatabaseSheet.tsx@@ -1,14 +1,18 @@import { create } from "@bufbuild/protobuf";-import { useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { v4 as uuidv4 } from "uuid";+import { issueServiceClientConnect, planServiceClientConnect } from "@/connect";import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";import { InstanceSelect } from "@/react/components/InstanceSelect";+import type { IssueLabel } from "@/react/components/IssueLabelSelect";+import { IssueLabelSelect } from "@/react/components/IssueLabelSelect";import {- type IssueLabel,- IssueLabelSelect,-} from "@/react/components/IssueLabelSelect";+ PermissionGuard,+ usePermissionCheck,+} from "@/react/components/PermissionGuard";import { ProjectSelect } from "@/react/components/ProjectSelect";+import { Alert } from "@/react/components/ui/alert";import { Button } from "@/react/components/ui/button";import { Combobox } from "@/react/components/ui/combobox";import {@@ -29,9 +33,13 @@ import {import { useCurrentUser } from "@/react/hooks/useAppState";import { useProjectByName } from "@/react/hooks/useProjectByName";import { cn } from "@/react/lib/utils";+import {+ createPlanWithDraftReview,+ DraftReviewIssueCreationError,+} from "@/react/pages/project/plan-detail/utils/header";import { router } from "@/react/router";+import { PROJECT_V1_ROUTE_PLAN_DETAIL } from "@/react/router/handles";import { useAppStore } from "@/react/stores/app";-import { experimentalCreateIssueByPlan } from "@/react/stores/app/issue";import { pushNotification } from "@/store";import {defaultCharsetOfEngineV1,@@ -41,7 +49,6 @@ import {} from "@/types";import { Engine } from "@/types/proto-es/v1/common_pb";import type { Instance } from "@/types/proto-es/v1/instance_service_pb";-import { Issue_Type, IssueSchema } from "@/types/proto-es/v1/issue_service_pb";import {Plan_CreateDatabaseConfigSchema,Plan_SpecSchema,@@ -49,7 +56,8 @@ import {} from "@/types/proto-es/v1/plan_service_pb";import {enginesSupportCreateDatabase,- getIssueRoute,+ extractPlanUID,+ extractProjectResourceName,instanceV1HasCollationAndCharacterSet,normalizeTitle,} from "@/utils";@@ -63,14 +71,64 @@ export interface CreateDatabaseSheetProps {projectName?: string;}-export function CreateDatabaseSheet({+interface CreateDatabaseSession {+ id: number;+ open: boolean;+ fixedProjectName?: string;+}++export function CreateDatabaseSheet(props: CreateDatabaseSheetProps) {+ const { open, onClose, projectName: fixedProjectName } = props;+ const sessionRef = useRef<CreateDatabaseSession>({+ id: 0,+ open: false,+ fixedProjectName,+ });+ const session = sessionRef.current;+ if (open) {+ if (!session.open || session.fixedProjectName !== fixedProjectName) {+ session.id += 1;+ session.fixedProjectName = fixedProjectName;+ }+ session.open = true;+ } else {+ session.open = false;+ }+ const isSessionActive = useCallback(+ (id: number) => sessionRef.current.open && sessionRef.current.id === id,+ []+ );++ return (+ <Sheet open={open} onOpenChange={(next) => !next && onClose()}>+ <SheetContent width="standard">+ <CreateDatabaseForm+ key={`${session.id}:${session.fixedProjectName ?? ""}`}+ open={open}+ onClose={onClose}+ fixedProjectName={session.fixedProjectName}+ sessionId={session.id}+ isSessionActive={isSessionActive}+ />+ </SheetContent>+ </Sheet>+ );+}++function CreateDatabaseForm({open,onClose,- projectName: fixedProjectName,-}: CreateDatabaseSheetProps) {+ fixedProjectName,+ sessionId,+ isSessionActive,+}: {+ open: boolean;+ onClose: () => void;+ fixedProjectName?: string;+ sessionId: number;+ isSessionActive: (id: number) => boolean;+}) {const { t } = useTranslation();- // subscribe to re-render on project cache change- const projectsByName = useAppStore((s) => s.projectsByName);const currentUser = useCurrentUser();const [projectName, setProjectName] = useState("");@@ -96,78 +154,72 @@ export function CreateDatabaseSheet({const environments = useAppStore((s) => s.environmentList);const [selectedProject, setSelectedProject] = useState<- | {- issueLabels: IssueLabel[];- forceIssueLabels: boolean;- }- | undefined+ { name: string; issueLabels: IssueLabel[] } | undefined>();const effectiveProjectName = fixedProjectName || projectName;- // Intentional split: enforceIssueTitle is read reactively (via the app-store- // project cache) because it's a governance gate that MUST reflect live state- // (workspace-picker swaps change projects mid-form). `issueLabels` /- // `forceIssueLabels` stay on the pre-existing `selectedProject` snapshot- // pattern below — they have a known staleness seam that is out of scope- // for BYT-9310. Do not collapse these back together without a separate spec.- const projectFromName = useProjectByName(effectiveProjectName ?? "");- const projectReactive = effectiveProjectName ? projectFromName : undefined;- void projectsByName;-- // Note on hydration: projectStore.getProjectByName returns an- // unknownProject() sentinel when the project is not yet cached. The sentinel- // has restrictive defaults (enforceIssueTitle=true). Rather than depend on- // the sentinel value, we mask the pre-hydration state entirely with- // `projectHydrated` — this keeps the gate correct regardless of the sentinel- // and makes the intent ("we haven't seen the real project yet") explicit.- const projectHydrated = selectedProject !== undefined;+ // Project hydration and the reactive cache entry must agree on the exact+ // resource name. The store returns an unknown-project sentinel on a miss;+ // that placeholder must never satisfy governance or become a create parent.+ const projectFromName = useProjectByName(effectiveProjectName);+ const projectReactive =+ effectiveProjectName && projectFromName.name === effectiveProjectName+ ? projectFromName+ : undefined;+ const projectHydrated =+ selectedProject?.name === effectiveProjectName &&+ projectReactive !== undefined;const enforceIssueTitle =projectHydrated && (projectReactive?.enforceIssueTitle ?? false);const projectFetchRef = useRef(0);useEffect(() => {+ const fetchId = ++projectFetchRef.current;setIssueLabels([]);setSelectedProject(undefined);- if (!effectiveProjectName) return;- const fetchId = ++projectFetchRef.current;- useAppStore+ if (!open || !isValidProjectName(effectiveProjectName)) return;++ void useAppStore.getState().getOrFetchProjectByName(effectiveProjectName).then((project) => {- if (fetchId !== projectFetchRef.current) return;+ if (+ fetchId !== projectFetchRef.current ||+ !isSessionActive(sessionId) ||+ project.name !== effectiveProjectName ||+ !isValidProjectName(project.name)+ ) {+ return;+ }setSelectedProject({+ name: project.name,issueLabels: project.issueLabels ?? [],- forceIssueLabels: project.forceIssueLabels ?? false,});})- .catch((error) => {- if (fetchId !== projectFetchRef.current) return;- // Hydration-failed cell: without this catch, `projectHydrated` stays- // false forever and `allowCreate` is permanently disabled with no- // recovery path (transient network error, stale project, permission).- // Flip `projectHydrated` with safe defaults so the user can retry.- // The governance gate still applies: `enforceIssueTitle` is read from- // `projectReactive`, which returns the `unknownProject()` sentinel- // (`enforceIssueTitle=true`) when the project isn't cached — forcing- // a manual title, the safe governance default. The backend remains- // the source of truth on submit.- setSelectedProject({ issueLabels: [], forceIssueLabels: false });+ .catch((error: unknown) => {+ if (+ fetchId !== projectFetchRef.current ||+ !isSessionActive(sessionId)+ ) {+ return;+ }pushNotification({module: "bytebase",style: "CRITICAL",title: t("common.error"),- description: String(- (error as { message?: string })?.message ?? error- ),+ description: error instanceof Error ? error.message : String(error),});});- // `t` is intentionally omitted from the dep array: react-i18next's `t`- // is stable across renders in production, and including it causes the- // effect to re-fire spuriously in test harnesses where `useTranslation`- // is mocked to return a fresh closure per render. Same convention as- // the auto-fill effect below.- }, [effectiveProjectName]);++ return () => {+ if (projectFetchRef.current === fetchId) {+ projectFetchRef.current += 1;+ }+ };+ // `t` is stable in production and intentionally omitted because test+ // translation adapters may return a new closure on every render.+ }, [effectiveProjectName, isSessionActive, open, sessionId]);// Auto-fill when the project doesn't enforce manual titles.// Intentional omissions from the dep array: `title` and `titleEdited` are@@ -185,7 +237,14 @@ export function CreateDatabaseSheet({}, [databaseName, enforceIssueTitle, projectHydrated]);const projectIssueLabels = selectedProject?.issueLabels ?? [];- const forceIssueLabels = selectedProject?.forceIssueLabels ?? false;+ const [canCreateDraftReview, createPermissionReason] = usePermissionCheck(+ ["bb.plans.create", "bb.issues.create"],+ projectReactive+ );+ const [canUpdateIssue] = usePermissionCheck(+ ["bb.issues.update"],+ projectReactive+ );const requireOwner =selectedInstance &&@@ -200,57 +259,62 @@ export function CreateDatabaseSheet({!!databaseName &&!isReservedName &&(!requireOwner || !!ownerName) &&- (!forceIssueLabels || issueLabels.length > 0) &&projectHydrated &&+ canCreateDraftReview &&!(enforceIssueTitle && !normalizeTitle(title));+ const instanceFetchRef = useRef(0);useEffect(() => {- if (!open) return;- setProjectName("");- setInstanceName("");- setSelectedInstance(undefined);- setDatabaseName("");- setTableName("");- setCluster("");- setEnvironmentName("");- setOwnerName("");- setIssueLabels([]);- setCharacterSet("");- setCollation("");- setCreating(false);- setInstanceRoles([]);- setTitle("");- setTitleEdited(false);+ if (!open) {+ instanceFetchRef.current += 1;+ }+ return () => {+ instanceFetchRef.current += 1;+ };}, [open]);- const instanceFetchRef = useRef(0);const handleInstanceChange = async (name: string,inst: Instance | undefined) => {+ const fetchId = ++instanceFetchRef.current;setInstanceName(name);setSelectedInstance(inst);setOwnerName("");setTableName("");setCluster("");setInstanceRoles([]);- if (inst?.environment) setEnvironmentName(inst.environment);+ setEnvironmentName(inst?.environment ?? "");if (- inst &&- [Engine.POSTGRES, Engine.REDSHIFT, Engine.COCKROACHDB].includes(+ !inst ||+ ![Engine.POSTGRES, Engine.REDSHIFT, Engine.COCKROACHDB].includes(inst.engine)) {- const fetchId = ++instanceFetchRef.current;+ return;+ }++ try {const full = await useAppStore.getState().getOrFetchInstanceByName(name);- if (fetchId !== instanceFetchRef.current) return;- if (full?.roles) {- setInstanceRoles(- full.roles- .filter((r) => !INTERNAL_RDS_USERS.includes(r.roleName))- .map((r) => ({ name: r.name, roleName: r.roleName }))- );+ if (fetchId !== instanceFetchRef.current || !isSessionActive(sessionId)) {+ return;}+ setInstanceRoles(+ (full.roles ?? [])+ .filter((role) => !INTERNAL_RDS_USERS.includes(role.roleName))+ .map((role) => ({ name: role.name, roleName: role.roleName }))+ );+ } catch (error: unknown) {+ if (fetchId !== instanceFetchRef.current || !isSessionActive(sessionId)) {+ return;+ }+ setInstanceRoles([]);+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.error"),+ description: error instanceof Error ? error.message : String(error),+ });}};@@ -261,6 +325,14 @@ export function CreateDatabaseSheet({const project = await useAppStore.getState().getOrFetchProjectByName(effectiveProjectName);+ if (!isSessionActive(sessionId)) return;+ if (+ !isValidProjectName(project.name) ||+ project.name !== effectiveProjectName+ ) {+ throw new Error(t("common.error"));+ }+const engine = selectedInstance?.engine ?? 0;const createDatabaseConfig = create(Plan_CreateDatabaseConfigSchema, {target: instanceName,@@ -284,250 +356,283 @@ export function CreateDatabaseSheet({specs: [spec],creator: currentUser.name,});- const issueCreate = create(IssueSchema, {- title: effectiveTitle,- type: Issue_Type.DATABASE_CHANGE,+ const { plan: createdPlan } = await createPlanWithDraftReview({+ createIssue: (request) =>+ issueServiceClientConnect.createIssue(request),+ createPlan: (request) => planServiceClientConnect.createPlan(request),creator: `users/${currentUser.email}`,labels: issueLabels,+ parent: effectiveProjectName,+ plan: planCreate,});- const { createdIssue } = await experimentalCreateIssueByPlan(- project,- issueCreate,- planCreate,- { skipRollout: true }- );+ if (!isSessionActive(sessionId)) return;+onClose();- await router.push(getIssueRoute(createdIssue));- } catch (error) {+ await router.push({+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,+ params: {+ projectId: extractProjectResourceName(createdPlan.name),+ planId: extractPlanUID(createdPlan.name),+ },+ });+ } catch (error: unknown) {+ if (!isSessionActive(sessionId)) return;+ if (error instanceof DraftReviewIssueCreationError) {+ onClose();+ await router.push({+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,+ params: {+ projectId: extractProjectResourceName(error.plan.name),+ planId: extractPlanUID(error.plan.name),+ },+ });+ }pushNotification({module: "bytebase",style: "CRITICAL",title: t("common.failed"),- description: String(error),+ description: String(+ error instanceof DraftReviewIssueCreationError ? error.cause : error+ ),});} finally {- setCreating(false);+ if (isSessionActive(sessionId)) {+ setCreating(false);+ }}};- if (!open) return null;-const showCharsetCollation =selectedInstance && instanceV1HasCollationAndCharacterSet(selectedInstance);return (- <Sheet open={open} onOpenChange={(next) => !next && onClose()}>- <SheetContent width="standard">- <SheetHeader>- <SheetTitle>{t("quick-action.create-db")}</SheetTitle>- </SheetHeader>-- <SheetBody>- <FormFieldGroup>- {!fixedProjectName && (- <FormField- title={- <>- {t("common.project")} <span className="text-error">*</span>- </>- }- >- <ProjectSelect- value={projectName}- onChange={(name) => setProjectName(name)}- portal- />- </FormField>- )}-- {selectedProject && projectIssueLabels.length > 0 && (- <IssueLabelSelect- labels={projectIssueLabels}- selected={issueLabels}- required={forceIssueLabels}- onChange={setIssueLabels}- />- )}-+ <>+ <SheetHeader>+ <SheetTitle>{t("quick-action.create-db")}</SheetTitle>+ </SheetHeader>++ <SheetBody>+ <FormFieldGroup>+ {!fixedProjectName && (<FormFieldtitle={<>- {t("common.instance")} <span className="text-error">*</span>+ {t("common.project")} <span className="text-error">*</span></>}>- <InstanceSelect- value={instanceName}- onChange={handleInstanceChange}- engines={enginesSupportCreateDatabase()}+ <ProjectSelect+ value={projectName}+ onChange={(name) => setProjectName(name)}portal/></FormField>-+ )}++ {selectedProject && projectIssueLabels.length > 0 && (+ <IssueLabelSelect+ labels={projectIssueLabels}+ selected={issueLabels}+ required={false}+ onChange={setIssueLabels}+ />+ )}+ {projectHydrated && !canUpdateIssue && (+ <Alert+ variant="warning"+ description={t("plan.draft-update-permission-required")}+ />+ )}++ <FormField+ title={+ <>+ {t("common.instance")} <span className="text-error">*</span>+ </>+ }+ >+ <InstanceSelect+ value={instanceName}+ onChange={handleInstanceChange}+ engines={enginesSupportCreateDatabase()}+ portal+ />+ </FormField>++ <FormField>+ <FormTitle id="create-database-name-title">+ {t("create-db.new-database-name")}{" "}+ <span className="text-error">*</span>+ </FormTitle>+ <Input+ id="create-database-name"+ aria-labelledby="create-database-name-title"+ value={databaseName}+ onChange={(e) => setDatabaseName(e.target.value)}+ placeholder={t("create-db.new-database-name")}+ className={cn(isReservedName && "border-error")}+ />+ {isReservedName && (+ <FormError>+ {t("create-db.reserved-db-error", { databaseName })}+ </FormError>+ )}+ </FormField>++ <FormField>+ <FormTitle id="create-database-title-title">+ {t("create-db.issue-title")}+ {enforceIssueTitle && <span className="text-error"> *</span>}+ </FormTitle>+ <Input+ id="create-database-title"+ aria-labelledby="create-database-title-title"+ value={title}+ placeholder={t("create-db.issue-title")}+ onChange={(e) => {+ const next = e.target.value;+ setTitle(next);+ // Invariant: titleEdited ⇒ title is non-empty user intent.+ // When the user deletes to empty, reset the flag so the+ // auto-fill effect resumes tracking databaseName — otherwise+ // the flag stays sticky and the next auto-fill (first char+ // of a re-typed databaseName) gets frozen by the guard.+ setTitleEdited(next !== "");+ }}+ />+ </FormField>++ {selectedInstance?.engine === Engine.MONGODB && (<FormField>- <FormTitle id="create-database-name-title">- {t("create-db.new-database-name")}{" "}+ <FormTitle id="create-database-collection-name-title">+ {t("create-db.new-collection-name")}{" "}<span className="text-error">*</span></FormTitle><Input- id="create-database-name"- aria-labelledby="create-database-name-title"- value={databaseName}- onChange={(e) => setDatabaseName(e.target.value)}- placeholder={t("create-db.new-database-name")}- className={cn(isReservedName && "border-error")}+ id="create-database-collection-name"+ aria-labelledby="create-database-collection-name-title"+ value={tableName}+ onChange={(e) => setTableName(e.target.value)}/>- {isReservedName && (- <FormError>- {t("create-db.reserved-db-error", { databaseName })}- </FormError>- )}</FormField>+ )}+ {selectedInstance?.engine === Engine.CLICKHOUSE && (<FormField>- <FormTitle id="create-database-title-title">- {t("create-db.issue-title")}- {enforceIssueTitle && <span className="text-error"> *</span>}+ <FormTitle id="create-database-cluster-title">+ {t("create-db.cluster")}</FormTitle><Input- id="create-database-title"- aria-labelledby="create-database-title-title"- value={title}- placeholder={t("create-db.issue-title")}- onChange={(e) => {- const next = e.target.value;- setTitle(next);- // Invariant: titleEdited ⇒ title is non-empty user intent.- // When the user deletes to empty, reset the flag so the- // auto-fill effect resumes tracking databaseName — otherwise- // the flag stays sticky and the next auto-fill (first char- // of a re-typed databaseName) gets frozen by the guard.- setTitleEdited(next !== "");- }}+ id="create-database-cluster"+ aria-labelledby="create-database-cluster-title"+ value={cluster}+ onChange={(e) => setCluster(e.target.value)}/></FormField>+ )}- {selectedInstance?.engine === Engine.MONGODB && (- <FormField>- <FormTitle id="create-database-collection-name-title">- {t("create-db.new-collection-name")}{" "}+ {requireOwner && instanceName && (+ <FormField+ title={+ <>+ {t("create-db.database-owner-name")}{" "}<span className="text-error">*</span>+ </>+ }+ >+ <Combobox+ value={ownerName}+ onChange={setOwnerName}+ placeholder={t("create-db.database-owner-name")}+ noResultsText={t("common.no-data")}+ options={instanceRoles.map((role) => ({+ value: role.roleName,+ label: role.roleName,+ }))}+ portal+ />+ </FormField>+ )}++ <FormField title={<>{t("common.environment")}</>}>+ <Combobox+ value={environmentName}+ onChange={setEnvironmentName}+ placeholder={t("common.environment")}+ noResultsText={t("common.no-data")}+ renderValue={(opt) => (+ <EnvironmentLabel environmentName={opt.value} />+ )}+ options={environments.map((env) => ({+ value: env.name,+ label: env.title,+ render: () => <EnvironmentLabel environmentName={env.name} />,+ }))}+ portal+ />+ </FormField>++ {showCharsetCollation && (+ <>+ <FormField>+ <FormTitle id="create-database-character-set-title">+ {selectedInstance.engine === Engine.POSTGRES+ ? t("db.encoding")+ : t("db.character-set")}</FormTitle><Input- id="create-database-collection-name"- aria-labelledby="create-database-collection-name-title"- value={tableName}- onChange={(e) => setTableName(e.target.value)}+ id="create-database-character-set"+ aria-labelledby="create-database-character-set-title"+ value={characterSet}+ onChange={(e) => setCharacterSet(e.target.value)}+ placeholder={defaultCharsetOfEngineV1(+ selectedInstance.engine+ )}/></FormField>- )}-- {selectedInstance?.engine === Engine.CLICKHOUSE && (<FormField>- <FormTitle id="create-database-cluster-title">- {t("create-db.cluster")}+ <FormTitle id="create-database-collation-title">+ {t("db.collation")}</FormTitle><Input- id="create-database-cluster"- aria-labelledby="create-database-cluster-title"- value={cluster}- onChange={(e) => setCluster(e.target.value)}+ id="create-database-collation"+ aria-labelledby="create-database-collation-title"+ value={collation}+ onChange={(e) => setCollation(e.target.value)}+ placeholder={+ defaultCollationOfEngineV1(selectedInstance.engine) ||+ t("common.default")+ }/></FormField>- )}-- {requireOwner && instanceName && (- <FormField- title={- <>- {t("create-db.database-owner-name")}{" "}- <span className="text-error">*</span>- </>- }- >- <Combobox- value={ownerName}- onChange={setOwnerName}- placeholder={t("create-db.database-owner-name")}- noResultsText={t("common.no-data")}- options={instanceRoles.map((role) => ({- value: role.roleName,- label: role.roleName,- }))}- />- </FormField>- )}-- <FormField title={<>{t("common.environment")}</>}>- <Combobox- value={environmentName}- onChange={setEnvironmentName}- placeholder={t("common.environment")}- noResultsText={t("common.no-data")}- renderValue={(opt) => (- <EnvironmentLabel environmentName={opt.value} />- )}- options={environments.map((env) => ({- value: env.name,- label: env.title,- render: () => <EnvironmentLabel environmentName={env.name} />,- }))}- />- </FormField>-- {showCharsetCollation && (- <>- <FormField>- <FormTitle id="create-database-character-set-title">- {selectedInstance.engine === Engine.POSTGRES- ? t("db.encoding")- : t("db.character-set")}- </FormTitle>- <Input- id="create-database-character-set"- aria-labelledby="create-database-character-set-title"- value={characterSet}- onChange={(e) => setCharacterSet(e.target.value)}- placeholder={defaultCharsetOfEngineV1(- selectedInstance.engine- )}- />- </FormField>- <FormField>- <FormTitle id="create-database-collation-title">- {t("db.collation")}- </FormTitle>- <Input- id="create-database-collation"- aria-labelledby="create-database-collation-title"- value={collation}- onChange={(e) => setCollation(e.target.value)}- placeholder={- defaultCollationOfEngineV1(selectedInstance.engine) ||- t("common.default")- }- />- </FormField>- </>- )}- </FormFieldGroup>- </SheetBody>-- <SheetFooter>- <Button appearance="secondary" onClick={onClose}>- {t("common.cancel")}- </Button>- <Button disabled={!allowCreate || creating} onClick={handleCreate}>+ </>+ )}+ </FormFieldGroup>+ </SheetBody>++ <SheetFooter>+ <Button appearance="secondary" onClick={onClose}>+ {t("common.cancel")}+ </Button>+ <PermissionGuard+ permissions={["bb.plans.create", "bb.issues.create"]}+ project={projectReactive}+ >+ <Button+ disabled={!allowCreate || creating}+ onClick={handleCreate}+ title={createPermissionReason}+ >{t("common.create")}</Button>- </SheetFooter>-- {creating && (- <div className="absolute inset-0 bg-background/60 flex items-center justify-center z-10">- <div className="animate-spin size-6 border-2 border-accent border-t-transparent rounded-full" />- </div>- )}- </SheetContent>- </Sheet>+ </PermissionGuard>+ </SheetFooter>++ {creating && (+ <div className="absolute inset-0 bg-background/60 flex items-center justify-center z-10">+ <div className="animate-spin size-6 border-2 border-accent border-t-transparent rounded-full" />+ </div>+ )}+ </>);}diff --git a/frontend/src/react/components/issue-activity/IssueCommentActivity.test.tsx b/frontend/src/react/components/issue-activity/IssueCommentActivity.test.tsxindex a2e0d3ac2d..2dbaba3f02 100644--- a/frontend/src/react/components/issue-activity/IssueCommentActivity.test.tsx+++ b/frontend/src/react/components/issue-activity/IssueCommentActivity.test.tsx@@ -3,32 +3,66 @@ import { render, screen } from "@testing-library/react";import { describe, expect, test, vi } from "vitest";import {Issue_Type,+ IssueComment_ReviewSubmissionSchema,IssueCommentSchema,IssueSchema,IssueStatus,} from "@/types/proto-es/v1/issue_service_pb";import { PlanSchema } from "@/types/proto-es/v1/plan_service_pb";+import {+ getIssueCommentType,+ IssueCommentType,+} from "@/react/stores/app/issueComment";import { IssueCommentRow } from "./IssueCommentActivity";vi.mock("react-i18next", async (importOriginal) => ({...(await importOriginal<typeof import("react-i18next")>()),- useTranslation: () => ({ t: (key: string) => key }),+ useTranslation: () => ({+ t: (key: string) =>+ key === "plan.review.activity.marked-ready-for-review"+ ? "marked this plan ready for review"+ : key,+ }),}));vi.mock("@/react/stores/app", () => ({useAppStore: (selector: (state: unknown) => unknown) =>selector({- getUserByIdentifier: () => ({- email: "[email protected]",- title: "Alice",- }),+ getUserByIdentifier: (identifier: string) =>+ identifier.includes("alice")+ ? {+ email: "[email protected]",+ title: "Alice",+ }+ : {+ name: "users/[email protected]",+ email: "[email protected]",+ title: "Submitter",+ },}),}));+vi.mock("@/react/components/HumanizeTs", () => ({+ HumanizeTs: () => null,+}));+vi.mock("@/react/components/monaco", () => ({ReadonlyDiffMonaco: () => null,}));+vi.mock("@/react/components/UserAvatar", () => ({+ UserAvatar: () => <span data-testid="user-avatar" />,+}));++const reviewSubmission = create(IssueCommentSchema, {+ name: "projects/p1/issues/1/issueComments/1",+ creator: "users/[email protected]",+ event: {+ case: "reviewSubmission",+ value: create(IssueComment_ReviewSubmissionSchema),+ },+});+describe("IssueCommentRow", () => {test("shows who bypassed review and created the rollout", () => {const issue = create(IssueSchema, {@@ -61,4 +95,21 @@ describe("IssueCommentRow", () => {screen.getByText("activity.sentence.review-skipped-rollout-created")).toBeInTheDocument();});++ test("renders Review Submission as a meaningful Issue Detail activity", () => {+ expect(getIssueCommentType(reviewSubmission)).toBe(+ IssueCommentType.REVIEW_SUBMISSION+ );++ const { container } = render(+ <IssueCommentRow comment={reviewSubmission} isLast={true} />+ );++ expect(screen.getByText("Submitter")).toBeInTheDocument();+ expect(+ screen.getByText("marked this plan ready for review")+ ).toBeInTheDocument();+ expect(container.querySelectorAll(".lucide-send")).toHaveLength(1);+ expect(container.querySelector("[data-testid='user-avatar']")).toBeNull();+ });});diff --git a/frontend/src/react/components/issue-activity/IssueCommentActivity.tsx b/frontend/src/react/components/issue-activity/IssueCommentActivity.tsxindex 5f7bf283e6..5cbc336825 100644--- a/frontend/src/react/components/issue-activity/IssueCommentActivity.tsx+++ b/frontend/src/react/components/issue-activity/IssueCommentActivity.tsx@@ -2,7 +2,7 @@// badge and the human-readable action sentence (including rich plan-spec diff// rows). Used by both the issue-detail comment list and the plan-detail review// timeline so their icons, wordings, and detailed styles stay consistent.-import { Loader2 } from "lucide-react";+import { Loader2, Send } from "lucide-react";import { Fragment, type ReactNode, useEffect, useState } from "react";import { useTranslation } from "react-i18next";import { HumanizeTs } from "@/react/components/HumanizeTs";@@ -312,6 +312,13 @@ function IssueCommentActionIcon({ issue, plan, comment }: ActivityProps) {}}+ if (+ commentType === IssueCommentType.REVIEW_SUBMISSION &&+ comment.event.case === "reviewSubmission"+ ) {+ return <ReviewSubmissionIcon />;+ }+if (commentType === IssueCommentType.PLAN_UPDATE &&comment.event.case === "planUpdate"@@ -360,6 +367,24 @@ export function CommentIconBadge({);}+export function ReviewSubmissionIcon() {+ return (+ <CommentIconBadge+ className="bg-control-bg text-control"+ icon={<Send className="size-4" />}+ />+ );+}++export function ReviewSubmissionSentence() {+ const { t } = useTranslation();+ return (+ <span className="wrap-break-word min-w-0 text-control-light">+ {t("plan.review.activity.marked-ready-for-review")}+ </span>+ );+}+// Renders an activity badge from a design-module icon spec — the white glyph on// a tone-colored circle. The single place activity badges are built.function ActivityBadge({ spec }: { spec: ActivityIconSpec }) {@@ -409,6 +434,13 @@ function IssueCommentActionSentence({}}+ if (+ commentType === IssueCommentType.REVIEW_SUBMISSION &&+ comment.event.case === "reviewSubmission"+ ) {+ return <ReviewSubmissionSentence />;+ }+if (commentType === IssueCommentType.ISSUE_UPDATE &&comment.event.case === "issueUpdate"diff --git a/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx b/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsxindex a501eb23f1..9f3527f0fa 100644--- a/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx+++ b/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx@@ -90,7 +90,13 @@ import {extractStageUID,getStageStatusFromCounts,} from "@/utils/v1/issue/rollout";-import { getReviewBadge, type ReviewBadge } from "./utils/reviewBadge";+import { isReleaseBackedPlan } from "./plan-detail/utils/spec";+import {+ getPlanDraftState,+ getReviewBadge,+ type PlanDraftState,+ type ReviewBadge,+} from "./utils/reviewBadge";// Below Tailwind's `sm` breakpoint (640px) we switch the plan list and the// database picker to their compact mobile layouts.@@ -181,7 +187,10 @@ export function ProjectPlanDashboardPage({ projectId }: { projectId: string }) {[t, listUsers, me]);- const [canCreate] = usePermissionCheck(["bb.plans.create"], project);+ const [canCreate] = usePermissionCheck(+ ["bb.plans.create", "bb.issues.create"],+ project+ );// Build plan filterconst planFilter = useMemo(() => {@@ -293,7 +302,7 @@ export function ProjectPlanDashboardPage({ projectId }: { projectId: string }) {scopeOptions={scopeOptions}/><PermissionGuard- permissions={["bb.plans.create"]}+ permissions={["bb.plans.create", "bb.issues.create"]}project={project}><Button@@ -365,7 +374,7 @@ interface PlanRowContext {updateTimeTs: number;approvalTag: { label: string; variant: ReviewBadge["variant"] } | undefined;isDeleted: boolean;- showDraftTag: boolean;+ draftState: PlanDraftState;}function PlanTable({ plans, projectId }: { plans: Plan[]; projectId: string }) {@@ -400,11 +409,16 @@ function PlanTable({ plans, projectId }: { plans: Plan[]; projectId: string }) {{t("common.closed")}</span>)}- {ctx.showDraftTag && !ctx.isDeleted && (+ {ctx.draftState === "draft" && !ctx.isDeleted && (<span className="inline-flex items-center rounded-full bg-control-bg text-control-light px-2 py-0.5 text-xs shrink-0">{t("common.draft")}</span>)}+ {ctx.draftState === "incomplete" && !ctx.isDeleted && (+ <Badge variant="destructive" className="shrink-0 px-2 text-xs">+ {t("plan.lifecycle.incomplete")}+ </Badge>+ )}</div>),},@@ -560,7 +574,12 @@ function PlanRow({const { t } = useTranslation();const isDeleted = plan.state === State.DELETED;- const showDraftTag = plan.issue === "" && !plan.hasRollout;+ const draftState = getPlanDraftState({+ approvalStatus: plan.approvalStatus,+ hasRollout: plan.hasRollout,+ isGitOpsPlan: isReleaseBackedPlan(plan.specs),+ issueName: plan.issue,+ });const creatorUser = useAppStore((state) =>state.getUserByIdentifier(plan.creator)@@ -618,7 +637,7 @@ function PlanRow({updateTimeTs,approvalTag,isDeleted,- showDraftTag,+ draftState,};return (diff --git a/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.test.tsx b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.test.tsxindex 14989a7434..275a79163b 100644--- a/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.test.tsx+++ b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.test.tsx@@ -59,7 +59,7 @@ vi.mock("@/react/lib/utils", () => ({}));vi.mock("./components/deploy/DeployBranch", () => ({- DeployBranch: () => null,+ DeployBranch: () => <div data-testid="deploy-branch">deploy branch</div>,}));vi.mock("./components/review/PlanReviewSection", () => ({@@ -84,7 +84,9 @@ vi.mock("./components/PlanDetailChangesBranch", () => ({}));vi.mock("./components/PlanDetailDeployFuture", () => ({- PlanDetailDeployFuture: () => null,+ PlanDetailDeployFuture: () => (+ <button data-testid="deploy-future-control">deploy future control</button>+ ),}));vi.mock("./components/PlanDetailHeader", () => ({@@ -195,6 +197,50 @@ describe("ProjectPlanDetailPage", () => {expect(selectedSpecIdText()).toBe("spec-2");});+ it("resets spec selection when navigating to another plan", async () => {+ const firstPage = buildPage();+ firstPage.isCreating = false;+ firstPage.pageKey = "foo/plan-1";+ firstPage.planId = "plan-1";+ mocks.usePlanDetailPage.mockReturnValue(firstPage);++ await act(async () => {+ root.render(+ <ProjectPlanDetailPage+ planId="plan-1"+ projectId="foo"+ specId="spec-1"+ />+ );+ await Promise.resolve();+ });++ await act(async () => {+ (+ [...container.querySelectorAll("button")].find(+ (button) => button.textContent === "select second spec"+ ) as HTMLButtonElement+ ).click();+ await Promise.resolve();+ });+ expect(selectedSpecIdText()).toBe("spec-2");++ const secondPage = buildPage();+ secondPage.isCreating = false;+ secondPage.pageKey = "foo/plan-2";+ secondPage.planId = "plan-2";+ secondPage.plan.specs = [+ { id: "new-spec" },+ ] as typeof secondPage.plan.specs;+ mocks.usePlanDetailPage.mockReturnValue(secondPage);+ await act(async () => {+ root.render(<ProjectPlanDetailPage planId="plan-2" projectId="foo" />);+ await Promise.resolve();+ });++ expect(selectedSpecIdText()).toBe("new-spec");+ });+it("renders the review phase for sheet-backed plans with an issue", async () => {mocks.usePlanDetailPage.mockReturnValue({...buildPage(),@@ -235,6 +281,85 @@ describe("ProjectPlanDetailPage", () => {expect(container.textContent).toContain("plan.phase.review-description");});+ it("recognizes a linked Draft Review Issue as the active draft changes phase", async () => {+ const page = buildPage();+ page.isCreating = false;+ page.planId = "1";+ page.plan.name = "projects/foo/plans/1";+ page.plan.issue = "projects/foo/issues/1";+ page.issue = {+ name: "projects/foo/issues/1",+ draft: true,+ } as PlanDetailPageState["issue"];+ mocks.usePlanDetailPage.mockReturnValue(page);++ await act(async () => {+ root.render(+ <ProjectPlanDetailPage planId="1" projectId="foo" specId="spec-1" />+ );+ await Promise.resolve();+ });++ expect(container.textContent).toContain("common.draft");+ expect(container.textContent).not.toContain("common.under-review");+ });++ it("does not surface rollout controls for a draft issue with stale rollout data", async () => {+ const page = buildPage();+ page.isCreating = false;+ page.planId = "1";+ page.pageKey = "foo/1";+ page.plan.name = "projects/foo/plans/1";+ page.plan.issue = "projects/foo/issues/1";+ page.issue = {+ name: "projects/foo/issues/1",+ draft: true,+ } as PlanDetailPageState["issue"];+ page.rollout = {+ name: "projects/foo/plans/1/rollout",+ stages: [+ {+ name: "projects/foo/plans/1/rollout/stages/prod",+ tasks: [{ status: 1 }],+ },+ ],+ } as PlanDetailPageState["rollout"];+ mocks.usePlanDetailPage.mockReturnValue(page);++ await act(async () => {+ root.render(+ <ProjectPlanDetailPage planId="1" projectId="foo" specId="spec-1" />+ );+ await Promise.resolve();+ });++ expect(container.textContent).toContain("common.draft");+ expect(container.querySelector("[data-testid='deploy-branch']")).toBeNull();+ expect(+ container.querySelector("[data-testid='deploy-future-control']")+ ).toBeNull();+ expect(container.textContent).not.toContain("common.not-started");+ });++ it("shows an incomplete state for a persisted plan without its Draft Review Issue", async () => {+ const page = buildPage();+ page.isCreating = false;+ page.planId = "1";+ page.plan.name = "projects/foo/plans/1";+ page.plan.issue = "";+ page.issue = undefined;+ mocks.usePlanDetailPage.mockReturnValue(page);++ await act(async () => {+ root.render(+ <ProjectPlanDetailPage planId="1" projectId="foo" specId="spec-1" />+ );+ await Promise.resolve();+ });++ expect(container.textContent).toContain("plan.lifecycle.incomplete");+ });+it("hides the review phase for GitOps plans with release-backed specs", async () => {const page = buildPage();page.plan.specs = [diff --git a/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsxindex 7af0e09822..38e98191ca 100644--- a/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx+++ b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx@@ -99,11 +99,15 @@ function ProjectPlanDetailPageInner({const phaseConfigs = useMemo(() => {const hasIssue = !!page.issue;- const hasRollout = !!page.rollout;+ const isDraftIssue = page.issue?.draft === true;+ const hasSubmittedIssue = hasIssue && !isDraftIssue;+ const effectiveRollout = isDraftIssue ? undefined : page.rollout;+ const hasRollout = !!effectiveRollout;const isIssueClosed =page.issue?.status === IssueStatus.CANCELED ||page.issue?.status === IssueStatus.DONE;- const allTasks = page.rollout?.stages.flatMap((stage) => stage.tasks) ?? [];+ const allTasks =+ effectiveRollout?.stages.flatMap((stage) => stage.tasks) ?? [];const allDone =allTasks.length > 0 &&allTasks.every(@@ -113,7 +117,7 @@ function ProjectPlanDetailPageInner({);let review: PhaseStatus = "future";- if (hasIssue) {+ if (hasSubmittedIssue) {if (page.issue?.status === IssueStatus.CANCELED) {review = "closed";} else {@@ -122,7 +126,7 @@ function ProjectPlanDetailPageInner({}const changesStatus: PhaseStatus =- page.isCreating || (reviewVisible && !hasIssue && !hasRollout)+ page.isCreating || (reviewVisible && !hasSubmittedIssue && !hasRollout)? "active": "completed";const deployStatus: PhaseStatus = hasRollout@@ -133,10 +137,17 @@ function ProjectPlanDetailPageInner({const changesBadge =changesStatus === "active" && !page.isCreating- ? { label: t("common.draft"), variant: "default" as const }+ ? {+ label: page.issue?.draft+ ? t("common.draft")+ : t("plan.lifecycle.incomplete"),+ variant: page.issue?.draft+ ? ("default" as const)+ : ("destructive" as const),+ }: undefined;const rawReviewBadge = getReviewBadge({- hasIssue,+ hasIssue: hasSubmittedIssue,issueStatus: page.issue?.status,hasRollout,approvalStatus: page.issue?.approvalStatus,@@ -148,8 +159,8 @@ function ProjectPlanDetailPageInner({}: undefined;const deployBadge = (() => {- if (deployStatus !== "active" || !page.rollout) return undefined;- const rolloutStatus = getRolloutStatus(page.rollout);+ if (deployStatus !== "active" || !effectiveRollout) return undefined;+ const rolloutStatus = getRolloutStatus(effectiveRollout);if (rolloutStatus === Task_Status.FAILED) {return { label: t("common.failed"), variant: "destructive" as const };}@@ -203,6 +214,10 @@ function ProjectPlanDetailPageInner({};}, [page.isCreating, page.issue, page.rollout, reviewVisible, t]);+ useEffect(() => {+ setSelectedSpecId(specId ?? "");+ }, [page.pageKey]);+// Mirror the URL specId into local state. We deliberately don't include// selectedSpecId in the deps — children (e.g. PlanDetailChangesBranch) may// set selectedSpecId to a draft spec that has no URL yet, and snapping it@@ -301,8 +316,19 @@ function ProjectPlanDetailPageInner({status={phaseConfigs.deploy.status}onSelect={() => page.expandPhase("deploy")}onToggle={() => page.togglePhase("deploy")}- summary={buildDeploySummary(page.rollout, t)}- future={<PlanDetailDeployFuture />}+ summary={buildDeploySummary(+ page.issue?.draft ? undefined : page.rollout,+ t+ )}+ future={+ page.issue?.draft ? (+ <p className="mt-0.5 text-sm text-control-placeholder">+ {t("plan.phase.deploy-description")}+ </p>+ ) : (+ <PlanDetailDeployFuture />+ )+ }><DeployBranch /></PhaseSection>diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsxindex d9f2673207..e7069ce5ec 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx@@ -1,4 +1,4 @@-import type { ReactNode } from "react";+import type { ButtonHTMLAttributes, ReactNode } from "react";import { act, useState } from "react";import { createRoot } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -87,18 +87,8 @@ vi.mock("@/react/components/EnvironmentLabel", () => ({}));vi.mock("@/react/components/ui/button", () => ({- Button: ({- children,- disabled,- onClick,- }: {- children: ReactNode;- disabled?: boolean;- onClick?: () => void;- }) => (- <button disabled={disabled} onClick={onClick}>- {children}- </button>+ Button: ({ children, ...props }: ButtonHTMLAttributes<HTMLButtonElement>) => (+ <button {...props}>{children}</button>),}));@@ -566,6 +556,7 @@ function buildPageState(): PlanDetailPageState {return {activePhases: new Set(["changes"]),bypassLeaveGuardOnce: vi.fn(),+ creationIssueLabels: [],currentUser: {name: "users/[email protected]",} as PlanDetailPageState["currentUser"],@@ -612,6 +603,7 @@ function buildPageState(): PlanDetailPageState {routeName: undefined,routePhase: "changes",selectedTaskName: undefined,+ setCreationIssueLabels: vi.fn(),setEditing: vi.fn(),setIsRunningChecks: vi.fn(),taskRuns: [],@@ -808,12 +800,192 @@ describe("PlanDetailChangesBranch", () => {await flush();expect(container.textContent).toContain("group-a");- renderHarness(1);+ renderHarness(0);await flush();expect(container.textContent).toContain("group-a");});+ it("discards a pending change when navigating to another plan", async () => {+ const page = buildPageState();+ page.isCreating = false;+ page.pageKey = "foo/plan-1";+ page.planId = "plan-1";+ page.plan.name = "projects/foo/plans/plan-1";++ act(() => {+ root.render(+ <PlanDetailProvider value={page}>+ <PlanDetailChangesBranch+ selectedSpecId="spec-1"+ onSelectedSpecIdChange={vi.fn()}+ />+ </PlanDetailProvider>+ );+ });+ await flush();++ await act(async () => {+ (+ [...container.querySelectorAll("button")].find(+ (button) => button.getAttribute("aria-label") === "plan.add-spec"+ ) as HTMLButtonElement+ ).click();+ });+ await flush();+ await act(async () => {+ (+ [...container.querySelectorAll("button")].find((button) =>+ button.textContent?.includes("common.database-group")+ ) as HTMLButtonElement+ ).click();+ });+ await flush();+ await act(async () => {+ (+ [...container.querySelectorAll("tr")].find((row) =>+ row.textContent?.includes("group-a")+ ) as HTMLTableRowElement+ ).click();+ });+ await flush();+ await act(async () => {+ (+ [...container.querySelectorAll("button")].find(+ (button) => button.textContent === "common.confirm"+ ) as HTMLButtonElement+ ).click();+ });+ await flush();++ expect(+ [...container.querySelectorAll("button")].filter((button) =>+ button.textContent?.includes("plan.spec.type.database-change")+ )+ ).toHaveLength(2);+ expect(+ (+ [...container.querySelectorAll("button")].find(+ (button) => button.getAttribute("aria-label") === "plan.add-spec"+ ) as HTMLButtonElement+ ).disabled+ ).toBe(true);++ const nextPage = buildPageState();+ nextPage.isCreating = false;+ nextPage.pageKey = "foo/plan-2";+ nextPage.planId = "plan-2";+ nextPage.plan.name = "projects/foo/plans/plan-2";+ act(() => {+ root.render(+ <PlanDetailProvider value={nextPage}>+ <PlanDetailChangesBranch+ selectedSpecId="spec-1"+ onSelectedSpecIdChange={vi.fn()}+ />+ </PlanDetailProvider>+ );+ });+ await flush();++ expect(+ [...container.querySelectorAll("button")].filter((button) =>+ button.textContent?.includes("plan.spec.type.database-change")+ )+ ).toHaveLength(1);+ expect(+ (+ [...container.querySelectorAll("button")].find(+ (button) => button.getAttribute("aria-label") === "plan.add-spec"+ ) as HTMLButtonElement+ ).disabled+ ).toBe(false);+ expect(container.textContent).toContain("spec-1::0");+ });++ it("clears per-spec editor state when the page identity changes", async () => {+ const sheetName = "projects/foo/sheets/-1";+ mocks.localSheets.set(sheetName, {+ name: sheetName,+ content: new TextEncoder().encode("select 1;"),+ contentSize: 0n,+ });+ mocks.getPlanOptionVisibility.mockReturnValue({+ shouldShow: true,+ showGhost: false,+ showInstanceRole: false,+ showIsolationLevel: false,+ showPreBackup: false,+ showTransactionMode: true,+ });+ const page = buildPageState();+ page.pageKey = "foo/create-1";+ page.plan.specs = [+ {+ id: "spec-1",+ config: {+ case: "changeDatabaseConfig",+ value: { sheet: sheetName, targets: [DB_WIDGETS] },+ },+ },+ ] as unknown as PlanDetailPageState["plan"]["specs"];++ act(() => {+ root.render(+ <PlanDetailProvider value={page}>+ <PlanDetailChangesBranch+ selectedSpecId="spec-1"+ onSelectedSpecIdChange={vi.fn()}+ />+ </PlanDetailProvider>+ );+ });+ await flush();++ await act(async () => {+ (+ [...container.querySelectorAll("button")].find(+ (button) => button.textContent === "run draft checks"+ ) as HTMLButtonElement+ ).click();+ });+ await flush();+ expect(container.textContent).toContain("spec-1:check-run-for-spec-1:0");++ await act(async () => {+ (+ [...container.querySelectorAll("button")].find(+ (button) => button.textContent === "switch-off"+ ) as HTMLButtonElement+ ).click();+ });+ await flush();+ await act(async () => {+ (+ [...container.querySelectorAll("button")].find(+ (button) => button.textContent === "run draft checks"+ ) as HTMLButtonElement+ ).click();+ });+ await flush();+ expect(container.textContent).toContain("spec-1:check-run-for-spec-1:1");++ act(() => {+ root.render(+ <PlanDetailProvider value={{ ...page, pageKey: "foo/create-2" }}>+ <PlanDetailChangesBranch+ selectedSpecId="spec-1"+ onSelectedSpecIdChange={vi.fn()}+ />+ </PlanDetailProvider>+ );+ });+ await flush();++ expect(container.textContent).toContain("spec-1::0");+ expect(container.textContent).not.toContain("check-run-for-spec-1");+ });+it("does not navigate while adding a change to a creating plan", async () => {const onSelectedSpecIdChange = vi.fn();diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsxindex d7695de114..f4c49f9cc7 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx@@ -224,6 +224,18 @@ export function PlanDetailChangesBranch({const [statementVersionBySpecId, setStatementVersionBySpecId] = useState<Record<string, number>>({});+ const pageKeyRef = useRef(page.pageKey);+ pageKeyRef.current = page.pageKey;++ useEffect(() => {+ setShowAddSpecSheet(false);+ setShowTargetSelectorSheet(false);+ setSpecPendingDelete(null);+ setPendingNewSpec(null);+ setIsPendingSelected(false);+ setDraftCheckResultsBySpecId({});+ setStatementVersionBySpecId({});+ }, [page.pageKey]);const specs = page.plan.specs ?? [];// Specs visible in the tab strip — real specs plus any pending draft.const visibleSpecs = useMemo(@@ -244,7 +256,7 @@ export function PlanDetailChangesBranch({if (isReleaseBackedPlan(page.plan.specs)) return false;if (page.isCreating) return true;return (- !page.plan.hasRollout &&+ !(page.plan.hasRollout && !page.issue?.draft) &&(page.plan.creator === currentUser.name ||hasProjectPermissionV2(project, "bb.plans.update")));@@ -253,6 +265,7 @@ export function PlanDetailChangesBranch({page.isCreating,page.plan.creator,page.plan.hasRollout,+ page.issue?.draft,page.plan.specs,page.plan.state,page.readonly,@@ -269,16 +282,18 @@ export function PlanDetailChangesBranch({return planPatch;}+ const actionPageKey = page.pageKey;const response = await planServiceClientConnect.updatePlan(create(UpdatePlanRequestSchema, {plan: planPatch,updateMask: { paths: ["specs"] },}));+ if (pageKeyRef.current !== actionPageKey) return undefined;patchState({ plan: response });return response;},- [page.isCreating, page.plan, patchState]+ [page.isCreating, page.pageKey, page.plan, patchState]);const selectSpec = useCallback(@@ -354,8 +369,10 @@ export function PlanDetailChangesBranch({(spec) => spec.id !== targetSpec.id);const fallbackSpec = nextSpecs[0];+ const actionPageKey = page.pageKey;try {- await commitSpecs(nextSpecs);+ const updated = await commitSpecs(nextSpecs);+ if (!updated || pageKeyRef.current !== actionPageKey) return;if (fallbackSpec) {selectSpec(fallbackSpec.id);}@@ -365,6 +382,7 @@ export function PlanDetailChangesBranch({title: t("common.updated"),});} catch (error) {+ if (pageKeyRef.current !== actionPageKey) return;pushNotification({module: "bytebase",style: "CRITICAL",@@ -372,7 +390,9 @@ export function PlanDetailChangesBranch({description: String(error),});} finally {- setSpecPendingDelete(null);+ if (pageKeyRef.current === actionPageKey) {+ setSpecPendingDelete(null);+ }}};@@ -402,8 +422,10 @@ export function PlanDetailChangesBranch({}return patched;});+ const actionPageKey = page.pageKey;try {- await commitSpecs(nextSpecs);+ const updated = await commitSpecs(nextSpecs);+ if (!updated || pageKeyRef.current !== actionPageKey) return;pushNotification({module: "bytebase",style: "SUCCESS",@@ -411,6 +433,7 @@ export function PlanDetailChangesBranch({});setShowTargetSelectorSheet(false);} catch (error) {+ if (pageKeyRef.current !== actionPageKey) return;pushNotification({module: "bytebase",style: "CRITICAL",@@ -553,18 +576,19 @@ export function PlanDetailChangesBranch({: t("plan.add-spec")}>- <button+ <Buttonaria-label={t("plan.add-spec")}className={cn(ICON_ACTION_CLASS,- "size-7 rounded-md [touch-action:manipulation]"+ "size-7 rounded-md p-0 [touch-action:manipulation]")}disabled={Boolean(pendingNewSpec)}onClick={() => setShowAddSpecSheet(true)}- type="button"+ size="sm"+ appearance="secondary"><Plus aria-hidden="true" className="size-4" />- </button>+ </Button></Tooltip>) : undefined}@@ -639,7 +663,10 @@ export function PlanDetailChangesBranch({spec-detail group when the selected spec changes (resetting eachsection's internal state) without the sections colliding on a sharedkey={selectedSpec.id}, which logged a duplicate-key warning. */}- <div key={selectedSpec.id} className="flex flex-col gap-y-4">+ <div+ key={`${page.pageKey}:${selectedSpec.id}`}+ className="flex flex-col gap-y-4"+ ><TargetsSectionallowEdit={canModifySpecs}onEdit={() => setShowTargetSelectorSheet(true)}@@ -736,6 +763,8 @@ function OptionsSection({const { t } = useTranslation();const page = usePlanDetailContext();const { patchState, refreshState } = page;+ const pageKeyRef = useRef(page.pageKey);+ pageKeyRef.current = page.pageKey;const currentUser = useCurrentUser();// subscribe to re-render on project cache changeconst projectsByName = useAppStore((s) => s.projectsByName);@@ -836,7 +865,7 @@ function OptionsSection({);const allowChange = useMemo(() => {if (page.readonly) return false;- if (page.plan.hasRollout) return false;+ if (page.plan.hasRollout && !page.issue?.draft) return false;if (page.isCreating) return true;return (page.plan.creator === currentUser.name ||@@ -846,6 +875,7 @@ function OptionsSection({currentUser.name,page.isCreating,page.plan.creator,+ page.issue?.draft,page.plan.hasRollout,page.readonly,project,@@ -938,11 +968,13 @@ function OptionsSection({return;}+ const actionPageKey = page.pageKey;const updatedPlan = await updateSpecSheetWithStatement(page.plan,selectedSpec,nextStatement);+ if (pageKeyRef.current !== actionPageKey) return;if (updatedPlan) {patchState({ plan: updatedPlan });}@@ -953,6 +985,7 @@ function OptionsSection({[onStatementPersisted,page.isCreating,+ page.pageKey,page.plan,patchState,refreshState,@@ -977,12 +1010,14 @@ function OptionsSection({return;}+ const actionPageKey = page.pageKey;const response = await planServiceClientConnect.updatePlan(create(UpdatePlanRequestSchema, {plan: planPatch,updateMask: { paths: ["specs"] },}));+ if (pageKeyRef.current !== actionPageKey) return;patchState({ plan: response });};diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.test.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.test.tsxnew file mode 100644index 0000000000..987f98e4b6--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.test.tsx@@ -0,0 +1,793 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import {+ type ButtonHTMLAttributes,+ cloneElement,+ isValidElement,+ type ReactElement,+ type ReactNode,+ type TextareaHTMLAttributes,+} from "react";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { State } from "@/types/proto-es/v1/common_pb";+import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";+import type { PlanDetailPageState } from "../shell/hooks/types";+import { PlanDetailHeader } from "./PlanDetailHeader";+import { PlanDetailHeaderDetails } from "./PlanDetailHeaderDetails";++const mocks = vi.hoisted(() => ({+ batchUpdateIssuesStatus: vi.fn(),+ creationIssueLabels: [] as string[],+ createIssue: vi.fn(),+ createPlan: vi.fn(),+ lifecycle: { kind: "none" } as { kind: string },+ page: undefined as unknown as PlanDetailPageState,+ patchState: vi.fn(),+ permissions: new Set<string>(),+ pushNotification: vi.fn(),+ replaceRoute: vi.fn(),+ setCreationIssueLabels: vi.fn(),+ updateIssue: vi.fn(),+ updatePlan: vi.fn(),+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ }),+}));++vi.mock("@bufbuild/protobuf", () => ({+ clone: (_schema: unknown, message: Record<string, unknown>) => ({+ ...message,+ }),+ create: (_schema: unknown, init?: Record<string, unknown>) => ({ ...init }),+}));++vi.mock("@/connect", () => ({+ issueServiceClientConnect: {+ batchUpdateIssuesStatus: mocks.batchUpdateIssuesStatus,+ createIssue: mocks.createIssue,+ updateIssue: mocks.updateIssue,+ },+ planServiceClientConnect: {+ createPlan: mocks.createPlan,+ updatePlan: mocks.updatePlan,+ },+}));++vi.mock("@/react/components/IssueLabelSelect", () => ({+ IssueLabelSelect: ({+ onChange,+ selected,+ }: {+ onChange: (labels: string[]) => void;+ selected: string[];+ }) => (+ <div>+ <output data-testid="selected-labels">{selected.join(",")}</output>+ <button onClick={() => onChange(["replacement"])} type="button">+ select replacement label+ </button>+ </div>+ ),+}));++vi.mock("@/react/components/MarkdownEditor", () => ({+ MarkdownEditor: ({ content }: { content: string }) => <span>{content}</span>,+}));++vi.mock("@/react/components/ui/button", () => ({+ Button: ({+ appearance: _appearance,+ children,+ size: _size,+ variant: _variant,+ ...props+ }: ButtonHTMLAttributes<HTMLButtonElement> & {+ appearance?: string;+ size?: string;+ variant?: string;+ }) => <button {...props}>{children}</button>,+}));++vi.mock("@/react/components/ui/checkbox", () => ({+ Checkbox: ({+ checked,+ onCheckedChange,+ }: {+ checked: boolean;+ onCheckedChange?: (checked: boolean) => void;+ }) => (+ <input+ checked={checked}+ onChange={(event) => onCheckedChange?.(event.target.checked)}+ type="checkbox"+ />+ ),+}));++vi.mock("@/react/components/ui/textarea", () => ({+ Textarea: (props: TextareaHTMLAttributes<HTMLTextAreaElement>) => (+ <textarea {...props} />+ ),+}));++vi.mock("@/react/components/ui/popover", async () => {+ const React = await vi.importActual<typeof import("react")>("react");+ const PopoverContext = React.createContext<{+ onOpenChange?: (open: boolean) => void;+ open: boolean;+ }>({ open: false });++ return {+ Popover: ({+ children,+ onOpenChange,+ open = false,+ }: {+ children: ReactNode;+ onOpenChange?: (open: boolean) => void;+ open?: boolean;+ }) => (+ <PopoverContext.Provider value={{ onOpenChange, open }}>+ <div>{children}</div>+ </PopoverContext.Provider>+ ),+ PopoverContent: ({ children }: { children: ReactNode }) => {+ const { open } = React.useContext(PopoverContext);+ return open ? <div>{children}</div> : null;+ },+ PopoverTrigger: ({+ children,+ render,+ }: {+ children: ReactNode;+ render?: ReactElement<ButtonHTMLAttributes<HTMLButtonElement>>;+ }) => {+ const { onOpenChange, open } = React.useContext(PopoverContext);+ if (!isValidElement(render)) return <>{children}</>;+ const originalOnClick = render.props.onClick;+ return cloneElement(+ render,+ {+ onClick: (event) => {+ originalOnClick?.(event);+ onOpenChange?.(!open);+ },+ },+ children+ );+ },+ };+});++vi.mock("@/react/components/ui/dropdown-menu", () => ({+ DropdownMenu: ({ children }: { children: ReactNode }) => (+ <div>{children}</div>+ ),+ DropdownMenuContent: ({ children }: { children: ReactNode }) => (+ <div>{children}</div>+ ),+ DropdownMenuItem: ({+ children,+ onClick,+ }: {+ children: ReactNode;+ onClick?: () => void;+ }) => <button onClick={onClick}>{children}</button>,+ DropdownMenuTrigger: ({+ children,+ render,+ }: {+ children: ReactNode;+ render?: ReactElement;+ }) =>+ isValidElement(render) ? (+ cloneElement(render, {}, children)+ ) : (+ <>{children}</>+ ),+}));++vi.mock("@/react/lib/utils", () => ({+ cn: (...classes: Array<string | false | null | undefined>) =>+ classes.filter(Boolean).join(" "),+}));++vi.mock("@/react/router", () => ({+ router: { replace: mocks.replaceRoute },+}));++vi.mock("@/react/stores/app", () => {+ const getState = () => ({+ createSheet: vi.fn(),+ listIssueComments: vi.fn(),+ });+ return { useAppStore: { getState } };+});++vi.mock("@/store", () => ({ pushNotification: mocks.pushNotification }));++vi.mock("@/utils", () => ({+ extractPlanUID: (name: string) => name.split("/").at(-1) ?? "",+ extractProjectResourceName: () => "p1",+ extractSheetUID: (name: string) => name,+ hasProjectPermissionV2: (_project: unknown, permission: string) =>+ mocks.permissions.has(permission),+}));++vi.mock("../hooks/usePlanDetailSpecValidation", () => ({+ usePlanDetailSpecValidation: () => ({ emptySpecIdSet: new Set<string>() }),+}));++vi.mock("../shell/focusPhase", () => ({ focusPlanPhase: vi.fn() }));+vi.mock("../shell/PlanDetailContext", () => ({+ usePlanDetailContext: () => mocks.page,+}));+vi.mock("../utils/localSheet", () => ({+ getLocalSheetByName: vi.fn(),+ removeLocalSheet: vi.fn(),+}));+vi.mock("./PlanDetailMeta", () => ({ PlanDetailMeta: () => null }));+vi.mock("./lifecycle/PlanLifecycleSlot", () => ({+ PlanLifecycleSlot: () => null,+}));+vi.mock("./lifecycle/PlanLifecycleStamp", () => ({+ PlanLifecycleStamp: () => null,+}));+vi.mock("./lifecycle/planLifecycleHeaderState", () => ({+ slotHasPrimaryControl: () => false,+}));+vi.mock("./lifecycle/usePlanLifecycleHeader", () => ({+ usePlanLifecycleHeader: () => mocks.lifecycle,+}));++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((next) => {+ resolve = next;+ });+ return { promise, resolve };+}++const makePage = ({+ draft = true,+ issueStatus = IssueStatus.OPEN,+ planState = State.ACTIVE,+ creating = false,+}: {+ draft?: boolean;+ issueStatus?: IssueStatus;+ planState?: State;+ creating?: boolean;+} = {}): PlanDetailPageState =>+ ({+ activePhases: new Set(),+ bypassLeaveGuardOnce: vi.fn(),+ creationIssueLabels: mocks.creationIssueLabels,+ currentUser: { email: "[email protected]", name: "users/reviewer" },+ expandPhase: vi.fn(),+ isCreating: creating,+ isEditing: false,+ isInitializing: false,+ isRunningChecks: false,+ issue: creating+ ? undefined+ : {+ description: "Stale issue description",+ draft,+ labels: [],+ name: "projects/p1/issues/456",+ plan: "projects/p1/plans/123",+ status: issueStatus,+ title: "Stale issue title",+ },+ pageKey: "plan-123",+ patchState: mocks.patchState,+ pendingLeaveConfirm: false,+ plan: {+ creator: "users/owner",+ description: "Plan description",+ hasRollout: false,+ issue: creating ? "" : "projects/p1/issues/456",+ name: creating ? "" : "projects/p1/plans/123",+ specs: [],+ state: planState,+ title: "Plan title",+ },+ planCheckRuns: [],+ planId: creating ? "create" : "123",+ project: {+ enforceSqlReview: false,+ forceIssueLabels: false,+ issueLabels: [],+ name: "projects/p1",+ },+ projectCanCreateRollout: false,+ projectId: "p1",+ projectRequireIssueApproval: false,+ projectRequirePlanCheckNoError: false,+ projectTitle: "Project One",+ readonly: false,+ ready: true,+ refreshState: vi.fn(async () => undefined),+ resolveLeaveConfirm: vi.fn(),+ rollout: undefined,+ setCreationIssueLabels: mocks.setCreationIssueLabels,+ setEditing: vi.fn(),+ setIsRunningChecks: vi.fn(),+ taskRuns: [],+ taskRunsByTaskName: new Map(),+ togglePhase: vi.fn(),+ }) as unknown as PlanDetailPageState;++beforeEach(() => {+ vi.clearAllMocks();+ mocks.creationIssueLabels = [];+ mocks.permissions = new Set(["bb.plans.update"]);+ mocks.lifecycle = { kind: "none" };+ mocks.page = makePage();+ mocks.updatePlan.mockImplementation(async (request) => request.plan);+ mocks.updateIssue.mockImplementation(async (request) => request.issue);+ mocks.batchUpdateIssuesStatus.mockResolvedValue({});+ vi.spyOn(window, "confirm").mockReturnValue(true);+});++describe("PlanDetailHeader draft ownership", () => {+ test("edits draft title and description through UpdatePlan with plan permission only", async () => {+ render(+ <>+ <PlanDetailHeader />+ <PlanDetailHeaderDetails />+ </>+ );++ const title = screen.getByDisplayValue("Plan title");+ expect(title).toBeEnabled();+ fireEvent.focus(title);+ fireEvent.change(title, { target: { value: "Updated plan title" } });+ fireEvent.blur(title);++ fireEvent.click(screen.getByText("Plan description"));+ const description = screen.getByDisplayValue("Plan description");+ fireEvent.change(description, {+ target: { value: "Updated plan description" },+ });+ fireEvent.click(screen.getByRole("button", { name: "common.save" }));++ await waitFor(() => expect(mocks.updatePlan).toHaveBeenCalledTimes(2));+ expect(mocks.updatePlan.mock.calls.map(([request]) => request)).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ plan: expect.objectContaining({ title: "Updated plan title" }),+ updateMask: { paths: ["title"] },+ }),+ expect.objectContaining({+ plan: expect.objectContaining({+ description: "Updated plan description",+ }),+ updateMask: { paths: ["description"] },+ }),+ ])+ );+ expect(mocks.updateIssue).not.toHaveBeenCalled();+ expect(mocks.patchState).toHaveBeenCalledWith({+ plan: expect.objectContaining({ title: "Updated plan title" }),+ });+ expect(mocks.patchState).toHaveBeenCalledWith({+ plan: expect.objectContaining({+ description: "Updated plan description",+ }),+ });+ });++ test("preserves dirty title and description edits across polling updates", () => {+ const { rerender } = render(+ <>+ <PlanDetailHeader />+ <PlanDetailHeaderDetails />+ </>+ );+ const title = screen.getByDisplayValue("Plan title");+ fireEvent.focus(title);+ fireEvent.change(title, { target: { value: "Local draft title" } });+ fireEvent.click(screen.getByText("Plan description"));+ fireEvent.change(screen.getByDisplayValue("Plan description"), {+ target: { value: "Local draft description" },+ });++ mocks.page = {+ ...mocks.page,+ plan: {+ ...mocks.page.plan,+ description: "Polled plan description",+ title: "Polled plan title",+ },+ };+ rerender(+ <>+ <PlanDetailHeader />+ <PlanDetailHeaderDetails />+ </>+ );++ expect(screen.getByDisplayValue("Local draft title")).toBe(title);+ expect(screen.getByDisplayValue("Local draft description")).toBeVisible();+ });++ test("resets dirty metadata when navigating to another plan", () => {+ const { rerender } = render(+ <>+ <PlanDetailHeader />+ <PlanDetailHeaderDetails />+ </>+ );+ const title = screen.getByDisplayValue("Plan title");+ fireEvent.focus(title);+ fireEvent.change(title, { target: { value: "Old local title" } });+ fireEvent.click(screen.getByText("Plan description"));+ fireEvent.change(screen.getByDisplayValue("Plan description"), {+ target: { value: "Old local description" },+ });++ mocks.page = {+ ...makePage(),+ pageKey: "plan-456",+ plan: {+ ...makePage().plan,+ description: "New plan description",+ name: "projects/p1/plans/456",+ title: "New plan title",+ },+ };+ rerender(+ <>+ <PlanDetailHeader />+ <PlanDetailHeaderDetails />+ </>+ );++ expect(screen.getByDisplayValue("New plan title")).toBeVisible();+ expect(screen.queryByDisplayValue("Old local title")).toBeNull();+ expect(screen.getByText("New plan description")).toBeVisible();+ expect(screen.queryByDisplayValue("Old local description")).toBeNull();+ });++ test("collapses an expanded description after navigation", () => {+ const longDescription = "A".repeat(180);+ mocks.page = {+ ...makePage(),+ plan: { ...makePage().plan, description: longDescription },+ };+ const { rerender } = render(<PlanDetailHeaderDetails />);++ fireEvent.click(screen.getByRole("button", { name: "common.show-more" }));+ expect(+ screen.getByRole("button", { name: "common.show-less" })+ ).toBeVisible();++ mocks.page = {+ ...makePage(),+ pageKey: "plan-456",+ plan: {+ ...makePage().plan,+ description: "B".repeat(180),+ name: "projects/p1/plans/456",+ },+ };+ rerender(<PlanDetailHeaderDetails />);++ expect(+ screen.getByRole("button", { name: "common.show-more" })+ ).toBeVisible();+ });++ test("resets review labels and warning acknowledgment after navigation", () => {+ mocks.permissions = new Set(["bb.plans.update", "bb.issues.update"]);+ mocks.lifecycle = { kind: "ready-for-review" };+ mocks.page = {+ ...makePage(),+ issue: { ...makePage().issue!, labels: ["old"] },+ plan: {+ ...makePage().plan,+ planCheckRunStatusCount: { ERROR: 1 },+ specs: [{ config: { case: "changeDatabaseConfig", value: {} } }],+ },+ } as unknown as PlanDetailPageState;+ const { rerender } = render(<PlanDetailHeader />);++ fireEvent.click(+ screen.getByRole("button", { name: "plan.ready-for-review" })+ );+ fireEvent.click(+ screen.getByRole("button", { name: "select replacement label" })+ );+ fireEvent.click(screen.getByRole("checkbox"));+ expect(screen.getByTestId("selected-labels")).toHaveTextContent(+ "replacement"+ );+ expect(screen.getByRole("checkbox")).toBeChecked();++ mocks.page = {+ ...mocks.page,+ pageKey: "plan-456",+ issue: { ...mocks.page.issue!, labels: ["new"] },+ plan: {+ ...mocks.page.plan,+ name: "projects/p1/plans/456",+ },+ };+ rerender(<PlanDetailHeader />);++ fireEvent.click(+ screen.getByRole("button", { name: "plan.ready-for-review" })+ );+ expect(screen.getByTestId("selected-labels")).toHaveTextContent("new");+ expect(screen.getByRole("checkbox")).not.toBeChecked();+ });++ test("submits labels from the Ready for Review popover and surfaces a single failure", async () => {+ const failure = new Error("approval setup failed");+ mocks.permissions = new Set(["bb.plans.update", "bb.issues.update"]);+ mocks.lifecycle = { kind: "ready-for-review" };+ mocks.page = {+ ...makePage(),+ issue: { ...makePage().issue!, labels: ["old"] },+ };+ mocks.updateIssue.mockRejectedValueOnce(failure);+ render(<PlanDetailHeader />);++ fireEvent.click(+ screen.getByRole("button", { name: "plan.ready-for-review" })+ );+ expect(screen.getByTestId("selected-labels")).toHaveTextContent("old");+ fireEvent.click(+ screen.getByRole("button", { name: "select replacement label" })+ );+ fireEvent.click(screen.getByRole("button", { name: "common.confirm" }));++ await waitFor(() => expect(mocks.updateIssue).toHaveBeenCalledOnce());+ expect(mocks.updateIssue).toHaveBeenCalledWith(+ expect.objectContaining({+ issue: expect.objectContaining({+ draft: false,+ labels: ["replacement"],+ }),+ updateMask: { paths: ["draft", "labels"] },+ })+ );+ await waitFor(() =>+ expect(mocks.pushNotification).toHaveBeenCalledWith({+ module: "bytebase",+ style: "CRITICAL",+ title: "common.failed",+ description: String(failure),+ })+ );+ expect(mocks.updateIssue).toHaveBeenCalledOnce();+ expect(mocks.patchState).not.toHaveBeenCalled();+ });++ test("ignores a title update response from the previous plan", async () => {+ const pending = deferred<Record<string, unknown>>();+ mocks.updatePlan.mockReturnValueOnce(pending.promise);+ const { rerender } = render(<PlanDetailHeader />);+ const title = screen.getByDisplayValue("Plan title");+ fireEvent.focus(title);+ fireEvent.change(title, { target: { value: "Old saved title" } });+ fireEvent.blur(title);++ mocks.page = {+ ...makePage(),+ pageKey: "plan-456",+ plan: {+ ...makePage().plan,+ name: "projects/p1/plans/456",+ title: "New plan title",+ },+ };+ rerender(<PlanDetailHeader />);+ pending.resolve({+ name: "projects/p1/plans/123",+ title: "Old saved title",+ });++ await waitFor(() =>+ expect(screen.getByDisplayValue("New plan title")).toBeVisible()+ );+ expect(mocks.patchState).not.toHaveBeenCalled();+ });++ test("ignores a description update response from the previous plan", async () => {+ const pending = deferred<Record<string, unknown>>();+ mocks.updatePlan.mockReturnValueOnce(pending.promise);+ const { rerender } = render(<PlanDetailHeaderDetails />);+ fireEvent.click(screen.getByText("Plan description"));+ fireEvent.change(screen.getByDisplayValue("Plan description"), {+ target: { value: "Old saved description" },+ });+ fireEvent.click(screen.getByRole("button", { name: "common.save" }));++ mocks.page = {+ ...makePage(),+ pageKey: "plan-456",+ plan: {+ ...makePage().plan,+ description: "New plan description",+ name: "projects/p1/plans/456",+ },+ };+ rerender(<PlanDetailHeaderDetails />);+ pending.resolve({+ description: "Old saved description",+ name: "projects/p1/plans/123",+ });++ await waitFor(() =>+ expect(screen.getByText("New plan description")).toBeVisible()+ );+ expect(mocks.patchState).not.toHaveBeenCalled();+ });++ test.each([+ ["common.close", State.ACTIVE, State.DELETED],+ ["common.reopen", State.DELETED, State.ACTIVE],+ ])("uses UpdatePlan for draft %s", async (label, initialState, nextState) => {+ mocks.page = makePage({ planState: initialState });+ render(<PlanDetailHeader />);++ fireEvent.click(screen.getByRole("button", { name: label }));++ await waitFor(() => expect(mocks.updatePlan).toHaveBeenCalledOnce());+ expect(mocks.updatePlan).toHaveBeenCalledWith(+ expect.objectContaining({+ plan: expect.objectContaining({ state: nextState }),+ updateMask: { paths: ["state"] },+ })+ );+ expect(mocks.batchUpdateIssuesStatus).not.toHaveBeenCalled();+ await waitFor(() =>+ expect(mocks.patchState).toHaveBeenCalledWith({+ plan: expect.objectContaining({ state: nextState }),+ issue: expect.objectContaining({+ status:+ nextState === State.DELETED+ ? IssueStatus.CANCELED+ : IssueStatus.OPEN,+ }),+ })+ );+ });++ test("creates directly without a confirmation panel", async () => {+ mocks.permissions = new Set(["bb.plans.create", "bb.issues.create"]);+ mocks.lifecycle = { kind: "create" };+ mocks.page = makePage({ creating: true });+ mocks.createPlan.mockResolvedValue({+ ...mocks.page.plan,+ name: "projects/p1/plans/123",+ });+ mocks.createIssue.mockResolvedValue({+ draft: true,+ labels: [],+ name: "projects/p1/issues/456",+ plan: "projects/p1/plans/123",+ });++ render(<PlanDetailHeader />);++ expect(screen.getByRole("button", { name: "common.create" })).toBeEnabled();+ fireEvent.click(screen.getByRole("button", { name: "common.create" }));++ expect(+ screen.queryByRole("button", { name: "common.confirm" })+ ).not.toBeInTheDocument();+ await waitFor(() => expect(mocks.createPlan).toHaveBeenCalledOnce());+ });++ test("allows draft creation when review labels are still missing", () => {+ mocks.permissions = new Set(["bb.plans.create", "bb.issues.create"]);+ mocks.lifecycle = { kind: "create" };+ const page = makePage({ creating: true });+ mocks.page = {+ ...page,+ project: {+ ...page.project,+ forceIssueLabels: true,+ },+ };++ render(<PlanDetailHeader />);++ expect(screen.getByRole("button", { name: "common.create" })).toBeEnabled();+ });++ test("keeps invalid draft creation blocked without a confirmation panel", () => {+ mocks.permissions = new Set(["bb.plans.create", "bb.issues.create"]);+ mocks.lifecycle = { kind: "create" };+ const page = makePage({ creating: true });+ mocks.page = {+ ...page,+ plan: { ...page.plan, title: "" },+ };++ render(<PlanDetailHeader />);++ expect(screen.getByRole("button", { name: "common.create" })).toBeDisabled();+ expect(screen.getByRole("button", { name: "common.create" })).toHaveAttribute(+ "title",+ "plan.title-required"+ );+ });++ test("creates the draft Issue with labels selected on the preview page", async () => {+ mocks.creationIssueLabels = ["preview-label"];+ mocks.permissions = new Set([+ "bb.plans.create",+ "bb.issues.create",+ "bb.issues.update",+ ]);+ mocks.lifecycle = { kind: "create" };+ mocks.page = makePage({ creating: true });+ mocks.createPlan.mockResolvedValue({+ ...mocks.page.plan,+ name: "projects/p1/plans/123",+ });+ mocks.createIssue.mockResolvedValue({+ draft: true,+ labels: ["preview-label"],+ name: "projects/p1/issues/456",+ plan: "projects/p1/plans/123",+ });++ render(<PlanDetailHeader />);++ fireEvent.click(screen.getByRole("button", { name: "common.create" }));++ await waitFor(() => expect(mocks.createIssue).toHaveBeenCalledOnce());+ expect(mocks.createIssue).toHaveBeenCalledWith(+ expect.objectContaining({+ issue: expect.objectContaining({ labels: ["preview-label"] }),+ })+ );+ });+});++describe("PlanDetailHeader submitted issue behavior", () => {+ test("keeps submitted metadata and close mutations on the Issue service", async () => {+ mocks.permissions = new Set(["bb.issues.update"]);+ mocks.page = makePage({ draft: false });+ render(+ <>+ <PlanDetailHeader />+ <PlanDetailHeaderDetails />+ </>+ );++ const title = screen.getByDisplayValue("Stale issue title");+ fireEvent.focus(title);+ fireEvent.change(title, { target: { value: "Submitted issue title" } });+ fireEvent.blur(title);++ fireEvent.click(screen.getByText("Stale issue description"));+ fireEvent.change(screen.getByDisplayValue("Stale issue description"), {+ target: { value: "Submitted issue description" },+ });+ fireEvent.click(screen.getByRole("button", { name: "common.save" }));++ fireEvent.click(+ screen.getByRole("button", { name: "issue.batch-transition.close" })+ );++ await waitFor(() => expect(mocks.updateIssue).toHaveBeenCalledTimes(2));+ await waitFor(() =>+ expect(mocks.batchUpdateIssuesStatus).toHaveBeenCalledOnce()+ );+ expect(+ mocks.updateIssue.mock.calls.map(([request]) => request.updateMask)+ ).toEqual(+ expect.arrayContaining([{ paths: ["title"] }, { paths: ["description"] }])+ );+ expect(mocks.updatePlan).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsxindex 1441daf14c..c1417ce781 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx@@ -23,29 +23,22 @@ import {} from "@/react/components/ui/popover";import { cn } from "@/react/lib/utils";import { router } from "@/react/router";-import {- PROJECT_V1_ROUTE_ISSUE_DETAIL,- PROJECT_V1_ROUTE_PLAN_DETAIL,-} from "@/react/router/handles";+import { PROJECT_V1_ROUTE_PLAN_DETAIL } from "@/react/router/handles";import { useAppStore } from "@/react/stores/app";import { pushNotification } from "@/store";import { State } from "@/types/proto-es/v1/common_pb";import {BatchUpdateIssuesStatusRequestSchema,- CreateIssueRequestSchema,- Issue_Type,IssueSchema,IssueStatus,ListIssueCommentsRequestSchema,UpdateIssueRequestSchema,} from "@/types/proto-es/v1/issue_service_pb";import {- CreatePlanRequestSchema,PlanSchema,UpdatePlanRequestSchema,} from "@/types/proto-es/v1/plan_service_pb";import {- extractIssueUID,extractPlanUID,extractProjectResourceName,extractSheetUID,@@ -55,11 +48,13 @@ import { usePlanDetailSpecValidation } from "../hooks/usePlanDetailSpecValidatioimport { focusPlanPhase } from "../shell/focusPhase";import { usePlanDetailContext } from "../shell/PlanDetailContext";import {+ createPlanWithDraftReview,+ DraftReviewIssueCreationError,getCreateIssueBlockingErrors,getCreateIssueConfirmErrors,getCreatePlanBlockingReasons,hasChecksWarning,- shouldStayOnPlanDetailPage,+ submitDraftReview,} from "../utils/header";import { getLocalSheetByName, removeLocalSheet } from "../utils/localSheet";import { PlanLifecycleSlot } from "./lifecycle/PlanLifecycleSlot";@@ -75,7 +70,10 @@ export function PlanDetailHeader() {const { patchState, setEditing } = page;const currentUser = page.currentUser;const project = page.project;- const [title, setTitle] = useState(page.plan.title);+ const draftIssue = page.issue?.draft === true;+ const persistedTitle =+ page.issue && !draftIssue ? page.issue.title : page.plan.title;+ const [title, setTitle] = useState(persistedTitle);const [editingTitle, setEditingTitle] = useState(false);const [updating, setUpdating] = useState(false);const [showReviewPopover, setShowReviewPopover] = useState(false);@@ -86,8 +84,8 @@ export function PlanDetailHeader() {const { emptySpecIdSet } = usePlanDetailSpecValidation(page.plan.specs ?? []);const titleInputRef = useRef<HTMLInputElement>(null);const titleAutoFocusedRef = useRef(false);- const createButtonRef = useRef<HTMLButtonElement>(null);- const [showCreateErrors, setShowCreateErrors] = useState(false);+ const pageKeyRef = useRef(page.pageKey);+ pageKeyRef.current = page.pageKey;const createPlanBlockingReasons = useMemo(() =>getCreatePlanBlockingReasons({@@ -97,29 +95,65 @@ export function PlanDetailHeader() {}),[emptySpecIdSet.size, page.plan.title, t]);- const titleMissing = page.plan.title.trim() === "";+ const canCreatePlan = hasProjectPermissionV2(project, "bb.plans.create");+ const canCreateIssue = hasProjectPermissionV2(project, "bb.issues.create");+ const canCreateDraftReview = canCreatePlan && canCreateIssue;+ const createPermissionReason = canCreateDraftReview+ ? undefined+ : t("common.missing-required-permission", {+ permissions: ["bb.plans.create", "bb.issues.create"]+ .filter(+ (permission) =>+ !hasProjectPermissionV2(+ project,+ permission as "bb.plans.create" | "bb.issues.create"+ )+ )+ .join(", "),+ });++ const canUpdatePlan =+ page.plan.creator === currentUser.name ||+ hasProjectPermissionV2(project, "bb.plans.update");++ useEffect(() => {+ setTitle(persistedTitle);+ setEditingTitle(false);+ setUpdating(false);+ setShowReviewPopover(false);+ setSelectedLabels(draftIssue ? (page.issue?.labels ?? []) : []);+ setChecksWarningAcknowledged(false);+ setSubmittingReview(false);+ titleAutoFocusedRef.current = false;+ setEditing("title", false);+ }, [page.pageKey]);useEffect(() => {- const nextTitle = page.issue?.title ?? page.plan.title;- setTitle((prev) => (prev === nextTitle ? prev : nextTitle));- }, [page.issue?.title, page.plan.title]);+ if (!editingTitle) {+ setTitle((prev) => (prev === persistedTitle ? prev : persistedTitle));+ }+ }, [editingTitle, persistedTitle]);++ useEffect(() => {+ if (draftIssue && !showReviewPopover) {+ setSelectedLabels(page.issue?.labels ?? []);+ }+ }, [draftIssue, page.issue?.labels, showReviewPopover]);const allowTitleEdit = useMemo(() => {if (page.readonly) return false;if (page.isCreating) return true;if (!page.issue && page.plan.hasRollout) return false;+ if (draftIssue) return canUpdatePlan;if (page.issue) {return hasProjectPermissionV2(project, "bb.issues.update");}- return (- page.plan.creator === currentUser.name ||- hasProjectPermissionV2(project, "bb.plans.update")- );+ return canUpdatePlan;}, [- currentUser.name,+ canUpdatePlan,+ draftIssue,page.isCreating,page.issue,- page.plan.creator,page.plan.hasRollout,page.readonly,project,@@ -143,33 +177,38 @@ export function PlanDetailHeader() {const lifecycle = usePlanLifecycleHeader(page);const showClosePlan =!page.isCreating &&- !page.plan.issue &&!page.plan.hasRollout &&- page.plan.state === State.ACTIVE;+ page.plan.state === State.ACTIVE &&+ (!page.issue || draftIssue) &&+ canUpdatePlan;const showReopenPlan =!page.isCreating &&- !page.plan.issue &&!page.plan.hasRollout &&- page.plan.state === State.DELETED;+ page.plan.state === State.DELETED &&+ (!page.issue || draftIssue) &&+ canUpdatePlan;- // Close (cancel) / reopen the review issue from the header, mirroring the issue- // detail page. Close is offered during the review phase (open issue, no rollout- // yet); reopen once the review was canceled.+ // Submitted issues retain issue-status actions. Draft lifecycle changes flow+ // through the Plan service, which synchronizes the linked draft Issue.const canUpdateIssue = hasProjectPermissionV2(project, "bb.issues.update");const showCloseIssue =!!page.issue &&+ !draftIssue &&page.issue.status === IssueStatus.OPEN &&!page.plan.hasRollout &&canUpdateIssue;const showReopenIssue =!!page.issue &&+ !draftIssue &&page.issue.status === IssueStatus.CANCELED &&canUpdateIssue;- const submitDisabled = page.isEditing;- const submitDisabledReason = submitDisabled+ const submitDisabled = page.isEditing || !canUpdateIssue;+ const submitDisabledReason = page.isEditing? t("plan.editor.save-changes-before-continuing")- : undefined;+ : !canUpdateIssue+ ? t("plan.draft-update-permission-required")+ : undefined;const saveTitle = async () => {if (page.isCreating) {@@ -187,7 +226,8 @@ export function PlanDetailHeader() {// Skip the API round-trip when nothing changed so we don't pollute the// issue timeline with "changed name from X to X".const trimmed = title.trim();- const currentTitle = page.issue?.title ?? page.plan.title;+ const currentTitle =+ page.issue && !draftIssue ? page.issue.title : page.plan.title;if (trimmed === currentTitle) {setTitle(currentTitle);setEditingTitle(false);@@ -195,9 +235,10 @@ export function PlanDetailHeader() {return;}+ const actionPageKey = page.pageKey;try {setUpdating(true);- if (page.issue) {+ if (page.issue && !draftIssue) {const issuePatch = create(IssueSchema, {...page.issue,title,@@ -208,6 +249,7 @@ export function PlanDetailHeader() {updateMask: { paths: ["title"] },}));+ if (pageKeyRef.current !== actionPageKey) return;patchState({ issue: response });} else {const planPatch = create(PlanSchema, {@@ -220,10 +262,12 @@ export function PlanDetailHeader() {updateMask: { paths: ["title"] },}));+ if (pageKeyRef.current !== actionPageKey) return;patchState({ plan: response });}} catch (error) {- setTitle(page.issue?.title ?? page.plan.title);+ if (pageKeyRef.current !== actionPageKey) return;+ setTitle(currentTitle);pushNotification({module: "bytebase",style: "CRITICAL",@@ -231,13 +275,16 @@ export function PlanDetailHeader() {description: String(error),});} finally {- setUpdating(false);- setEditingTitle(false);- setEditing("title", false);+ if (pageKeyRef.current === actionPageKey) {+ setUpdating(false);+ setEditingTitle(false);+ setEditing("title", false);+ }}};const updatePlanState = async (state: State) => {+ const actionPageKey = page.pageKey;try {const planPatch = clone(PlanSchema, page.plan);planPatch.state = state;@@ -247,13 +294,22 @@ export function PlanDetailHeader() {updateMask: { paths: ["state"] },}));- patchState({ plan: updated });+ if (pageKeyRef.current !== actionPageKey) return;+ if (draftIssue && page.issue) {+ const issue = clone(IssueSchema, page.issue);+ issue.status =+ state === State.DELETED ? IssueStatus.CANCELED : IssueStatus.OPEN;+ patchState({ plan: updated, issue });+ } else {+ patchState({ plan: updated });+ }pushNotification({module: "bytebase",style: "SUCCESS",title: t("common.updated"),});} catch (error) {+ if (pageKeyRef.current !== actionPageKey) return;pushNotification({module: "bytebase",style: "CRITICAL",@@ -266,6 +322,7 @@ export function PlanDetailHeader() {const updateIssueStatus = async (status: IssueStatus) => {const issue = page.issue;if (!issue) return;+ const actionPageKey = page.pageKey;try {await issueServiceClientConnect.batchUpdateIssuesStatus(create(BatchUpdateIssuesStatusRequestSchema, {@@ -274,6 +331,7 @@ export function PlanDetailHeader() {status,}));+ if (pageKeyRef.current !== actionPageKey) return;// Closing / reopening records a system comment — refresh page state and the// issue comments so the review timeline reflects it (like issue detail).await Promise.all([@@ -285,6 +343,7 @@ export function PlanDetailHeader() {})),]);+ if (pageKeyRef.current !== actionPageKey) return;// Land on the review section so the close/reopen system comment and the// updated status are visible (consistent with the other header advances).focusPlanPhase("review", page.expandPhase);@@ -294,6 +353,7 @@ export function PlanDetailHeader() {title: t("common.updated"),});} catch (error) {+ if (pageKeyRef.current !== actionPageKey) return;pushNotification({module: "bytebase",style: "CRITICAL",@@ -368,7 +428,7 @@ export function PlanDetailHeader() {? secondaryActions.slice(1): secondaryActions;- const createSheets = async () => {+ const createSheets = async (actionPageKey: string) => {for (const spec of page.plan.specs) {let config = null;if (spec.config?.case === "changeDatabaseConfig")@@ -382,43 +442,64 @@ export function PlanDetailHeader() {const createdSheet = await useAppStore.getState().createSheet(project.name, local);+ if (pageKeyRef.current !== actionPageKey) return false;removeLocalSheet(config.sheet);config.sheet = createdSheet.name;}}+ return true;};const handleCreatePlan = async () => {- if (createPlanBlockingReasons.length > 0) {- setShowCreateErrors(true);+ if (createPlanBlockingReasons.length > 0 || !canCreateDraftReview) {return;}+ const actionPageKey = page.pageKey;try {setUpdating(true);- await createSheets();- const createdPlan = await planServiceClientConnect.createPlan(- create(CreatePlanRequestSchema, {- parent: project.name,- plan: page.plan,- })- );+ if (!(await createSheets(actionPageKey))) return;+ const { plan } = await createPlanWithDraftReview({+ createIssue: (request) =>+ issueServiceClientConnect.createIssue(request),+ createPlan: (request) => planServiceClientConnect.createPlan(request),+ creator: `users/${currentUser.email}`,+ labels: page.creationIssueLabels,+ parent: project.name,+ plan: page.plan,+ });+ if (pageKeyRef.current !== actionPageKey) return;page.bypassLeaveGuardOnce();- void router.replace({+ await router.replace({name: PROJECT_V1_ROUTE_PLAN_DETAIL,params: {- projectId: extractProjectResourceName(createdPlan.name),- planId: extractPlanUID(createdPlan.name),+ projectId: extractProjectResourceName(plan.name),+ planId: extractPlanUID(plan.name),},});} catch (error) {+ if (pageKeyRef.current !== actionPageKey) return;+ if (error instanceof DraftReviewIssueCreationError) {+ page.bypassLeaveGuardOnce();+ await router.replace({+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,+ params: {+ projectId: extractProjectResourceName(error.plan.name),+ planId: extractPlanUID(error.plan.name),+ },+ });+ }pushNotification({module: "bytebase",style: "CRITICAL",title: t("common.failed"),- description: String(error),+ description: String(+ error instanceof DraftReviewIssueCreationError ? error.cause : error+ ),});} finally {- setUpdating(false);+ if (pageKeyRef.current === actionPageKey) {+ setUpdating(false);+ }}};@@ -432,6 +513,8 @@ export function PlanDetailHeader() {}),[emptySpecIdSet.size, page.plan, project, t]);+ const createDisabledReason =+ createPermissionReason ?? createPlanBlockingReasons[0];const showChecksWarning = useMemo(() => hasChecksWarning(page.plan),[page.plan]@@ -448,7 +531,7 @@ export function PlanDetailHeader() {);const resetReviewPopoverDraft = () => {- setSelectedLabels([]);+ setSelectedLabels(page.issue?.labels ?? []);setChecksWarningAcknowledged(false);};@@ -459,44 +542,31 @@ export function PlanDetailHeader() {}};- const handleCreateIssue = async () => {- if (createIssueConfirmErrors.length > 0) return;+ const handleSubmitDraftReview = async () => {+ if (+ !page.issue?.draft ||+ !canUpdateIssue ||+ createIssueConfirmErrors.length > 0+ ) {+ return;+ }+ const actionPageKey = page.pageKey;try {setSubmittingReview(true);- const createdIssue = await issueServiceClientConnect.createIssue(- create(CreateIssueRequestSchema, {- parent: project.name,- issue: create(IssueSchema, {- creator: `users/${currentUser.email}`,- labels: selectedLabels,- plan: page.plan.name,- status: IssueStatus.OPEN,- type: Issue_Type.DATABASE_CHANGE,- }),- })- );- handleReviewPopoverOpenChange(false);- patchState({- issue: createdIssue,- plan: {- ...page.plan,- issue: createdIssue.name,- },- });- if (shouldStayOnPlanDetailPage(page.plan)) {- await page.refreshState();- // Land the user on the review they just opened.- focusPlanPhase("review", page.expandPhase);- return;- }- void router.push({- name: PROJECT_V1_ROUTE_ISSUE_DETAIL,- params: {- projectId: extractProjectResourceName(page.plan.name),- issueId: extractIssueUID(createdIssue.name),- },+ const submittedIssue = await submitDraftReview({+ issue: page.issue,+ labels: selectedLabels,+ updateIssue: (request) =>+ issueServiceClientConnect.updateIssue(request),});+ if (pageKeyRef.current !== actionPageKey) return;+ handleReviewPopoverOpenChange(false);+ patchState({ issue: submittedIssue });+ await page.refreshState();+ if (pageKeyRef.current !== actionPageKey) return;+ focusPlanPhase("review", page.expandPhase);} catch (error) {+ if (pageKeyRef.current !== actionPageKey) return;pushNotification({module: "bytebase",style: "CRITICAL",@@ -504,7 +574,9 @@ export function PlanDetailHeader() {description: String(error),});} finally {- setSubmittingReview(false);+ if (pageKeyRef.current === actionPageKey) {+ setSubmittingReview(false);+ }}};@@ -555,38 +627,18 @@ export function PlanDetailHeader() {ready-for-review stay here (coupled to the title/create flow); allother states render through PlanLifecycleSlot. */}{lifecycle.kind === "create" ? (- <Popover- modal={false}- onOpenChange={setShowCreateErrors}- open={showCreateErrors && createPlanBlockingReasons.length > 0}+ <Button+ disabled={+ updating ||+ !canCreateDraftReview ||+ createPlanBlockingReasons.length > 0+ }+ onClick={() => void handleCreatePlan()}+ title={createDisabledReason}>- <Button- disabled={updating}- onClick={() => void handleCreatePlan()}- ref={createButtonRef}- >- {updating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}- {t("common.create")}- </Button>- <PopoverContent- anchor={createButtonRef}- className="max-w-xs overflow-hidden border-error/40 p-0"- initialFocus={titleMissing ? titleInputRef : false}- >- <Alert- className="rounded-none border-0 shadow-none"- description={- <ul className="list-disc pl-4">- {createPlanBlockingReasons.map((reason) => (- <li key={reason}>{reason}</li>- ))}- </ul>- }- title={t("plan.cannot-create")}- variant="error"- />- </PopoverContent>- </Popover>+ {updating && <Loader2 className="mr-2 size-4 animate-spin" />}+ {t("common.create")}+ </Button>) : lifecycle.kind === "ready-for-review" ? (<Popoveropen={showReviewPopover}@@ -615,7 +667,7 @@ export function PlanDetailHeader() {onChecksWarningAcknowledgedChange={setChecksWarningAcknowledged}- onConfirm={() => void handleCreateIssue()}+ onConfirm={() => void handleSubmitDraftReview()}onSelectedLabelsChange={setSelectedLabels}selectedLabels={selectedLabels}showChecksWarning={showChecksWarning}@@ -681,7 +733,7 @@ function ReadyForReviewPopoverContent({forceIssueLabels: boolean;issueLabels: IssueLabel[];onCancel: () => void;- onChecksWarningAcknowledgedChange: (checked: boolean) => void;+ onChecksWarningAcknowledgedChange?: (checked: boolean) => void;onConfirm: () => void;onSelectedLabelsChange: (labels: string[]) => void;selectedLabels: string[];@@ -693,9 +745,7 @@ function ReadyForReviewPopoverContent({return (<div className="flex flex-col gap-y-4">{showChecksWarning && (- <div className="rounded-sm border border-warning/30 bg-warning/10 px-3 py-2 text-sm text-warning">- {t("issue.checks-warning-hint")}- </div>+ <Alert variant="warning" description={t("issue.checks-warning-hint")} />)}<IssueLabelSelectlabels={issueLabels}@@ -708,7 +758,7 @@ function ReadyForReviewPopoverContent({<Checkboxchecked={checksWarningAcknowledged}onCheckedChange={(checked) =>- onChecksWarningAcknowledgedChange(checked)+ onChecksWarningAcknowledgedChange?.(checked)}/><span>@@ -719,9 +769,14 @@ function ReadyForReviewPopoverContent({</label>)}{confirmErrors.length > 0 && (- <div className="whitespace-pre-line rounded-sm border border-error/30 bg-error/5 px-3 py-2 text-sm text-error">- {confirmErrors.join("\n")}- </div>+ <Alert+ variant="error"+ description={+ <span className="whitespace-pre-line">+ {confirmErrors.join("\n")}+ </span>+ }+ />)}<div className="flex justify-start gap-x-2 pt-1"><Button@@ -733,7 +788,7 @@ function ReadyForReviewPopoverContent({onClick={onConfirm}size="sm">- {submitting && <Loader2 className="h-4 w-4 animate-spin" />}+ {submitting && <Loader2 className="size-4 animate-spin" />}{t("common.confirm")}</Button><Button onClick={onCancel} size="sm" appearance="secondary">diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeaderDetails.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeaderDetails.tsxindex 98076e2365..439f68d529 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeaderDetails.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeaderDetails.tsx@@ -4,14 +4,18 @@// description-edit state; the title row owns the title + lifecycle slot.import { create } from "@bufbuild/protobuf";import { ChevronUp, Plus } from "lucide-react";-import { useEffect, useMemo, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";-import { planServiceClientConnect } from "@/connect";+import { issueServiceClientConnect, planServiceClientConnect } from "@/connect";import { MarkdownEditor } from "@/react/components/MarkdownEditor";import { Button } from "@/react/components/ui/button";import { Textarea } from "@/react/components/ui/textarea";import { cn } from "@/react/lib/utils";import { pushNotification } from "@/store";+import {+ IssueSchema,+ UpdateIssueRequestSchema,+} from "@/types/proto-es/v1/issue_service_pb";import {PlanSchema,UpdatePlanRequestSchema,@@ -26,27 +30,47 @@ export function PlanDetailHeaderDetails() {const { patchState, setEditing } = page;const currentUser = page.currentUser;const project = page.project;- const [description, setDescription] = useState(page.plan.description);+ const draftIssue = page.issue?.draft === true;+ const persistedDescription =+ page.issue && !draftIssue ? page.issue.description : page.plan.description;+ const [description, setDescription] = useState(persistedDescription);const [editingDescription, setEditingDescription] = useState(false);const [showFullDescription, setShowFullDescription] = useState(false);const [updating, setUpdating] = useState(false);+ const pageKeyRef = useRef(page.pageKey);+ pageKeyRef.current = page.pageKey;++ useEffect(() => {+ setDescription(persistedDescription);+ setEditingDescription(false);+ setShowFullDescription(false);+ setUpdating(false);+ setEditing("description", false);+ }, [page.pageKey]);useEffect(() => {- setDescription((prev) =>- prev === page.plan.description ? prev : page.plan.description- );- }, [page.plan.description]);+ if (!editingDescription) {+ setDescription((prev) =>+ prev === persistedDescription ? prev : persistedDescription+ );+ }+ }, [editingDescription, persistedDescription]);const allowDescriptionEdit = useMemo(() => {if (page.readonly) return false;if (page.isCreating) return true;if (!page.issue && page.plan.hasRollout) return false;- return (+ const canUpdatePlan =page.plan.creator === currentUser.name ||- hasProjectPermissionV2(project, "bb.plans.update")- );+ hasProjectPermissionV2(project, "bb.plans.update");+ if (draftIssue) return canUpdatePlan;+ if (page.issue) {+ return hasProjectPermissionV2(project, "bb.issues.update");+ }+ return canUpdatePlan;}, [currentUser.name,+ draftIssue,page.isCreating,page.issue,page.plan.creator,@@ -67,19 +91,37 @@ export function PlanDetailHeaderDetails() {return;}+ const actionPageKey = page.pageKey;let saved = false;try {setUpdating(true);- const planPatch = create(PlanSchema, { ...page.plan, description });- const response = await planServiceClientConnect.updatePlan(- create(UpdatePlanRequestSchema, {- plan: planPatch,- updateMask: { paths: ["description"] },- })- );- patchState({ plan: response });+ if (page.issue && !draftIssue) {+ const issuePatch = create(IssueSchema, {+ ...page.issue,+ description,+ });+ const response = await issueServiceClientConnect.updateIssue(+ create(UpdateIssueRequestSchema, {+ issue: issuePatch,+ updateMask: { paths: ["description"] },+ })+ );+ if (pageKeyRef.current !== actionPageKey) return;+ patchState({ issue: response });+ } else {+ const planPatch = create(PlanSchema, { ...page.plan, description });+ const response = await planServiceClientConnect.updatePlan(+ create(UpdatePlanRequestSchema, {+ plan: planPatch,+ updateMask: { paths: ["description"] },+ })+ );+ if (pageKeyRef.current !== actionPageKey) return;+ patchState({ plan: response });+ }saved = true;} catch (error) {+ if (pageKeyRef.current !== actionPageKey) return;pushNotification({module: "bytebase",style: "CRITICAL",@@ -87,10 +129,12 @@ export function PlanDetailHeaderDetails() {description: String(error),});} finally {- setUpdating(false);- if (saved) {- setEditingDescription(false);- setEditing("description", false);+ if (pageKeyRef.current === actionPageKey) {+ setUpdating(false);+ if (saved) {+ setEditingDescription(false);+ setEditing("description", false);+ }}}};@@ -117,21 +161,21 @@ export function PlanDetailHeaderDetails() {) : (<ButtononClick={() => {- setDescription(page.plan.description);+ setDescription(persistedDescription);setEditingDescription(false);setEditing("description", false);}}size="xs"appearance="secondary">- <ChevronUp className="mr-1 h-4 w-4" />+ <ChevronUp className="mr-1 size-4" />{t("common.collapse")}</Button>)}{!page.isCreating && (<ButtononClick={() => {- setDescription(page.plan.description);+ setDescription(persistedDescription);setEditingDescription(false);setEditing("description", false);}}@@ -163,7 +207,8 @@ export function PlanDetailHeaderDetails() {className={cn("relative w-full rounded-md border border-transparent px-2 py-1 text-left text-sm text-control-light transition-all duration-200",!showFullDescription && "max-h-[4.5rem] overflow-hidden",- allowDescriptionEdit && "cursor-pointer hover:border-gray-200"+ allowDescriptionEdit &&+ "cursor-pointer hover:border-control-border")}onClick={() => {if (!allowDescriptionEdit) return;@@ -184,22 +229,23 @@ export function PlanDetailHeaderDetails() {<MarkdownEditor content={description} mode="preview" /></div>{!showFullDescription && isDescriptionLong && (- <div className="pointer-events-none absolute bottom-0 left-0 right-0 h-6 bg-gradient-to-t from-white to-transparent" />+ <div className="pointer-events-none absolute bottom-0 left-0 right-0 h-6 bg-gradient-to-t from-background to-transparent" />)}</div>{isDescriptionLong && (- <button- className="mt-1 px-2 text-xs text-control-placeholder hover:text-control"+ <Button+ className="mt-1 px-2 text-control-placeholder hover:text-control"onClick={(event) => {event.stopPropagation();setShowFullDescription((value) => !value);}}- type="button"+ size="xs"+ appearance="link">{showFullDescription? t("common.show-less"): t("common.show-more")}- </button>+ </Button>)}</div>) : allowDescriptionEdit ? (@@ -212,7 +258,7 @@ export function PlanDetailHeaderDetails() {size="xs"appearance="secondary">- <Plus className="mr-1 h-4 w-4" />+ <Plus className="mr-1 size-4" />{t("plan.description.placeholder")}</Button>) : null}diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailMeta.test.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailMeta.test.tsxnew file mode 100644index 0000000000..9a5a5c4e89--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailMeta.test.tsx@@ -0,0 +1,222 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import {+ type ButtonHTMLAttributes,+ type ReactElement,+ type ReactNode,+} from "react";+import { beforeEach, expect, test, vi } from "vitest";+import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";+import type { PlanDetailPageState } from "../shell/hooks/types";+import { PlanDetailMeta } from "./PlanDetailMeta";++const mocks = vi.hoisted(() => ({+ creationIssueLabels: [] as string[],+ page: undefined as unknown as PlanDetailPageState,+ patchState: vi.fn(),+ permissions: new Set<string>(),+ pushNotification: vi.fn(),+ setCreationIssueLabels: vi.fn(),+ updateIssue: vi.fn(),+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("@bufbuild/protobuf", () => ({+ create: (_schema: unknown, init?: Record<string, unknown>) => ({ ...init }),+}));++vi.mock("@/connect", () => ({+ issueServiceClientConnect: { updateIssue: mocks.updateIssue },+}));++vi.mock("@/react/components/HumanizeTs", () => ({ HumanizeTs: () => null }));++vi.mock("@/react/components/ui/checkbox", () => ({+ Checkbox: ({ checked }: { checked: boolean }) => (+ <input checked={checked} readOnly type="checkbox" />+ ),+}));++vi.mock("@/react/components/ui/popover", async () => {+ const React = await vi.importActual<typeof import("react")>("react");+ const PopoverContext = React.createContext<{+ onOpenChange?: (open: boolean) => void;+ open: boolean;+ }>({ open: false });++ return {+ Popover: ({+ children,+ onOpenChange,+ open = false,+ }: {+ children: ReactNode;+ onOpenChange?: (open: boolean) => void;+ open?: boolean;+ }) => (+ <PopoverContext.Provider value={{ onOpenChange, open }}>+ <div>{children}</div>+ </PopoverContext.Provider>+ ),+ PopoverContent: ({ children }: { children: ReactNode }) => {+ const { open } = React.useContext(PopoverContext);+ return open ? <div>{children}</div> : null;+ },+ PopoverTrigger: ({+ children,+ render,+ }: {+ children: ReactNode;+ render?: ReactElement<ButtonHTMLAttributes<HTMLButtonElement>>;+ }) => {+ const { onOpenChange, open } = React.useContext(PopoverContext);+ if (!React.isValidElement(render)) return <>{children}</>;+ const originalOnClick = render.props.onClick;+ return React.cloneElement(+ render,+ {+ onClick: (event) => {+ originalOnClick?.(event);+ onOpenChange?.(!open);+ },+ },+ children+ );+ },+ };+});++vi.mock("@/react/lib/utils", () => ({+ cn: (...classes: Array<string | false | null | undefined>) =>+ classes.filter(Boolean).join(" "),+}));++vi.mock("@/store", () => ({+ extractUserEmail: (name: string) => name,+ pushNotification: mocks.pushNotification,+}));++vi.mock("@/types", () => ({ getTimeForPbTimestampProtoEs: () => 0 }));++vi.mock("@/utils", () => ({+ colorToHex: () => "#000000",+ hasProjectPermissionV2: (_project: unknown, permission: string) =>+ mocks.permissions.has(permission),+}));++vi.mock("../shell/PlanDetailContext", () => ({+ usePlanDetailContext: () => mocks.page,+}));++const makePage = (): PlanDetailPageState =>+ ({+ creationIssueLabels: mocks.creationIssueLabels,+ isCreating: false,+ issue: {+ draft: true,+ labels: ["alpha"],+ name: "projects/p1/issues/456",+ status: IssueStatus.OPEN,+ },+ patchState: mocks.patchState,+ plan: {+ creator: "users/[email protected]",+ name: "projects/p1/plans/123",+ },+ project: {+ issueLabels: [{ value: "alpha" }, { value: "beta" }],+ name: "projects/p1",+ },+ setCreationIssueLabels: mocks.setCreationIssueLabels,+ }) as unknown as PlanDetailPageState;++beforeEach(() => {+ vi.clearAllMocks();+ mocks.creationIssueLabels = [];+ mocks.page = makePage();+ mocks.permissions = new Set();+ mocks.updateIssue.mockImplementation(async (request) => request.issue);+});++test("edits Issue labels directly on the preview creation page", () => {+ mocks.creationIssueLabels = ["alpha"];+ const page = makePage();+ mocks.page = {+ ...page,+ isCreating: true,+ issue: undefined,+ project: {+ ...page.project,+ forceIssueLabels: true,+ },+ };++ render(<PlanDetailMeta />);++ expect(screen.getByText("alpha")).toBeVisible();+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ const labelsButton = screen.getByRole("button", { name: "issue.labels" });+ expect(labelsButton).toBeEnabled();+ fireEvent.click(labelsButton);+ fireEvent.click(screen.getByRole("button", { name: "beta" }));++ expect(mocks.setCreationIssueLabels).toHaveBeenCalledWith([+ "alpha",+ "beta",+ ]);+});++test("does not warn about missing Issue labels during creation", () => {+ const page = makePage();+ mocks.page = {+ ...page,+ isCreating: true,+ issue: undefined,+ project: {+ ...page.project,+ forceIssueLabels: true,+ },+ };++ render(<PlanDetailMeta />);++ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+});++test("keeps draft labels read-only without issues.update and editable with it", async () => {+ const { rerender } = render(<PlanDetailMeta />);++ expect(screen.getByRole("button", { name: "issue.labels" })).toBeDisabled();+ expect(+ screen.queryByRole("button", { name: "common.remove" })+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "beta" })+ ).not.toBeInTheDocument();++ mocks.permissions = new Set(["bb.issues.update"]);+ mocks.page = {+ ...mocks.page,+ project: { ...mocks.page.project },+ };+ rerender(<PlanDetailMeta />);++ const labelsButton = screen.getByRole("button", { name: "issue.labels" });+ expect(labelsButton).toBeEnabled();+ expect(screen.getByRole("button", { name: "common.remove" })).toBeEnabled();+ fireEvent.click(labelsButton);+ fireEvent.click(screen.getByRole("button", { name: "beta" }));++ await waitFor(() => expect(mocks.updateIssue).toHaveBeenCalledOnce());+ expect(mocks.updateIssue).toHaveBeenCalledWith(+ expect.objectContaining({+ issue: expect.objectContaining({+ draft: true,+ labels: ["alpha", "beta"],+ }),+ updateMask: { paths: ["labels"] },+ })+ );+});diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailMeta.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailMeta.tsxindex 8266f1b9ed..736ba47f75 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailMeta.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailMeta.tsx@@ -54,7 +54,16 @@ export function PlanDetailMeta() {}, [page.issue, project]);if (page.isCreating) {- return null;+ return (+ <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-control-placeholder">+ <InlineLabels+ allowChange+ issueLabels={project?.issueLabels ?? []}+ labels={page.creationIssueLabels}+ onUpdate={page.setCreationIssueLabels}+ />+ </div>+ );}const handleLabelsUpdate = async (labels: string[]) => {@@ -118,7 +127,7 @@ function InlineLabels({allowChange: boolean;issueLabels: Array<{ color?: Color; value: string }>;labels: string[];- onUpdate: (labels: string[]) => Promise<void>;+ onUpdate: (labels: string[]) => Promise<void> | void;}) {const { t } = useTranslation();const [open, setOpen] = useState(false);diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailRollbackSheet.lifecycle.test.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailRollbackSheet.lifecycle.test.tsxnew file mode 100644index 0000000000..ed3fdb98a9--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailRollbackSheet.lifecycle.test.tsx@@ -0,0 +1,180 @@+import { act, render, screen, waitFor } from "@testing-library/react";+import type { ReactNode } from "react";+import { beforeEach, describe, expect, test, vi } from "vitest";+import type { Task, TaskRun } from "@/types/proto-es/v1/rollout_service_pb";++const mocks = vi.hoisted(() => ({+ previewTaskRunRollback: vi.fn(),+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("@/connect", () => ({+ issueServiceClientConnect: {},+ planServiceClientConnect: {},+ rolloutServiceClientConnect: {+ previewTaskRunRollback: mocks.previewTaskRunRollback,+ },+}));++vi.mock("@/react/components/monaco", () => ({+ ReadonlyMonaco: ({ content }: { content: string }) => (+ <div data-testid="rollback-statement">{content}</div>+ ),+}));++vi.mock("@/react/components/PermissionGuard", () => ({+ PermissionGuard: ({ children }: { children: ReactNode }) => <>{children}</>,+ usePermissionCheck: () => [true, undefined],+}));++vi.mock("@/react/components/ui/alert", () => ({+ Alert: ({ description }: { description: ReactNode }) => (+ <div role="alert">{description}</div>+ ),+}));++vi.mock("@/react/components/ui/badge", () => ({+ Badge: ({ children }: { children: ReactNode }) => <span>{children}</span>,+}));++vi.mock("@/react/components/ui/button", () => ({+ Button: ({+ children,+ ...props+ }: React.ButtonHTMLAttributes<HTMLButtonElement>) => (+ <button {...props}>{children}</button>+ ),+}));++vi.mock("@/react/components/ui/checkbox", () => ({+ Checkbox: () => <input type="checkbox" />,+}));++vi.mock("@/react/components/ui/sheet", () => ({+ Sheet: ({ children, open }: { children: ReactNode; open: boolean }) =>+ open ? <>{children}</> : null,+ SheetBody: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ SheetContent: ({ children }: { children: ReactNode }) => (+ <div>{children}</div>+ ),+ SheetFooter: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ SheetHeader: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ SheetTitle: ({ children }: { children: ReactNode }) => <h2>{children}</h2>,+}));++vi.mock("@/react/hooks/useAppState", () => ({+ useCurrentUser: () => ({ name: "users/[email protected]" }),+}));++vi.mock("@/react/hooks/useProjectByName", () => ({+ useProjectByName: () => ({ name: "projects/p1" }),+}));++vi.mock("@/react/router", () => ({ router: { push: vi.fn() } }));++vi.mock("@/react/stores/app", () => ({+ useAppStore: Object.assign(+ (selector: (state: unknown) => unknown) =>+ selector({ projectsByName: { "projects/p1": { name: "projects/p1" } } }),+ { getState: () => ({ createSheet: vi.fn() }) }+ ),+}));++vi.mock("@/store", () => ({ pushNotification: vi.fn() }));++vi.mock("@/utils", () => ({+ extractPlanUID: () => "1",+ extractProjectResourceName: () => "p1",+}));++vi.mock("./PlanTargetDisplay", () => ({+ PlanTargetDisplay: ({ target }: { target: string }) => <span>{target}</span>,+}));++vi.mock("./rollbackDraft", () => ({ createRollbackDraftReview: vi.fn() }));++import { PlanDetailRollbackSheet } from "./PlanDetailRollbackSheet";++type PreviewResult = { statement: string };++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((next) => {+ resolve = next;+ });+ return { promise, resolve };+}++const task = (name: string) =>+ ({ name: `tasks/${name}`, target: `instances/i/databases/${name}` }) as Task;+const taskRun = (name: string) => ({ name: `taskRuns/${name}` }) as TaskRun;+const itemsA = [{ task: task("a"), taskRun: taskRun("a") }];+const itemsB = [{ task: task("b"), taskRun: taskRun("b") }];++describe("PlanDetailRollbackSheet request lifecycle", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ test("ignores a preview response from a prior open entity", async () => {+ const previewA = deferred<PreviewResult>();+ const previewB = deferred<PreviewResult>();+ mocks.previewTaskRunRollback.mockImplementation(+ (request: { name: string }) =>+ request.name === "taskRuns/a" ? previewA.promise : previewB.promise+ );+ const onOpenChange = vi.fn();+ const { rerender } = render(+ <PlanDetailRollbackSheet+ items={itemsA}+ onOpenChange={onOpenChange}+ open+ projectName="projects/p1"+ rolloutName="projects/p1/plans/1/rollout"+ />+ );+ await waitFor(() =>+ expect(mocks.previewTaskRunRollback).toHaveBeenCalled()+ );++ rerender(+ <PlanDetailRollbackSheet+ items={itemsA}+ onOpenChange={onOpenChange}+ open={false}+ projectName="projects/p1"+ rolloutName="projects/p1/plans/1/rollout"+ />+ );+ rerender(+ <PlanDetailRollbackSheet+ items={itemsB}+ onOpenChange={onOpenChange}+ open+ projectName="projects/p1"+ rolloutName="projects/p1/plans/2/rollout"+ />+ );++ previewB.resolve({ statement: "ROLLBACK B" });+ await waitFor(() =>+ expect(screen.getByTestId("rollback-statement")).toHaveTextContent(+ "ROLLBACK B"+ )+ );++ await act(async () => {+ previewA.resolve({ statement: "ROLLBACK A" });+ await Promise.resolve();+ await Promise.resolve();+ });++ expect(screen.getByTestId("rollback-statement")).toHaveTextContent(+ "ROLLBACK B"+ );+ expect(screen.queryByText("ROLLBACK A")).toBeNull();+ });+});diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailRollbackSheet.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailRollbackSheet.tsxindex ef4a47c08a..a44fba4991 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailRollbackSheet.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailRollbackSheet.tsx@@ -1,15 +1,20 @@import { create } from "@bufbuild/protobuf";import { createContextValues } from "@connectrpc/connect";import { DatabaseBackup, Loader2 } from "lucide-react";-import { useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { v4 as uuidv4 } from "uuid";import {+ issueServiceClientConnect,planServiceClientConnect,rolloutServiceClientConnect,} from "@/connect";import { silentContextKey } from "@/connect/context-key";import { ReadonlyMonaco } from "@/react/components/monaco";+import {+ PermissionGuard,+ usePermissionCheck,+} from "@/react/components/PermissionGuard";import { Alert } from "@/react/components/ui/alert";import { Badge } from "@/react/components/ui/badge";import { Button } from "@/react/components/ui/button";@@ -22,30 +27,22 @@ import {SheetHeader,SheetTitle,} from "@/react/components/ui/sheet";+import { useCurrentUser } from "@/react/hooks/useAppState";import { useProjectByName } from "@/react/hooks/useProjectByName";import { router } from "@/react/router";import { PROJECT_V1_ROUTE_PLAN_DETAIL } from "@/react/router/handles";import { useAppStore } from "@/react/stores/app";import { pushNotification } from "@/store";-import {- CreatePlanRequestSchema,- Plan_ChangeDatabaseConfigSchema,- Plan_SpecSchema,- PlanSchema,-} from "@/types/proto-es/v1/plan_service_pb";-import {- PreviewTaskRunRollbackRequestSchema,- type Task,- type TaskRun,-} from "@/types/proto-es/v1/rollout_service_pb";-import { SheetSchema } from "@/types/proto-es/v1/sheet_service_pb";+import type { Task, TaskRun } from "@/types/proto-es/v1/rollout_service_pb";+import { PreviewTaskRunRollbackRequestSchema } from "@/types/proto-es/v1/rollout_service_pb";import {extractPlanUID,extractPlanUIDFromRolloutName,extractProjectResourceName,- hasProjectPermissionV2,} from "@/utils";+import { DraftReviewIssueCreationError } from "../utils/header";import { PlanTargetDisplay } from "./PlanTargetDisplay";+import { createRollbackDraftReview } from "./rollbackDraft";export function PlanDetailRollbackSheet({open,@@ -64,6 +61,7 @@ export function PlanDetailRollbackSheet({}>;}) {const { t } = useTranslation();+ const currentUser = useCurrentUser();// subscribe to re-render on project cache changeconst projectsByName = useAppStore((s) => s.projectsByName);void projectsByName;@@ -84,58 +82,106 @@ export function PlanDetailRollbackSheet({}>>([]);const [step, setStep] = useState<1 | 2>(1);+ const requestGenerationRef = useRef(0);+ const requestControllersRef = useRef(new Set<AbortController>());+ const itemsRef = useRef(items);+ itemsRef.current = items;+ const itemsIdentity = useMemo(+ () =>+ JSON.stringify(+ items.map(({ task, taskRun }) => [task.name, task.target, taskRun.name])+ ),+ [items]+ );- useEffect(() => {- if (!open) {- setStep(1);- setPreviews([]);- setSelectedTaskRunNames([]);- return;+ const invalidateRequests = useCallback(() => {+ requestGenerationRef.current += 1;+ for (const controller of requestControllersRef.current) {+ controller.abort();}- if (items.length === 1) {- setSelectedTaskRunNames([items[0].taskRun.name]);- }- }, [items, open]);+ requestControllersRef.current.clear();+ }, []);- useEffect(() => {- if (!open || items.length !== 1 || step !== 1) {- return;- }- const only = items[0];- void (async () => {+ const requestPreviews = useCallback(+ async (targetItems: Array<{ task: Task; taskRun: TaskRun }>) => {+ invalidateRequests();+ const generation = requestGenerationRef.current;+ const controller = new AbortController();+ requestControllersRef.current.add(controller);+ setLoading(true);+ const nextPreviews = targetItems.map((item) => ({+ task: item.task,+ taskRun: item.taskRun,+ statement: undefined as string | undefined,+ error: undefined as string | undefined,+ }));try {- setLoading(true);- const response =- await rolloutServiceClientConnect.previewTaskRunRollback(- create(PreviewTaskRunRollbackRequestSchema, {- name: only.taskRun.name,- }),- {- contextValues: createContextValues().set(silentContextKey, true),+ for (const preview of nextPreviews) {+ try {+ const response =+ await rolloutServiceClientConnect.previewTaskRunRollback(+ create(PreviewTaskRunRollbackRequestSchema, {+ name: preview.taskRun.name,+ }),+ {+ contextValues: createContextValues().set(+ silentContextKey,+ true+ ),+ signal: controller.signal,+ }+ );+ if (requestGenerationRef.current !== generation) return;+ preview.statement = response.statement;+ } catch (error) {+ if (+ controller.signal.aborted ||+ requestGenerationRef.current !== generation+ ) {+ return;}- );- setPreviews([- {- task: only.task,- taskRun: only.taskRun,- statement: response.statement,- },- ]);- setStep(2);- } catch (error) {- setPreviews([- {- task: only.task,- taskRun: only.taskRun,- error: String(error),- },- ]);+ preview.error = String(error);+ }+ }+ if (requestGenerationRef.current !== generation) return;+ setPreviews(nextPreviews);setStep(2);} finally {+ requestControllersRef.current.delete(controller);+ if (requestGenerationRef.current === generation) {+ setLoading(false);+ }+ }+ },+ [invalidateRequests]+ );++ const handleOpenChange = useCallback(+ (nextOpen: boolean) => {+ if (!nextOpen) {+ invalidateRequests();setLoading(false);}- })();- }, [items, open, step]);+ onOpenChange(nextOpen);+ },+ [invalidateRequests, onOpenChange]+ );++ useEffect(() => {+ invalidateRequests();+ setLoading(false);+ setStep(1);+ setPreviews([]);+ setSelectedTaskRunNames([]);+ if (!open) return;++ const currentItems = itemsRef.current;+ if (currentItems.length === 1) {+ setSelectedTaskRunNames([currentItems[0].taskRun.name]);+ void requestPreviews(currentItems);+ }+ return invalidateRequests;+ }, [invalidateRequests, itemsIdentity, open, requestPreviews]);const selectedItems = useMemo(() =>@@ -143,18 +189,24 @@ export function PlanDetailRollbackSheet({[items, selectedTaskRunNames]);+ const [canCreateDraftReview, createPermissionReason] = usePermissionCheck(+ ["bb.plans.create", "bb.issues.create"],+ project+ );+ const [canUpdateIssue] = usePermissionCheck(["bb.issues.update"], project);+const canCreate = useMemo(() => {return (!loading &&previews.length > 0 &&previews.every((preview) => !preview.error) &&previews.some((preview) => preview.statement) &&- hasProjectPermissionV2(project, "bb.plans.create")+ canCreateDraftReview);- }, [loading, previews, project]);+ }, [canCreateDraftReview, loading, previews]);return (- <Sheet onOpenChange={onOpenChange} open={open}>+ <Sheet onOpenChange={handleOpenChange} open={open}><SheetContent width="wide"><SheetHeader><SheetTitle>{t("common.rollback")}</SheetTitle>@@ -181,7 +233,7 @@ export function PlanDetailRollbackSheet({return (<labelkey={item.taskRun.name}- className="flex cursor-pointer items-center gap-3 border-b border-control-border px-3 py-2 last:border-b-0 hover:bg-gray-50"+ className="flex cursor-pointer items-center gap-3 border-b border-control-border px-3 py-2 last:border-b-0 hover:bg-control-bg"><Checkboxchecked={checked}@@ -220,9 +272,15 @@ export function PlanDetailRollbackSheet({"task-run.rollback.preview-statement.description")}/>+ {!canUpdateIssue && (+ <Alert+ variant="warning"+ description={t("plan.draft-update-permission-required")}+ />+ )}{loading ? (<div className="flex items-center justify-center py-8 text-control-light">- <Loader2 className="h-5 w-5 animate-spin" />+ <Loader2 className="size-5 animate-spin" /></div>) : (previews.map((preview) => (@@ -246,10 +304,10 @@ export function PlanDetailRollbackSheet({max={256}/>) : (- <div className="flex items-center justify-center rounded-md border bg-gray-50 p-8">+ <div className="flex items-center justify-center rounded-md border border-control-border bg-control-bg p-8"><div className="flex flex-col items-center gap-y-2 text-center">- <DatabaseBackup className="h-6 w-6 text-gray-400" />- <p className="text-sm text-gray-500">+ <DatabaseBackup className="size-6 text-control-placeholder" />+ <p className="text-sm text-control-light">{t("task-run.rollback.no-statement-generated")}</p></div>@@ -263,123 +321,118 @@ export function PlanDetailRollbackSheet({</SheetBody><SheetFooter>{step === 1 ? (- <Button onClick={() => onOpenChange(false)} appearance="secondary">+ <Button+ onClick={() => handleOpenChange(false)}+ appearance="secondary"+ >{t("common.cancel")}</Button>) : (- <Button onClick={() => setStep(1)} appearance="secondary">+ <Button+ onClick={() => {+ invalidateRequests();+ setLoading(false);+ setStep(1);+ }}+ appearance="secondary"+ >{t("common.back")}</Button>)}{step === 1 ? (<Buttondisabled={selectedItems.length === 0}+ onClick={() => void requestPreviews(selectedItems)}+ >+ {t("common.next")}+ </Button>+ ) : null}+ <PermissionGuard+ permissions={["bb.plans.create", "bb.issues.create"]}+ project={project}+ >+ <Button+ disabled={step !== 2 || !canCreate}+ title={createPermissionReason}onClick={async () => {+ const successfulPreviews = previews.flatMap((preview) =>+ preview.statement+ ? [+ {+ statement: preview.statement,+ target: preview.task.target,+ },+ ]+ : []+ );+ if (successfulPreviews.length === 0) return;+ const actionGeneration = requestGenerationRef.current;try {setLoading(true);- const nextPreviews: Array<{- task: Task;- taskRun: TaskRun;- statement?: string;- error?: string;- }> = selectedItems.map((item) => ({- task: item.task,- taskRun: item.taskRun,- }));- for (const preview of nextPreviews) {- try {- const response =- await rolloutServiceClientConnect.previewTaskRunRollback(- create(PreviewTaskRunRollbackRequestSchema, {- name: preview.taskRun.name,- }),- {- contextValues: createContextValues().set(- silentContextKey,- true- ),- }- );- preview.statement = response.statement;- } catch (err) {- preview.error = String(err);+ const rolloutId = extractPlanUIDFromRolloutName(rolloutName);+ const { plan: createdPlan } = await createRollbackDraftReview(+ {+ createIssue: (request) =>+ issueServiceClientConnect.createIssue(request),+ createPlan: (request) =>+ planServiceClientConnect.createPlan(request),+ createSheet: (sheet) =>+ useAppStore+ .getState()+ .createSheet(normalizedProjectName, sheet),+ creator: currentUser.name,+ newId: uuidv4,+ parent: normalizedProjectName,+ previews: successfulPreviews,+ title: t("plan.rollback.title", { rolloutId }),+ description: t("plan.rollback.description", {+ count: successfulPreviews.length,+ rolloutId,+ }),}+ );+ if (requestGenerationRef.current !== actionGeneration) return;+ handleOpenChange(false);+ await router.push({+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,+ params: {+ projectId: extractProjectResourceName(createdPlan.name),+ planId: extractPlanUID(createdPlan.name),+ },+ });+ } catch (err) {+ if (requestGenerationRef.current !== actionGeneration) return;+ if (err instanceof DraftReviewIssueCreationError) {+ handleOpenChange(false);+ await router.push({+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,+ params: {+ projectId: extractProjectResourceName(err.plan.name),+ planId: extractPlanUID(err.plan.name),+ },+ });}- setPreviews(nextPreviews);- setStep(2);+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.failed"),+ description: String(+ err instanceof DraftReviewIssueCreationError+ ? err.cause+ : err+ ),+ });} finally {- setLoading(false);+ if (requestGenerationRef.current === actionGeneration) {+ setLoading(false);+ }}}}>- {t("common.next")}+ {loading && <Loader2 className="size-4 animate-spin" />}+ {t("common.confirm")}</Button>- ) : null}- <Button- disabled={step !== 2 || !canCreate}- onClick={async () => {- if (previews.length === 0) return;- try {- setLoading(true);- const specs = [];- for (const preview of previews) {- if (!preview.statement) continue;- const sheet = await useAppStore.getState().createSheet(- projectName,- create(SheetSchema, {- name: `${projectName}/sheets/${uuidv4()}`,- content: new TextEncoder().encode(preview.statement),- })- );- specs.push(- create(Plan_SpecSchema, {- id: uuidv4(),- config: {- case: "changeDatabaseConfig",- value: create(Plan_ChangeDatabaseConfigSchema, {- targets: [preview.task.target],- sheet: sheet.name,- }),- },- })- );- }- const plan = create(PlanSchema, {- name: `${projectName}/plans/${uuidv4()}`,- title: `Rollback for rollout#${extractPlanUIDFromRolloutName(- rolloutName- )}`,- description: `This plan is created to rollback ${previews.length} task(s) in rollout #${extractPlanUIDFromRolloutName(rolloutName)}`,- specs,- });- const createdPlan = await planServiceClientConnect.createPlan(- create(CreatePlanRequestSchema, {- parent: projectName,- plan,- })- );- void router.push({- name: PROJECT_V1_ROUTE_PLAN_DETAIL,- params: {- projectId: extractProjectResourceName(projectName),- planId: extractPlanUID(createdPlan.name),- },- });- } catch (err) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.failed"),- description: String(err),- });- } finally {- setLoading(false);- }- }}- >- {loading && <Loader2 className="h-4 w-4 animate-spin" />}- {t("common.confirm")}- </Button>+ </PermissionGuard></SheetFooter></SheetContent></Sheet>diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/PlanLifecycleSlot.tsx b/frontend/src/react/pages/project/plan-detail/components/lifecycle/PlanLifecycleSlot.tsxindex 5d8a0f53b7..dca299ec3f 100644--- a/frontend/src/react/pages/project/plan-detail/components/lifecycle/PlanLifecycleSlot.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/PlanLifecycleSlot.tsx@@ -22,6 +22,12 @@ export function PlanLifecycleSlot({const page = usePlanDetailContext();switch (state.kind) {+ case "incomplete":+ return (+ <LifecycleStamp size="md" tone="error">+ {t("plan.lifecycle.incomplete")}+ </LifecycleStamp>+ );case "review-generating":// The approval flow is still being generated — show the Review affordance// disabled with a loading spinner; no click action until it resolves.@@ -51,8 +57,7 @@ export function PlanLifecycleSlot({return <FrontierStatusStamp stage={state.stage} />;default:// create / ready-for-review render in the header; closed / deployed are- // terminal stamps rendered left of the title (PlanLifecycleStamp); none- // renders nothing.+ // terminal stamps rendered left of the title and none renders nothing.return null;}}diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.test.ts b/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.test.tsindex 5a08e890b1..e03bc5bd1c 100644--- a/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.test.ts+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.test.ts@@ -29,6 +29,7 @@ const base: PlanLifecycleResolverInput = {planState: State.ACTIVE,hasIssue: true,issueStatus: IssueStatus.OPEN,+ issueDraft: false,approvalStatus: ApprovalStatus.PENDING,hasCurrentStep: false,isCurrentUserCandidate: false,@@ -58,14 +59,44 @@ describe("resolvePlanLifecycleHeaderState — draft & terminal", () => {expect(resolve({ planState: State.DELETED }).kind).toBe("closed");});- test("no issue yet -> ready for review", () => {- expect(resolve({ hasIssue: false }).kind).toBe("ready-for-review");+ test("a valid Draft Review Issue is ready for review", () => {+ expect(resolve({ issueDraft: true }).kind).toBe("ready-for-review");+ });++ test("draft lifecycle wins over malformed stale rollout data", () => {+ expect(+ resolve({+ issueDraft: true,+ hasRollout: true,+ rollout: rollout(stage("s1", [Task_Status.NOT_STARTED])),+ }).kind+ ).toBe("ready-for-review");+ });++ test("a persisted plan without a loadable linked issue is incomplete", () => {+ expect(resolve({ hasIssue: false }).kind).toBe("incomplete");});test("canceled review with no rollout -> closed", () => {expect(resolve({ issueStatus: IssueStatus.CANCELED }).kind).toBe("closed");});+ test("closing and reopening a draft preserves its draft lifecycle", () => {+ expect(+ resolve({+ issueDraft: true,+ planState: State.DELETED,+ issueStatus: IssueStatus.CANCELED,+ }).kind+ ).toBe("closed");+ expect(+ resolve({+ issueDraft: true,+ issueStatus: IssueStatus.OPEN,+ }).kind+ ).toBe("ready-for-review");+ });+test("canceled review is terminal even with a rollout (not deploy)", () => {expect(resolve({diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.ts b/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.tsindex 1142ad3bc6..bc05c7b635 100644--- a/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.ts+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.ts@@ -33,6 +33,7 @@ export type PlanLifecycleHeaderState =// Draft & review setup.| { kind: "create" }| { kind: "ready-for-review" }+ | { kind: "incomplete" }| { kind: "closed" } // terminal stamp// Review.| { kind: "review-generating" } // disabled + loading@@ -55,6 +56,7 @@ export interface PlanLifecycleResolverInput {hasIssue: boolean;issueStatus: IssueStatus | undefined;+ issueDraft: boolean;approvalStatus: ApprovalStatus;hasCurrentStep: boolean;isCurrentUserCandidate: boolean;@@ -101,6 +103,12 @@ export function resolvePlanLifecycleHeaderState(return { kind: "closed" };}+ // Draft is the lifecycle boundary. Malformed stale rollout/approval data must+ // never surface governance or deploy controls before the draft is submitted.+ if (input.hasIssue && input.issueDraft) {+ return { kind: "ready-for-review" };+ }+// A canceled review is terminal even after a rollout was created — surface the// closed stamp, not deploy actions (matches the issue detail page). This must// precede the rollout branch, which otherwise wins on a stale/orphaned rollout.@@ -120,9 +128,11 @@ export function resolvePlanLifecycleHeaderState(return { kind: "none" };}- // No review issue yet: the draft can be submitted for review.+ // Persisted plans must have a linked Draft Review Issue. A missing or+ // unloadable issue is the durable partial-success state left when the second+ // create call fails; expose it instead of offering another create/retry.if (!input.hasIssue) {- return { kind: "ready-for-review" };+ return { kind: "incomplete" };}// Approval flow still being generated — no safe action until it resolves.diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/usePlanLifecycleHeader.ts b/frontend/src/react/pages/project/plan-detail/components/lifecycle/usePlanLifecycleHeader.tsindex 03602e6053..3583e395ea 100644--- a/frontend/src/react/pages/project/plan-detail/components/lifecycle/usePlanLifecycleHeader.ts+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/usePlanLifecycleHeader.ts@@ -49,8 +49,9 @@ export function usePlanLifecycleHeader(// `issue` object — polling replaces `page.issue` with a fresh reference every// tick, which would re-run the resolver and re-render the header even when the// status/approval it consumes is unchanged.- const hasIssue = !!page.plan.issue || !!page.issue;+ const hasIssue = !!page.issue;const issueStatus = page.issue?.status;+ const issueDraft = page.issue?.draft ?? false;const approvalStatus =page.issue?.approvalStatus ?? ApprovalStatus.APPROVAL_STATUS_UNSPECIFIED;@@ -63,6 +64,7 @@ export function usePlanLifecycleHeader(planState: page.plan.state,hasIssue,issueStatus,+ issueDraft,approvalStatus,hasCurrentStep: currentRole !== "",isCurrentUserCandidate,@@ -77,6 +79,7 @@ export function usePlanLifecycleHeader(hasIssue,isCurrentUserCandidate,isGitOpsPlan,+ issueDraft,issueStatus,page.isCreating,page.plan.state,diff --git a/frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.test.tsx b/frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.test.tsxindex b1fab6eda3..e5a9ddb81a 100644--- a/frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.test.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.test.tsx@@ -324,10 +324,12 @@ const makeIssueComment = (status: IssueComment_Approval_Status): IssueComment =>const makeIssue = ({approvalStatus,+ draft = false,status = IssueStatus.OPEN,roles = ["roles/PROJECT_OWNER"],}: {approvalStatus: ApprovalStatus;+ draft?: boolean;status?: IssueStatus;roles?: string[];}): Issue =>@@ -335,6 +337,7 @@ const makeIssue = ({name: "projects/p1/issues/123",creator: "users/[email protected]",approvalStatus,+ draft,status,approvers: [],approvalTemplate: {@@ -438,6 +441,28 @@ beforeEach(() => {// ---------------------------------------------------------------------------describe("PlanReviewSection — five review states", () => {+ test("draft review issue hides governance UI until it is submitted", () => {+ const issue = makeIssue({+ approvalStatus: ApprovalStatus.APPROVAL_STATUS_UNSPECIFIED,+ draft: true,+ });+ const { container, render, unmount } = renderIntoContainer(+ <PlanDetailProvider value={makePageState(issue, makePlan())}>+ <PlanReviewSection />+ </PlanDetailProvider>+ );++ render();++ expect(container.textContent).not.toContain("issue.approval-flow.self");+ expect(container.textContent).not.toContain("plan.review.footer.");+ expect(container.textContent).not.toContain(+ "custom-approval.approval-flow.skip"+ );++ unmount();+ });+test("in-progress (PENDING, checks pass): footer shows waiting-on-review + muted underline bypass link", () => {const issue = makeIssue({ approvalStatus: ApprovalStatus.PENDING });const plan = makePlan();diff --git a/frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.tsx b/frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.tsxindex a676382230..61d0224ff0 100644--- a/frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.tsx@@ -56,6 +56,16 @@ export function PlanReviewSection() {if (!issue) return null;+ if (issue.draft) {+ return (+ <ReviewActivityTimeline+ comments={comments}+ issue={issue}+ plan={page.plan}+ />+ );+ }+if (issue.approvalStatus === ApprovalStatus.CHECKING) {return (<div className="flex items-center gap-x-2 p-4 text-sm text-control-placeholder">diff --git a/frontend/src/react/pages/project/plan-detail/components/review/ReviewActivityTimeline.test.tsx b/frontend/src/react/pages/project/plan-detail/components/review/ReviewActivityTimeline.test.tsxnew file mode 100644index 0000000000..7f4c4914d1--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/review/ReviewActivityTimeline.test.tsx@@ -0,0 +1,153 @@+import { create } from "@bufbuild/protobuf";+import { act, type ReactNode } from "react";+import { createRoot } from "react-dom/client";+import { describe, expect, test, vi } from "vitest";+import {+ IssueComment_ReviewSubmissionSchema,+ IssueCommentSchema,+ IssueSchema,+} from "@/types/proto-es/v1/issue_service_pb";+import { PlanSchema } from "@/types/proto-es/v1/plan_service_pb";++vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => {} },+ useTranslation: () => ({+ t: (key: string) =>+ key === "plan.review.activity.marked-ready-for-review"+ ? "marked this plan ready for review"+ : key,+ }),+}));++vi.mock("@/react/components/issue-activity/IssueCommentActivity", () => ({+ ActivityRowShell: ({+ header,+ icon,+ }: {+ header: ReactNode;+ icon: ReactNode;+ }) => (+ <li>+ {icon}+ {header}+ </li>+ ),+ CommentCreator: ({ creator }: { creator: { title: string } }) => (+ <span>{creator.title}</span>+ ),+ CommentIconBadge: ({ icon }: { icon: ReactNode }) => <span>{icon}</span>,+ canEditIssueComment: () => false,+ IssueCommentRow: () => <li data-testid="comment-row" />,+ ReviewSubmissionIcon: () => <span data-testid="review-submission-icon" />,+ ReviewSubmissionSentence: () => (+ <span>marked this plan ready for review</span>+ ),+}));++vi.mock("@/react/components/HumanizeTs", () => ({+ HumanizeTs: () => null,+}));++vi.mock("@/react/components/MarkdownEditor", () => ({+ MarkdownEditor: () => null,+}));++vi.mock("@/react/hooks/useAppState", () => ({+ useCurrentUser: () => ({ email: "[email protected]" }),+}));++vi.mock("@/react/hooks/useProjectByName", () => ({+ useProjectByName: () => undefined,+}));++vi.mock("@/react/stores/app", () => ({+ useAppStore: Object.assign(+ (selector: (state: unknown) => unknown) =>+ selector({+ getUserByIdentifier: () => ({+ name: "users/[email protected]",+ email: "[email protected]",+ title: "Submitter",+ }),+ }),+ { getState: () => ({}) }+ ),+}));++vi.mock("@/store", () => ({+ pushNotification: vi.fn(),+}));++vi.mock("@/types", () => ({+ getTimeForPbTimestampProtoEs: () => 0,+ unknownUser: (principal: string) => ({+ name: principal,+ email: principal,+ title: principal,+ }),+}));++vi.mock("@/utils/iam/permission", () => ({+ hasProjectPermissionV2: () => false,+}));++vi.mock("../../shell/PlanDetailContext", () => ({+ usePlanDetailContext: () => ({ projectId: "p1" }),+}));++vi.mock("./ReviewCommentComposer", () => ({+ ReviewCommentComposer: () => null,+}));++import { ReviewActivityTimeline } from "./ReviewActivityTimeline";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const reviewSubmission = (name: string) =>+ create(IssueCommentSchema, {+ name,+ creator: "users/[email protected]",+ event: {+ case: "reviewSubmission",+ value: create(IssueComment_ReviewSubmissionSchema),+ },+ });++describe("ReviewActivityTimeline", () => {+ test("renders one persisted Review Submission instead of a fallback duplicate", () => {+ const issue = create(IssueSchema, {+ name: "projects/p1/issues/1",+ creator: "users/[email protected]",+ draft: false,+ });+ const plan = create(PlanSchema, { name: "projects/p1/plans/1" });+ const container = document.createElement("div");+ const root = createRoot(container);++ act(() => {+ root.render(+ <ReviewActivityTimeline+ comments={[+ reviewSubmission("comments/submission"),+ reviewSubmission("comments/duplicate"),+ ]}+ issue={issue}+ plan={plan}+ />+ );+ });++ expect(+ container.textContent?.match(/marked this plan ready for review/g)+ ).toHaveLength(1);+ expect(+ container.querySelectorAll("[data-testid='review-submission-icon']")+ ).toHaveLength(1);+ expect(container.querySelectorAll("li")).toHaveLength(1);+ expect(container.querySelector("[data-testid='comment-row']")).toBeNull();++ act(() => root.unmount());+ });+});diff --git a/frontend/src/react/pages/project/plan-detail/components/review/ReviewActivityTimeline.tsx b/frontend/src/react/pages/project/plan-detail/components/review/ReviewActivityTimeline.tsxindex 6677f94236..66a9d7ac30 100644--- a/frontend/src/react/pages/project/plan-detail/components/review/ReviewActivityTimeline.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/review/ReviewActivityTimeline.tsx@@ -1,5 +1,5 @@-import { FileText, Loader2, Pencil, Send } from "lucide-react";-import { type ReactNode, useMemo, useState } from "react";+import { FileText, Loader2, Pencil } from "lucide-react";+import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { HumanizeTs } from "@/react/components/HumanizeTs";import {@@ -8,6 +8,8 @@ import {CommentIconBadge,canEditIssueComment,IssueCommentRow,+ ReviewSubmissionIcon,+ ReviewSubmissionSentence,} from "@/react/components/issue-activity/IssueCommentActivity";import { MarkdownEditor } from "@/react/components/MarkdownEditor";import { Button } from "@/react/components/ui/button";@@ -49,6 +51,10 @@ export function ReviewActivityTimeline({const project = useProjectByName(`${projectNamePrefix}${page.projectId}`);const [expanded, setExpanded] = useState(false);+ useEffect(() => {+ setExpanded(false);+ }, [page.pageKey]);+const entries = useMemo(() =>buildTimelineEntries({@@ -56,9 +62,17 @@ export function ReviewActivityTimeline({planCreateTime: plan.createTime,issueCreator: issue.creator,issueCreateTime: issue.createTime,+ issueDraft: issue.draft,comments,}),- [comments, issue.createTime, issue.creator, plan.createTime, plan.creator]+ [+ comments,+ issue.createTime,+ issue.creator,+ issue.draft,+ plan.createTime,+ plan.creator,+ ]);const items = useMemo(() => {const renderable = entries.filter(isRenderableEntry);@@ -142,17 +156,18 @@ function TornSeparator({return (<div className="flex items-center gap-x-2 py-2"><div aria-hidden="true" className="h-2 flex-1" style={TORN_EDGE_STYLE} />- <button- className="group shrink-0 bg-white px-2 text-xs text-control-light hover:text-control"+ <Button+ className="group shrink-0 bg-background px-2 text-control-light hover:text-control"onClick={onShowAll}- type="button"+ size="xs"+ appearance="link">{t("plan.review.activity.n-hidden-events", { count })}<span className="mx-1 text-control-placeholder">·</span><span className="text-accent group-hover:underline">{t("plan.review.activity.show-all")}</span>- </button>+ </Button><div aria-hidden="true" className="h-2 flex-1" style={TORN_EDGE_STYLE} /></div>);@@ -197,16 +212,13 @@ function SyntheticIcon({}: {type: "plan-created" | "ready-for-review";}) {+ if (type === "ready-for-review") {+ return <ReviewSubmissionIcon />;+ }return (<CommentIconBadgeclassName="bg-control-bg text-control"- icon={- type === "plan-created" ? (- <FileText className="h-4 w-4" />- ) : (- <Send className="h-4 w-4" />- )- }+ icon={<FileText className="size-4" />}/>);}@@ -223,14 +235,16 @@ function SyntheticHeader({return (<><ActorName principal={source.creator} />- <span className="wrap-break-word min-w-0 text-gray-600">- {source.type === "plan-created"- ? t("plan.review.activity.created-this-plan")- : t("plan.review.activity.marked-ready-for-review")}- </span>+ {source.type === "plan-created" ? (+ <span className="wrap-break-word min-w-0 text-control-light">+ {t("plan.review.activity.created-this-plan")}+ </span>+ ) : (+ <ReviewSubmissionSentence />+ )}{source.time && (<HumanizeTs- className="text-gray-500"+ className="text-control-light"ts={getTimeForPbTimestampProtoEs(source.time, 0) / 1000}/>)}@@ -265,6 +279,22 @@ function ReviewCommentRow({const [isEditing, setIsEditing] = useState(false);const [editContent, setEditContent] = useState(comment.comment);const [saving, setSaving] = useState(false);+ const pageKeyRef = useRef(page.pageKey);+ const commentNameRef = useRef(comment.name);+ pageKeyRef.current = page.pageKey;+ commentNameRef.current = comment.name;++ useEffect(() => {+ setIsEditing(false);+ setEditContent(comment.comment);+ setSaving(false);+ }, [page.pageKey]);++ useEffect(() => {+ if (!isEditing) {+ setEditContent(comment.comment);+ }+ }, [comment.comment, isEditing]);const allowEdit = canEditIssueComment(comment, currentUser.email, project);@@ -273,14 +303,28 @@ function ReviewCommentRow({setIsEditing(false);return;}+ const actionPageKey = page.pageKey;+ const actionCommentName = comment.name;try {setSaving(true);await useAppStore.getState().updateIssueComment({issueCommentName: comment.name,comment: editContent,});+ if (+ pageKeyRef.current !== actionPageKey ||+ commentNameRef.current !== actionCommentName+ ) {+ return;+ }setIsEditing(false);} catch (error) {+ if (+ pageKeyRef.current !== actionPageKey ||+ commentNameRef.current !== actionCommentName+ ) {+ return;+ }pushNotification({module: "bytebase",style: "CRITICAL",@@ -288,7 +332,12 @@ function ReviewCommentRow({description: String(error),});} finally {- setSaving(false);+ if (+ pageKeyRef.current === actionPageKey &&+ commentNameRef.current === actionCommentName+ ) {+ setSaving(false);+ }}};@@ -318,7 +367,7 @@ function ReviewCommentRow({onClick={() => void save()}size="xs">- {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}+ {saving && <Loader2 className="size-3.5 animate-spin" />}{t("common.save")}</Button></div>@@ -338,7 +387,7 @@ function ReviewCommentRow({size="xs"appearance="secondary">- <Pencil className="h-3.5 w-3.5" />+ <Pencil className="size-3.5" /></Button>) : undefined;diff --git a/frontend/src/react/pages/project/plan-detail/components/review/timelineEvents.test.ts b/frontend/src/react/pages/project/plan-detail/components/review/timelineEvents.test.tsindex bb91a92445..1e6a8d515d 100644--- a/frontend/src/react/pages/project/plan-detail/components/review/timelineEvents.test.ts+++ b/frontend/src/react/pages/project/plan-detail/components/review/timelineEvents.test.ts@@ -3,6 +3,7 @@ import { TimestampSchema } from "@bufbuild/protobuf/wkt";import { describe, expect, test } from "vitest";import {IssueComment_Approval_Status,+ IssueComment_ReviewSubmissionSchema,IssueCommentSchema,} from "@/types/proto-es/v1/issue_service_pb";import { buildTimelineEntries } from "./timelineEvents";@@ -22,6 +23,17 @@ const approvalComment = (event: { case: "approval", value: { status } },});+const reviewSubmission = (name: string) =>+ create(IssueCommentSchema, {+ name,+ creator: "users/[email protected]",+ createTime: create(TimestampSchema, { seconds: 3n, nanos: 0 }),+ event: {+ case: "reviewSubmission",+ value: create(IssueComment_ReviewSubmissionSchema),+ },+ });+describe("buildTimelineEntries", () => {test("synthetic head rows come first, oldest-first", () => {const entries = buildTimelineEntries({@@ -48,4 +60,42 @@ describe("buildTimelineEntries", () => {expect(entries.map((e) => e.id)).toEqual(["c1", "c2"]);expect(entries.every((e) => e.source.type === "comment")).toBe(true);});+ test("never synthesizes Ready for Review while the issue is still a draft", () => {+ const entries = buildTimelineEntries({+ planCreator: "users/[email protected]",+ issueCreator: "users/[email protected]",+ issueDraft: true,+ comments: [],+ });++ expect(entries.map((entry) => entry.source.type)).toEqual(["plan-created"]);+ });++ test("uses the persisted Review Submission activity without a synthetic duplicate", () => {+ const entries = buildTimelineEntries({+ issueCreator: "users/[email protected]",+ issueCreateTime: create(TimestampSchema, { seconds: 2n, nanos: 0 }),+ issueDraft: false,+ comments: [reviewSubmission("c-submit"), userComment("c1", "hello")],+ });++ expect(entries.map((entry) => entry.id)).toEqual(["c-submit", "c1"]);+ expect(entries[0].source).toMatchObject({+ type: "ready-for-review",+ creator: "users/[email protected]",+ time: { seconds: 3n },+ });+ });+ test("renders at most one persisted Review Submission row", () => {+ const entries = buildTimelineEntries({+ issueCreator: "users/[email protected]",+ issueDraft: false,+ comments: [+ reviewSubmission("c-submit"),+ reviewSubmission("c-submit-duplicate"),+ ],+ });++ expect(entries.map((entry) => entry.id)).toEqual(["c-submit"]);+ });});diff --git a/frontend/src/react/pages/project/plan-detail/components/review/timelineEvents.ts b/frontend/src/react/pages/project/plan-detail/components/review/timelineEvents.tsindex 882a6c6fde..626937de94 100644--- a/frontend/src/react/pages/project/plan-detail/components/review/timelineEvents.ts+++ b/frontend/src/react/pages/project/plan-detail/components/review/timelineEvents.ts@@ -24,8 +24,12 @@ export function buildTimelineEntries(input: {planCreateTime?: Timestamp;issueCreator?: string;issueCreateTime?: Timestamp;+ issueDraft?: boolean;comments: IssueComment[];}): TimelineEntry[] {+ const reviewSubmission = input.comments.find(+ (comment) => comment.event.case === "reviewSubmission"+ );const entries: TimelineEntry[] = [];if (input.planCreator) {entries.push({@@ -37,7 +41,7 @@ export function buildTimelineEntries(input: {},});}- if (input.issueCreator) {+ if (input.issueCreator && !input.issueDraft && !reviewSubmission) {entries.push({id: "ready-for-review",source: {@@ -48,6 +52,19 @@ export function buildTimelineEntries(input: {});}for (const comment of input.comments) {+ if (comment.event.case === "reviewSubmission") {+ if (comment === reviewSubmission) {+ entries.push({+ id: comment.name,+ source: {+ type: "ready-for-review",+ creator: comment.creator,+ time: comment.createTime,+ },+ });+ }+ continue;+ }entries.push({ id: comment.name, source: { type: "comment", comment } });}return entries;diff --git a/frontend/src/react/pages/project/plan-detail/components/rollbackDraft.test.ts b/frontend/src/react/pages/project/plan-detail/components/rollbackDraft.test.tsnew file mode 100644index 0000000000..6551409106--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/rollbackDraft.test.ts@@ -0,0 +1,111 @@+import { create } from "@bufbuild/protobuf";+import { describe, expect, test, vi } from "vitest";+import type { CreateIssueRequest } from "@/types/proto-es/v1/issue_service_pb";+import { IssueSchema } from "@/types/proto-es/v1/issue_service_pb";+import type { CreatePlanRequest } from "@/types/proto-es/v1/plan_service_pb";+import { PlanSchema } from "@/types/proto-es/v1/plan_service_pb";+import { DraftReviewIssueCreationError } from "../utils/header";+import { createRollbackDraftReview } from "./rollbackDraft";++const preview = {+ statement: "UPDATE t SET active = FALSE;",+ target: "instances/i/databases/d",+};+const localizedTitle = "Localized rollback title";+const localizedDescription = "Localized rollback description";++describe("createRollbackDraftReview", () => {+ test("persists rollback sheets, then creates one Plan and one linked draft Issue", async () => {+ const calls: string[] = [];+ const createSheet = vi.fn(async (sheet) => ({+ ...sheet,+ name: "projects/p1/sheets/sheet-1",+ }));+ const createPlan = vi.fn(async (request: CreatePlanRequest) => {+ calls.push("plan");+ const plan = create(PlanSchema, request.plan);+ plan.name = "projects/p1/plans/plan-1";+ return plan;+ });+ const createIssue = vi.fn(async (request: CreateIssueRequest) => {+ calls.push("issue");+ const issue = create(IssueSchema, request.issue);+ issue.name = "projects/p1/issues/issue-1";+ return issue;+ });++ const result = await createRollbackDraftReview({+ createIssue,+ createPlan,+ createSheet,+ creator: "users/[email protected]",+ newId: () => "generated",+ parent: "projects/p1",+ previews: [preview],+ title: localizedTitle,+ description: localizedDescription,+ });++ expect(calls).toEqual(["plan", "issue"]);+ expect(createSheet).toHaveBeenCalledWith(+ expect.objectContaining({+ content: new TextEncoder().encode(preview.statement),+ name: "projects/p1/sheets/generated",+ })+ );+ expect(createPlan.mock.calls[0][0].plan).toMatchObject({+ creator: "users/[email protected]",+ specs: [+ {+ config: {+ case: "changeDatabaseConfig",+ value: {+ sheet: "projects/p1/sheets/sheet-1",+ targets: [preview.target],+ },+ },+ },+ ],+ title: localizedTitle,+ description: localizedDescription,+ });+ expect(createIssue.mock.calls[0][0].issue).toMatchObject({+ creator: "users/[email protected]",+ draft: true,+ labels: [],+ plan: "projects/p1/plans/plan-1",+ });+ expect(result.plan.name).toBe("projects/p1/plans/plan-1");+ });++ test("does not retry and exposes the persisted malformed Plan when Issue creation fails", async () => {+ const createdPlan = create(PlanSchema, {+ name: "projects/p1/plans/plan-1",+ });+ const createPlan = vi.fn(async () => createdPlan);+ const createIssue = vi.fn(async () => {+ throw new Error("draft issue failed");+ });++ await expect(+ createRollbackDraftReview({+ createIssue,+ createPlan,+ createSheet: vi.fn(async (sheet) => ({+ ...sheet,+ name: "projects/p1/sheets/sheet-1",+ })),+ creator: "users/[email protected]",+ newId: () => "generated",+ parent: "projects/p1",+ previews: [preview],+ title: localizedTitle,+ description: localizedDescription,+ })+ ).rejects.toMatchObject({+ plan: createdPlan,+ } satisfies Partial<DraftReviewIssueCreationError>);+ expect(createPlan).toHaveBeenCalledOnce();+ expect(createIssue).toHaveBeenCalledOnce();+ });+});diff --git a/frontend/src/react/pages/project/plan-detail/components/rollbackDraft.ts b/frontend/src/react/pages/project/plan-detail/components/rollbackDraft.tsnew file mode 100644index 0000000000..6e67eb784e--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/rollbackDraft.ts@@ -0,0 +1,80 @@+import { create } from "@bufbuild/protobuf";+import type {+ CreateIssueRequest,+ Issue,+} from "@/types/proto-es/v1/issue_service_pb";+import type {+ CreatePlanRequest,+ Plan,+} from "@/types/proto-es/v1/plan_service_pb";+import {+ Plan_ChangeDatabaseConfigSchema,+ Plan_SpecSchema,+ PlanSchema,+} from "@/types/proto-es/v1/plan_service_pb";+import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";+import { SheetSchema } from "@/types/proto-es/v1/sheet_service_pb";+import { createPlanWithDraftReview } from "../utils/header";++export interface RollbackDraftPreview {+ statement: string;+ target: string;+}++export async function createRollbackDraftReview({+ createIssue,+ createPlan,+ createSheet,+ creator,+ newId,+ parent,+ previews,+ title,+ description,+}: {+ createIssue: (request: CreateIssueRequest) => Promise<Issue>;+ createPlan: (request: CreatePlanRequest) => Promise<Plan>;+ createSheet: (sheet: Sheet) => Promise<Sheet>;+ creator: string;+ newId: () => string;+ parent: string;+ previews: RollbackDraftPreview[];+ title: string;+ description: string;+}): Promise<{ issue: Issue; plan: Plan }> {+ const specs = [];+ for (const preview of previews) {+ const sheet = await createSheet(+ create(SheetSchema, {+ name: `${parent}/sheets/${newId()}`,+ content: new TextEncoder().encode(preview.statement),+ })+ );+ specs.push(+ create(Plan_SpecSchema, {+ id: newId(),+ config: {+ case: "changeDatabaseConfig",+ value: create(Plan_ChangeDatabaseConfigSchema, {+ targets: [preview.target],+ sheet: sheet.name,+ }),+ },+ })+ );+ }++ return createPlanWithDraftReview({+ createIssue,+ createPlan,+ creator,+ labels: [],+ parent,+ plan: create(PlanSchema, {+ creator,+ title,+ description,+ specs,+ }),+ });+}diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/types.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/types.tsindex 4d8f6ea6a8..5cff7ba966 100644--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/types.ts+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/types.ts@@ -33,6 +33,8 @@ export interface PlanDetailPageSnapshot {}export interface PlanDetailPageState extends PlanDetailPageSnapshot {+ creationIssueLabels: string[];+ setCreationIssueLabels: (labels: string[]) => void;isEditing: boolean;isRunningChecks: boolean;setIsRunningChecks: (running: boolean) => void;diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/useDerivedPlanState.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/useDerivedPlanState.tsindex ec584075d9..ac152014a1 100644--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/useDerivedPlanState.ts+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/useDerivedPlanState.ts@@ -15,6 +15,8 @@ type PhaseState = ReturnType<typeof usePhaseState>;export function useDerivedPlanState(params: {snapshot: PlanDetailPageSnapshot;+ creationIssueLabels: string[];+ setCreationIssueLabels: (labels: string[]) => void;isEditing: boolean;isRunningChecks: boolean;setIsRunningChecks: (running: boolean) => void;@@ -30,6 +32,8 @@ export function useDerivedPlanState(params: {}): PlanDetailPageState {const {snapshot,+ creationIssueLabels,+ setCreationIssueLabels,isEditing,isRunningChecks,setIsRunningChecks,@@ -97,6 +101,8 @@ export function useDerivedPlanState(params: {return useMemo(() => ({...snapshot,+ creationIssueLabels,+ setCreationIssueLabels,isEditing,isRunningChecks,setIsRunningChecks,@@ -117,6 +123,7 @@ export function useDerivedPlanState(params: {}),[editing,+ creationIssueLabels,isEditing,isRunningChecks,patchState,@@ -126,6 +133,7 @@ export function useDerivedPlanState(params: {routeName,routePhase,routeStageId,+ setCreationIssueLabels,selectedTaskName,snapshot,taskRunsByTaskName,diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.tsindex ce3d60b5ae..41fd68cb0a 100644--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.ts+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.ts@@ -187,6 +187,7 @@ export const usePlanDetailPage = ({const phase = usePhaseState();const editing = useEditingScopes();const storeApi = usePlanDetailStoreApi();+ const [creationIssueLabels, setCreationIssueLabels] = useState<string[]>([]);const [isRunningChecks, setIsRunningChecks] = useState(false);const latestSnapshotRef = useRef(snapshot);const { resolveLeaveConfirm } = useLeaveGuard();@@ -204,6 +205,9 @@ export const usePlanDetailPage = ({const routeTaskId = route.taskId;const setActivePhases = phase.setActivePhases;const pageIdentityKey = `${projectId}/${planId}`;+ useEffect(() => {+ setCreationIssueLabels([]);+ }, [pageIdentityKey]);const phaseSelectionRef = useRef<PhaseSelection>({});phaseSelectionRef.current = {routePhase,@@ -459,6 +463,8 @@ export const usePlanDetailPage = ({return useDerivedPlanState({snapshot,+ creationIssueLabels,+ setCreationIssueLabels,isEditing,isRunningChecks,setIsRunningChecks,diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/useRedirects.test.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/useRedirects.test.tsnew file mode 100644index 0000000000..779a7fe3c2--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/useRedirects.test.ts@@ -0,0 +1,42 @@+import { create } from "@bufbuild/protobuf";+import { describe, expect, test } from "vitest";+import { IssueSchema } from "@/types/proto-es/v1/issue_service_pb";+import {+ Plan_CreateDatabaseConfigSchema,+ Plan_SpecSchema,+ PlanSchema,+} from "@/types/proto-es/v1/plan_service_pb";+import { shouldRedirectToIssueDetail } from "./useRedirects";++const createDatabasePlan = () =>+ create(PlanSchema, {+ specs: [+ create(Plan_SpecSchema, {+ config: {+ case: "createDatabaseConfig",+ value: create(Plan_CreateDatabaseConfigSchema),+ },+ }),+ ],+ });++describe("shouldRedirectToIssueDetail", () => {+ test("keeps a linked draft create-database issue on Plan Detail", () => {+ const issue = create(IssueSchema, {+ draft: true,+ name: "projects/p1/issues/1",+ });++ expect(shouldRedirectToIssueDetail(createDatabasePlan(), issue)).toBe(+ false+ );+ });++ test("redirects a submitted create-database issue to Issue Detail", () => {+ const issue = create(IssueSchema, {+ name: "projects/p1/issues/1",+ });++ expect(shouldRedirectToIssueDetail(createDatabasePlan(), issue)).toBe(true);+ });+});diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/useRedirects.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/useRedirects.tsindex 8317f4da5b..8f08298284 100644--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/useRedirects.ts+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/useRedirects.ts@@ -4,8 +4,8 @@ import { type Issue } from "@/types/proto-es/v1/issue_service_pb";import type { Plan } from "@/types/proto-es/v1/plan_service_pb";import { getIssueRoute } from "@/utils";-const shouldRedirectToIssueDetail = (plan: Plan, issue?: Issue) => {- if (!issue?.name) {+export const shouldRedirectToIssueDetail = (plan: Plan, issue?: Issue) => {+ if (!issue?.name || issue.draft) {return false;}if (plan.specs.length === 0) {diff --git a/frontend/src/react/pages/project/plan-detail/utils/header.test.ts b/frontend/src/react/pages/project/plan-detail/utils/header.test.tsindex c4a39e0470..31f41cf84b 100644--- a/frontend/src/react/pages/project/plan-detail/utils/header.test.ts+++ b/frontend/src/react/pages/project/plan-detail/utils/header.test.ts@@ -1,12 +1,25 @@-import { describe, expect, test } from "vitest";-import type { Plan } from "@/types/proto-es/v1/plan_service_pb";+import { create } from "@bufbuild/protobuf";+import { describe, expect, test, vi } from "vitest";+import type {+ CreateIssueRequest,+ UpdateIssueRequest,+} from "@/types/proto-es/v1/issue_service_pb";+import { IssueSchema } from "@/types/proto-es/v1/issue_service_pb";+import type {+ CreatePlanRequest,+ Plan,+} from "@/types/proto-es/v1/plan_service_pb";+import { PlanSchema } from "@/types/proto-es/v1/plan_service_pb";import type { Project } from "@/types/proto-es/v1/project_service_pb";import {+ createPlanWithDraftReview,+ DraftReviewIssueCreationError,getCreateIssueBlockingErrors,getCreateIssueConfirmErrors,getCreatePlanBlockingReasons,hasChecksWarning,shouldStayOnPlanDetailPage,+ submitDraftReview,} from "./header";const t = (key: string) => key;@@ -73,6 +86,24 @@ describe("plan detail header create issue helpers", () => {);});+ test("blocks issue creation while plan checks are queued", () => {+ const project = {+ enforceSqlReview: false,+ forceIssueLabels: false,+ } as Project;++ expect(+ getCreateIssueBlockingErrors({+ emptySpecCount: 0,+ plan: makePlan(["changeDatabaseConfig"], { AVAILABLE: 1 }),+ project,+ t,+ })+ ).toContain(+ "custom-approval.issue-review.disallow-approve-reason.some-task-checks-are-still-running"+ );+ });+test("blocks data export issue creation", () => {const project = {enforceSqlReview: false,@@ -90,6 +121,122 @@ describe("plan detail header create issue helpers", () => {});});+describe("createPlanWithDraftReview", () => {+ const plan = create(PlanSchema, {+ name: "projects/p1/plans/placeholder",+ title: "Add index",+ description: "Reduce query latency",+ });+ const createdPlan = create(PlanSchema, {+ ...plan,+ name: "projects/p1/plans/123",+ });+ const draftIssue = create(IssueSchema, {+ name: "projects/p1/issues/456",+ draft: true,+ plan: createdPlan.name,+ });++ test("creates the plan first and then one linked draft issue with initial labels", async () => {+ const calls: string[] = [];+ const createPlan = vi.fn(async (_request: CreatePlanRequest) => {+ calls.push("plan");+ return createdPlan;+ });+ const createIssue = vi.fn(async (_request: CreateIssueRequest) => {+ calls.push("issue");+ return draftIssue;+ });++ const result = await createPlanWithDraftReview({+ createIssue,+ createPlan,+ creator: "users/[email protected]",+ labels: ["prod", "security"],+ parent: "projects/p1",+ plan,+ });++ expect(calls).toEqual(["plan", "issue"]);+ expect(result).toEqual({ issue: draftIssue, plan: createdPlan });+ expect(createIssue).toHaveBeenCalledOnce();+ expect(createIssue.mock.calls[0][0].issue).toMatchObject({+ creator: "users/[email protected]",+ description: "Reduce query latency",+ draft: true,+ labels: ["prod", "security"],+ plan: "projects/p1/plans/123",+ title: "Add index",+ });+ });++ test("reports the persisted malformed plan and never retries when draft issue creation fails", async () => {+ const createPlan = vi.fn(async () => createdPlan);+ const failure = new Error("issue creation denied");+ const createIssue = vi.fn(async () => {+ throw failure;+ });++ const promise = createPlanWithDraftReview({+ createIssue,+ createPlan,+ creator: "users/[email protected]",+ labels: [],+ parent: "projects/p1",+ plan,+ });++ await expect(promise).rejects.toMatchObject({+ cause: failure,+ plan: createdPlan,+ } satisfies Partial<DraftReviewIssueCreationError>);+ expect(createPlan).toHaveBeenCalledOnce();+ expect(createIssue).toHaveBeenCalledOnce();+ });+});++describe("submitDraftReview", () => {+ test("submits the persisted issue by clearing draft and retaining selected labels", async () => {+ const draft = create(IssueSchema, {+ name: "projects/p1/issues/456",+ draft: true,+ labels: ["old"],+ });+ const submitted = create(IssueSchema, {+ ...draft,+ draft: false,+ labels: ["prod"],+ });+ const updateIssue = vi.fn(+ async (_request: UpdateIssueRequest) => submitted+ );++ await expect(+ submitDraftReview({ issue: draft, labels: ["prod"], updateIssue })+ ).resolves.toBe(submitted);+ expect(updateIssue.mock.calls[0][0]).toMatchObject({+ issue: { draft: false, labels: ["prod"] },+ updateMask: { paths: ["draft", "labels"] },+ });+ });++ test("surfaces the submission failure without retrying", async () => {+ const failure = new Error("approval setup failed");+ const updateIssue = vi.fn(async () => {+ throw failure;+ });++ await expect(+ submitDraftReview({+ issue: create(IssueSchema, { draft: true }),+ labels: [],+ updateIssue,+ })+ ).rejects.toBe(failure);+ expect(updateIssue).toHaveBeenCalledOnce();+ });+});+describe("getCreatePlanBlockingReasons", () => {test("flags an empty title", () => {expect(diff --git a/frontend/src/react/pages/project/plan-detail/utils/header.ts b/frontend/src/react/pages/project/plan-detail/utils/header.tsindex efdc7e5da2..58a3812b51 100644--- a/frontend/src/react/pages/project/plan-detail/utils/header.ts+++ b/frontend/src/react/pages/project/plan-detail/utils/header.ts@@ -1,8 +1,99 @@-import type { Plan } from "@/types/proto-es/v1/plan_service_pb";+import { create } from "@bufbuild/protobuf";+import type {+ CreateIssueRequest,+ Issue,+ UpdateIssueRequest,+} from "@/types/proto-es/v1/issue_service_pb";+import {+ CreateIssueRequestSchema,+ Issue_Type,+ IssueSchema,+ IssueStatus,+ UpdateIssueRequestSchema,+} from "@/types/proto-es/v1/issue_service_pb";+import type {+ CreatePlanRequest,+ Plan,+} from "@/types/proto-es/v1/plan_service_pb";+import { CreatePlanRequestSchema } from "@/types/proto-es/v1/plan_service_pb";import type { Project } from "@/types/proto-es/v1/project_service_pb";type T = (key: string, options?: Record<string, unknown>) => string;+export class DraftReviewIssueCreationError extends Error {+ readonly plan: Plan;+ override readonly cause: unknown;++ constructor(plan: Plan, cause: unknown) {+ super("The plan was created, but its Draft Review Issue was not created");+ this.name = "DraftReviewIssueCreationError";+ this.plan = plan;+ this.cause = cause;+ }+}++export async function createPlanWithDraftReview({+ createIssue,+ createPlan,+ creator,+ labels,+ parent,+ plan,+}: {+ createIssue: (request: CreateIssueRequest) => Promise<Issue>;+ createPlan: (request: CreatePlanRequest) => Promise<Plan>;+ creator: string;+ labels: string[];+ parent: string;+ plan: Plan;+}): Promise<{ issue: Issue; plan: Plan }> {+ const createdPlan = await createPlan(+ create(CreatePlanRequestSchema, { parent, plan })+ );++ try {+ const issue = await createIssue(+ create(CreateIssueRequestSchema, {+ parent,+ issue: create(IssueSchema, {+ creator,+ description: createdPlan.description,+ draft: true,+ labels,+ plan: createdPlan.name,+ status: IssueStatus.OPEN,+ title: createdPlan.title,+ type: Issue_Type.DATABASE_CHANGE,+ }),+ })+ );+ return { issue, plan: createdPlan };+ } catch (error) {+ throw new DraftReviewIssueCreationError(createdPlan, error);+ }+}++export async function submitDraftReview({+ issue,+ labels,+ updateIssue,+}: {+ issue: Issue;+ labels: string[];+ updateIssue: (request: UpdateIssueRequest) => Promise<Issue>;+}): Promise<Issue> {+ return updateIssue(+ create(UpdateIssueRequestSchema, {+ issue: create(IssueSchema, {+ ...issue,+ draft: false,+ labels,+ }),+ updateMask: { paths: ["draft", "labels"] },+ })+ );+}+export const shouldStayOnPlanDetailPage = (plan: Plan): boolean => {if (plan.specs.length === 0) {return true;@@ -65,7 +156,7 @@ export const getCreateIssueBlockingErrors = ({if (plan.specs.some((spec) => spec.config?.case === "exportDataConfig")) {errors.push(t("issue.data-export.creation-not-supported"));}- if ((statusCount.RUNNING ?? 0) > 0) {+ if ((statusCount.AVAILABLE ?? 0) > 0 || (statusCount.RUNNING ?? 0) > 0) {errors.push(t("custom-approval.issue-review.disallow-approve-reason.some-task-checks-are-still-running"diff --git a/frontend/src/react/pages/project/utils/reviewBadge.test.ts b/frontend/src/react/pages/project/utils/reviewBadge.test.tsindex 178d5ea235..cf4e30adaa 100644--- a/frontend/src/react/pages/project/utils/reviewBadge.test.ts+++ b/frontend/src/react/pages/project/utils/reviewBadge.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";-import { getReviewBadge } from "./reviewBadge";+import { getPlanDraftState, getReviewBadge } from "./reviewBadge";describe("getReviewBadge", () => {it("returns undefined when there is no issue", () => {@@ -142,6 +142,60 @@ describe("getReviewBadge", () => {});});+ describe("getPlanDraftState", () => {+ it("recognizes a linked draft from its unspecified approval status", () => {+ expect(+ getPlanDraftState({+ approvalStatus: ApprovalStatus.APPROVAL_STATUS_UNSPECIFIED,+ hasRollout: false,+ isGitOpsPlan: false,+ issueName: "projects/p1/issues/123",+ })+ ).toBe("draft");+ });++ it("recognizes the durable incomplete state when the linked issue is absent", () => {+ expect(+ getPlanDraftState({+ approvalStatus: ApprovalStatus.APPROVAL_STATUS_UNSPECIFIED,+ hasRollout: false,+ isGitOpsPlan: false,+ issueName: "",+ })+ ).toBe("incomplete");+ });++ it("does not call submitted or deployed plans drafts", () => {+ expect(+ getPlanDraftState({+ approvalStatus: ApprovalStatus.PENDING,+ hasRollout: false,+ isGitOpsPlan: false,+ issueName: "projects/p1/issues/123",+ })+ ).toBeUndefined();+ expect(+ getPlanDraftState({+ approvalStatus: ApprovalStatus.APPROVAL_STATUS_UNSPECIFIED,+ hasRollout: true,+ isGitOpsPlan: false,+ issueName: "projects/p1/issues/123",+ })+ ).toBeUndefined();+ });++ it("keeps release-backed GitOps plans exempt from UI Plan validity", () => {+ expect(+ getPlanDraftState({+ approvalStatus: ApprovalStatus.APPROVAL_STATUS_UNSPECIFIED,+ hasRollout: false,+ isGitOpsPlan: true,+ issueName: "",+ })+ ).toBeUndefined();+ });+ });+describe("without issue status (Plan List caller)", () => {it("hasRollout=true + PENDING → 'bypassed' (closes BYT-9551 plan 201)", () => {expect(diff --git a/frontend/src/react/pages/project/utils/reviewBadge.ts b/frontend/src/react/pages/project/utils/reviewBadge.tsindex f9be2c2553..1142177234 100644--- a/frontend/src/react/pages/project/utils/reviewBadge.ts+++ b/frontend/src/react/pages/project/utils/reviewBadge.ts@@ -15,6 +15,24 @@ export interface ReviewBadge {variant: "default" | "secondary" | "destructive" | "warning" | "success";}+export type PlanDraftState = "draft" | "incomplete" | undefined;++export function getPlanDraftState(input: {+ approvalStatus: ApprovalStatus;+ hasRollout: boolean;+ isGitOpsPlan: boolean;+ issueName: string;+}): PlanDraftState {+ if (+ input.isGitOpsPlan ||+ input.hasRollout ||+ input.approvalStatus !== ApprovalStatus.APPROVAL_STATUS_UNSPECIFIED+ ) {+ return undefined;+ }+ return input.issueName ? "draft" : "incomplete";+}+export function getReviewBadge(input: ReviewBadgeInput): ReviewBadge | undefined {diff --git a/frontend/src/react/router/issueDetailRedirect.test.ts b/frontend/src/react/router/issueDetailRedirect.test.tsindex fa82468731..9e61267c2e 100644--- a/frontend/src/react/router/issueDetailRedirect.test.ts+++ b/frontend/src/react/router/issueDetailRedirect.test.ts@@ -18,8 +18,13 @@ import { issueDetailRedirectLoader } from "./issueDetailRedirect";const PLAN_NAME = "projects/p1/plans/456";-const makeIssue = (type: Issue_Type, plan = ""): Issue =>- ({ name: "projects/p1/issues/123", type, plan }) as unknown as Issue;+const makeIssue = (type: Issue_Type, plan = "", draft = false): Issue =>+ ({+ name: "projects/p1/issues/123",+ type,+ plan,+ draft,+ }) as unknown as Issue;const makePlan = (cases: string[]): Plan =>({@@ -55,6 +60,18 @@ describe("issueDetailRedirectLoader", () => {expect(mocks.getPlan).toHaveBeenCalledOnce();});+ test("redirects a Draft Review Issue URL to its Plan", async () => {+ mocks.getIssue.mockResolvedValue(+ makeIssue(Issue_Type.DATABASE_EXPORT, PLAN_NAME, true)+ );++ const res = await run({ projectId: "p1", issueId: "123" });++ expect(res?.status).toBe(302);+ expect(res?.headers.get("Location")).toBe("/projects/p1/plans/456");+ expect(mocks.getPlan).not.toHaveBeenCalled();+ });+test("preserves the query string on redirect", async () => {mocks.getIssue.mockResolvedValue(makeIssue(Issue_Type.DATABASE_CHANGE, PLAN_NAME)diff --git a/frontend/src/react/router/issueDetailRedirect.ts b/frontend/src/react/router/issueDetailRedirect.tsindex 63bb576446..c2a7efeee9 100644--- a/frontend/src/react/router/issueDetailRedirect.ts+++ b/frontend/src/react/router/issueDetailRedirect.ts@@ -10,16 +10,13 @@ import {import { GetPlanRequestSchema } from "@/types/proto-es/v1/plan_service_pb";import { extractPlanUID } from "@/utils/v1/issue/plan";-// BYT-9721: Plan Detail is the canonical review surface for schema/data change-// plans (3.20.0). This route loader redirects the issue-detail route to Plan-// Detail for those issues, preserving the query string. Create-database, export,-// and grant issues stay on Issue Detail.+// Plan Detail is the canonical review surface for Draft Review Issues and+// schema/data change plans. Drafts redirect directly from their linked plan;+// submitted create-database, export, and grant issues stay on Issue Detail.//-// The discriminator is the plan's specs, not the issue type: schema-change and-// create-database share the DATABASE_CHANGE proto type, so we fetch the plan and-// redirect iff `shouldStayOnPlanDetailPage` — the same predicate Plan Detail's-// own `useRedirects` uses to decide staying. Sharing it guarantees the two can't-// ping-pong (issue -> plan -> issue -> ...).+// For submitted DATABASE_CHANGE issues, the plan specs distinguish schema+// changes from create-database plans. Drafts do not need that fetch: their+// lifecycle and metadata always belong on the linked Plan Detail surface.//// Every issue-detail entry point navigates to this route by name, so this single// guard covers deep links, inbox/notifications, and review CTAs without patching@@ -38,9 +35,21 @@ export async function issueDetailRedirectLoader({name: `${projectNamePrefix}${projectId}/${issueNamePrefix}${issueId}`,}));- // Export and grant issues stay on Issue Detail; skip the plan fetch for them.- // (DATABASE_CHANGE covers both schema-change and create-database.)- if (issue.type !== Issue_Type.DATABASE_CHANGE || !issue.plan) {+ if (!issue.plan) {+ return null;+ }+ // A Draft Review Issue is edited and submitted from Plan Detail regardless+ // of plan spec type. Its plan name is already sufficient, so avoid an+ // unnecessary GetPlan request.+ if (issue.draft) {+ const planId = extractPlanUID(issue.plan);+ if (!planId) return null;+ const { search } = new URL(request.url);+ return redirect(`/projects/${projectId}/plans/${planId}${search}`);+ }+ // Submitted export and grant issues stay on Issue Detail; skip the plan+ // fetch for them. DATABASE_CHANGE remains ambiguous until the plan loads.+ if (issue.type !== Issue_Type.DATABASE_CHANGE) {return null;}// DATABASE_CHANGE is ambiguous (schema-change vs create-database); the plan'sdiff --git a/frontend/src/react/stores/app/issueComment.ts b/frontend/src/react/stores/app/issueComment.tsindex eaad49545f..eeec564307 100644--- a/frontend/src/react/stores/app/issueComment.ts+++ b/frontend/src/react/stores/app/issueComment.ts@@ -19,6 +19,7 @@ export enum IssueCommentType {APPROVAL = "APPROVAL",ISSUE_UPDATE = "ISSUE_UPDATE",PLAN_UPDATE = "PLAN_UPDATE",+ REVIEW_SUBMISSION = "REVIEW_SUBMISSION",}export const getIssueCommentType = (@@ -30,6 +31,8 @@ export const getIssueCommentType = (return IssueCommentType.ISSUE_UPDATE;} else if (issueComment.event?.case === "planUpdate") {return IssueCommentType.PLAN_UPDATE;+ } else if (issueComment.event?.case === "reviewSubmission") {+ return IssueCommentType.REVIEW_SUBMISSION;}return IssueCommentType.USER_COMMENT;};diff --git a/frontend/src/types/proto-es/v1/common_pb.d.ts b/frontend/src/types/proto-es/v1/common_pb.d.tsindex 8897d02cc4..bd21627af1 100644--- a/frontend/src/types/proto-es/v1/common_pb.d.ts+++ b/frontend/src/types/proto-es/v1/common_pb.d.ts@@ -451,7 +451,7 @@ export declare const ExportFormatSchema: GenEnum<ExportFormat>;*/export enum ApprovalStatus {/**- * Unspecified approval status.+ * No approval workflow has started, including for a linked draft issue.** @generated from enum value: APPROVAL_STATUS_UNSPECIFIED = 0;*/diff --git a/frontend/src/types/proto-es/v1/issue_service_pb.d.ts b/frontend/src/types/proto-es/v1/issue_service_pb.d.tsindex d5f6d37b47..c3f6ff0776 100644--- a/frontend/src/types/proto-es/v1/issue_service_pb.d.ts+++ b/frontend/src/types/proto-es/v1/issue_service_pb.d.ts@@ -998,6 +998,14 @@ export declare type IssueComment = Message<"bytebase.v1.IssueComment"> & {*/value: IssueComment_PlanUpdate;case: "planUpdate";+ } | {+ /**+ * Review submission event.+ *+ * @generated from field: bytebase.v1.IssueComment.ReviewSubmission review_submission = 13;+ */+ value: IssueComment_ReviewSubmission;+ case: "reviewSubmission";} | { case: undefined; value?: undefined };};@@ -1120,6 +1128,20 @@ export declare type IssueComment_IssueUpdate = Message<"bytebase.v1.IssueComment*/export declare const IssueComment_IssueUpdateSchema: GenMessage<IssueComment_IssueUpdate>;+/**+ * Review submission event information.+ *+ * @generated from message bytebase.v1.IssueComment.ReviewSubmission+ */+export declare type IssueComment_ReviewSubmission = Message<"bytebase.v1.IssueComment.ReviewSubmission"> & {+};++/**+ * Describes the message bytebase.v1.IssueComment.ReviewSubmission.+ * Use `create(IssueComment_ReviewSubmissionSchema)` to create a new message.+ */+export declare const IssueComment_ReviewSubmissionSchema: GenMessage<IssueComment_ReviewSubmission>;+/*** Plan update event information (snapshot of plan.config.specs before* and after a PlanService.UpdatePlan call that mutated specs).diff --git a/frontend/src/types/proto-es/v1/issue_service_pb.js b/frontend/src/types/proto-es/v1/issue_service_pb.jsindex 2d072e04a9..e6abe1727b 100644--- a/frontend/src/types/proto-es/v1/issue_service_pb.js+++ b/frontend/src/types/proto-es/v1/issue_service_pb.js@@ -18,7 +18,7 @@ import { file_v1_plan_service } from "./plan_service_pb";* Describes the file v1/issue_service.proto.*/export const file_v1_issue_service = /*@__PURE__*/- fileDesc("ChZ2MS9pc3N1ZV9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSJKCg9HZXRJc3N1ZVJlcXVlc3QSKAoEbmFtZRgBIAEoCUIa4EEC+kEUChJieXRlYmFzZS5jb20vSXNzdWUSDQoFZm9yY2UYAiABKAgiagoSQ3JlYXRlSXNzdWVSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBImCgVpc3N1ZRgCIAEoCzISLmJ5dGViYXNlLnYxLklzc3VlQgPgQQIimQEKEUxpc3RJc3N1ZXNSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIRCglwYWdlX3NpemUYAiABKAUSEgoKcGFnZV90b2tlbhgDIAEoCRIOCgZmaWx0ZXIYBCABKAkSDQoFcXVlcnkYBSABKAkSEAoIb3JkZXJfYnkYBiABKAkiUQoSTGlzdElzc3Vlc1Jlc3BvbnNlEiIKBmlzc3VlcxgBIAMoCzISLmJ5dGViYXNlLnYxLklzc3VlEhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSKCAQoTU2VhcmNoSXNzdWVzUmVxdWVzdBITCgZwYXJlbnQYASABKAlCA+BBAhIRCglwYWdlX3NpemUYAiABKAUSEgoKcGFnZV90b2tlbhgDIAEoCRIOCgZmaWx0ZXIYBCABKAkSDQoFcXVlcnkYBSABKAkSEAoIb3JkZXJfYnkYBiABKAkiUwoUU2VhcmNoSXNzdWVzUmVzcG9uc2USIgoGaXNzdWVzGAEgAygLMhIuYnl0ZWJhc2UudjEuSXNzdWUSFwoPbmV4dF9wYWdlX3Rva2VuGAIgASgJIqABChJVcGRhdGVJc3N1ZVJlcXVlc3QSPQoFaXNzdWUYASABKAsyEi5ieXRlYmFzZS52MS5Jc3N1ZUIa4EEC+kEUChJieXRlYmFzZS5jb20vSXNzdWUSNAoLdXBkYXRlX21hc2sYAiABKAsyGi5nb29nbGUucHJvdG9idWYuRmllbGRNYXNrQgPgQQISFQoNYWxsb3dfbWlzc2luZxgDIAEoCCKYAQoeQmF0Y2hVcGRhdGVJc3N1ZXNTdGF0dXNSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIOCgZpc3N1ZXMYAiADKAkSKAoGc3RhdHVzGAMgASgOMhguYnl0ZWJhc2UudjEuSXNzdWVTdGF0dXMSDgoGcmVhc29uGAQgASgJIiEKH0JhdGNoVXBkYXRlSXNzdWVzU3RhdHVzUmVzcG9uc2UiUAoTQXBwcm92ZUlzc3VlUmVxdWVzdBIoCgRuYW1lGAEgASgJQhrgQQL6QRQKEmJ5dGViYXNlLmNvbS9Jc3N1ZRIPCgdjb21tZW50GAIgASgJIk8KElJlamVjdElzc3VlUmVxdWVzdBIoCgRuYW1lGAEgASgJQhrgQQL6QRQKEmJ5dGViYXNlLmNvbS9Jc3N1ZRIPCgdjb21tZW50GAIgASgJIlAKE1JlcXVlc3RJc3N1ZVJlcXVlc3QSKAoEbmFtZRgBIAEoCUIa4EEC+kEUChJieXRlYmFzZS5jb20vSXNzdWUSDwoHY29tbWVudBgCIAEoCSJFChlSZXRyeUlzc3VlQXBwcm92YWxSZXF1ZXN0EigKBG5hbWUYASABKAlCGuBBAvpBFAoSYnl0ZWJhc2UuY29tL0lzc3VlIswHCgVJc3N1ZRIMCgRuYW1lGAEgASgJEhcKBXRpdGxlGAIgASgJQgi6SAVyAxjIARIdCgtkZXNjcmlwdGlvbhgDIAEoCUIIukgFcgMYkE4SJQoEdHlwZRgEIAEoDjIXLmJ5dGViYXNlLnYxLklzc3VlLlR5cGUSKAoGc3RhdHVzGAUgASgOMhguYnl0ZWJhc2UudjEuSXNzdWVTdGF0dXMSLgoJYXBwcm92ZXJzGAYgAygLMhsuYnl0ZWJhc2UudjEuSXNzdWUuQXBwcm92ZXISOAoRYXBwcm92YWxfdGVtcGxhdGUYByABKAsyHS5ieXRlYmFzZS52MS5BcHByb3ZhbFRlbXBsYXRlEhQKB2NyZWF0b3IYCCABKAlCA+BBAxI0CgtjcmVhdGVfdGltZRgJIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBCA+BBAxI0Cgt1cGRhdGVfdGltZRgKIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBCA+BBAxIMCgRwbGFuGAsgASgJEioKCnJvbGVfZ3JhbnQYDSABKAsyFi5ieXRlYmFzZS52MS5Sb2xlR3JhbnQSKgoKcmlza19sZXZlbBgPIAEoDjIWLmJ5dGViYXNlLnYxLlJpc2tMZXZlbBIOCgZsYWJlbHMYESADKAkSOQoPYXBwcm92YWxfc3RhdHVzGBIgASgOMhsuYnl0ZWJhc2UudjEuQXBwcm92YWxTdGF0dXNCA+BBAxI2CgxhY2Nlc3NfZ3JhbnQYEyABKAlCIOBBA/pBGgoYYnl0ZWJhc2UuY29tL0FjY2Vzc0dyYW50EhIKBWRyYWZ0GBQgASgIQgPgQQEanAEKCEFwcHJvdmVyEjIKBnN0YXR1cxgBIAEoDjIiLmJ5dGViYXNlLnYxLklzc3VlLkFwcHJvdmVyLlN0YXR1cxIRCglwcmluY2lwYWwYAiABKAkiSQoGU3RhdHVzEhYKElNUQVRVU19VTlNQRUNJRklFRBAAEgsKB1BFTkRJTkcQARIMCghBUFBST1ZFRBACEgwKCFJFSkVDVEVEEAMiaAoEVHlwZRIUChBUWVBFX1VOU1BFQ0lGSUVEEAASEwoPREFUQUJBU0VfQ0hBTkdFEAESDgoKUk9MRV9HUkFOVBACEhMKD0RBVEFCQVNFX0VYUE9SVBADEhAKDEFDQ0VTU19HUkFOVBAEOjrqQTcKEmJ5dGViYXNlLmNvbS9Jc3N1ZRIhcHJvamVjdHMve3Byb2plY3R9L2lzc3Vlcy97aXNzdWV9InwKCVJvbGVHcmFudBIMCgRyb2xlGAEgASgJEgwKBHVzZXIYAiABKAkSJAoJY29uZGl0aW9uGAMgASgLMhEuZ29vZ2xlLnR5cGUuRXhwchItCgpleHBpcmF0aW9uGAQgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uIl8KEEFwcHJvdmFsVGVtcGxhdGUSJwoEZmxvdxgBIAEoCzIZLmJ5dGViYXNlLnYxLkFwcHJvdmFsRmxvdxINCgV0aXRsZRgCIAEoCRITCgtkZXNjcmlwdGlvbhgDIAEoCSIdCgxBcHByb3ZhbEZsb3cSDQoFcm9sZXMYASADKAkibQoYTGlzdElzc3VlQ29tbWVudHNSZXF1ZXN0EioKBnBhcmVudBgBIAEoCUIa4EEC+kEUChJieXRlYmFzZS5jb20vSXNzdWUSEQoJcGFnZV9zaXplGAIgASgFEhIKCnBhZ2VfdG9rZW4YAyABKAkiZwoZTGlzdElzc3VlQ29tbWVudHNSZXNwb25zZRIxCg5pc3N1ZV9jb21tZW50cxgBIAMoCzIZLmJ5dGViYXNlLnYxLklzc3VlQ29tbWVudBIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAkieQoZQ3JlYXRlSXNzdWVDb21tZW50UmVxdWVzdBIqCgZwYXJlbnQYASABKAlCGuBBAvpBFAoSYnl0ZWJhc2UuY29tL0lzc3VlEjAKDWlzc3VlX2NvbW1lbnQYAiABKAsyGS5ieXRlYmFzZS52MS5Jc3N1ZUNvbW1lbnQixgEKGVVwZGF0ZUlzc3VlQ29tbWVudFJlcXVlc3QSKgoGcGFyZW50GAEgASgJQhrgQQL6QRQKEmJ5dGViYXNlLmNvbS9Jc3N1ZRIwCg1pc3N1ZV9jb21tZW50GAIgASgLMhkuYnl0ZWJhc2UudjEuSXNzdWVDb21tZW50EjQKC3VwZGF0ZV9tYXNrGAMgASgLMhouZ29vZ2xlLnByb3RvYnVmLkZpZWxkTWFza0ID4EECEhUKDWFsbG93X21pc3NpbmcYBCABKAgi6wcKDElzc3VlQ29tbWVudBIMCgRuYW1lGAEgASgJEhoKB2NvbW1lbnQYAiABKAlCCbpIBnIEGICABBIPCgdwYXlsb2FkGAMgASgJEjQKC2NyZWF0ZV90aW1lGAQgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEjQKC3VwZGF0ZV90aW1lGAUgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEhQKB2NyZWF0b3IYBiABKAlCA+BBAxI2CghhcHByb3ZhbBgHIAEoCzIiLmJ5dGViYXNlLnYxLklzc3VlQ29tbWVudC5BcHByb3ZhbEgAEj0KDGlzc3VlX3VwZGF0ZRgIIAEoCzIlLmJ5dGViYXNlLnYxLklzc3VlQ29tbWVudC5Jc3N1ZVVwZGF0ZUgAEjsKC3BsYW5fdXBkYXRlGAwgASgLMiQuYnl0ZWJhc2UudjEuSXNzdWVDb21tZW50LlBsYW5VcGRhdGVIABqQAQoIQXBwcm92YWwSOQoGc3RhdHVzGAEgASgOMikuYnl0ZWJhc2UudjEuSXNzdWVDb21tZW50LkFwcHJvdmFsLlN0YXR1cyJJCgZTdGF0dXMSFgoSU1RBVFVTX1VOU1BFQ0lGSUVEEAASCwoHUEVORElORxABEgwKCEFQUFJPVkVEEAISDAoIUkVKRUNURUQQAxrpAgoLSXNzdWVVcGRhdGUSFwoKZnJvbV90aXRsZRgBIAEoCUgAiAEBEhUKCHRvX3RpdGxlGAIgASgJSAGIAQESHQoQZnJvbV9kZXNjcmlwdGlvbhgDIAEoCUgCiAEBEhsKDnRvX2Rlc2NyaXB0aW9uGAQgASgJSAOIAQESMgoLZnJvbV9zdGF0dXMYBSABKA4yGC5ieXRlYmFzZS52MS5Jc3N1ZVN0YXR1c0gEiAEBEjAKCXRvX3N0YXR1cxgGIAEoDjIYLmJ5dGViYXNlLnYxLklzc3VlU3RhdHVzSAWIAQESEwoLZnJvbV9sYWJlbHMYByADKAkSEQoJdG9fbGFiZWxzGAggAygJQg0KC19mcm9tX3RpdGxlQgsKCV90b190aXRsZUITChFfZnJvbV9kZXNjcmlwdGlvbkIRCg9fdG9fZGVzY3JpcHRpb25CDgoMX2Zyb21fc3RhdHVzQgwKCl90b19zdGF0dXMaYgoKUGxhblVwZGF0ZRIqCgpmcm9tX3NwZWNzGAEgAygLMhYuYnl0ZWJhc2UudjEuUGxhbi5TcGVjEigKCHRvX3NwZWNzGAIgAygLMhYuYnl0ZWJhc2UudjEuUGxhbi5TcGVjQgcKBWV2ZW50Kk0KC0lzc3VlU3RhdHVzEhwKGElTU1VFX1NUQVRVU19VTlNQRUNJRklFRBAAEggKBE9QRU4QARIICgRET05FEAISDAoIQ0FOQ0VMRUQQAzLsEAoMSXNzdWVTZXJ2aWNlEoABCghHZXRJc3N1ZRIcLmJ5dGViYXNlLnYxLkdldElzc3VlUmVxdWVzdBoSLmJ5dGViYXNlLnYxLklzc3VlIkLaQQRuYW1liuowDWJiLmlzc3Vlcy5nZXSQ6jABgtPkkwIgEh4vdjEve25hbWU9cHJvamVjdHMvKi9pc3N1ZXMvKn0SnAEKC0NyZWF0ZUlzc3VlEh8uYnl0ZWJhc2UudjEuQ3JlYXRlSXNzdWVSZXF1ZXN0GhIuYnl0ZWJhc2UudjEuSXNzdWUiWNpBDHBhcmVudCxpc3N1ZYrqMBBiYi5pc3N1ZXMuY3JlYXRlkOowAZjqMAGC0+STAic6BWlzc3VlIh4vdjEve3BhcmVudD1wcm9qZWN0cy8qfS9pc3N1ZXMSlAEKCkxpc3RJc3N1ZXMSHi5ieXRlYmFzZS52MS5MaXN0SXNzdWVzUmVxdWVzdBofLmJ5dGViYXNlLnYxLkxpc3RJc3N1ZXNSZXNwb25zZSJF2kEGcGFyZW50iuowDmJiLmlzc3Vlcy5saXN0kOowAYLT5JMCIBIeL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vaXNzdWVzEpoBCgxTZWFyY2hJc3N1ZXMSIC5ieXRlYmFzZS52MS5TZWFyY2hJc3N1ZXNSZXF1ZXN0GiEuYnl0ZWJhc2UudjEuU2VhcmNoSXNzdWVzUmVzcG9uc2UiRYrqMA1iYi5pc3N1ZXMuZ2V0kOowAoLT5JMCKjoBKiIlL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vaXNzdWVzOnNlYXJjaBKnAQoLVXBkYXRlSXNzdWUSHy5ieXRlYmFzZS52MS5VcGRhdGVJc3N1ZVJlcXVlc3QaEi5ieXRlYmFzZS52MS5Jc3N1ZSJj2kERaXNzdWUsdXBkYXRlX21hc2uK6jAQYmIuaXNzdWVzLnVwZGF0ZZDqMAGY6jABgtPkkwItOgVpc3N1ZTIkL3YxL3tpc3N1ZS5uYW1lPXByb2plY3RzLyovaXNzdWVzLyp9EsABChFMaXN0SXNzdWVDb21tZW50cxIlLmJ5dGViYXNlLnYxLkxpc3RJc3N1ZUNvbW1lbnRzUmVxdWVzdBomLmJ5dGViYXNlLnYxLkxpc3RJc3N1ZUNvbW1lbnRzUmVzcG9uc2UiXNpBBnBhcmVudIrqMBViYi5pc3N1ZUNvbW1lbnRzLmxpc3SQ6jABgtPkkwIwEi4vdjEve3BhcmVudD1wcm9qZWN0cy8qL2lzc3Vlcy8qfS9pc3N1ZUNvbW1lbnRzEtIBChJDcmVhdGVJc3N1ZUNvbW1lbnQSJi5ieXRlYmFzZS52MS5DcmVhdGVJc3N1ZUNvbW1lbnRSZXF1ZXN0GhkuYnl0ZWJhc2UudjEuSXNzdWVDb21tZW50InnaQRRwYXJlbnQsaXNzdWVfY29tbWVudIrqMBdiYi5pc3N1ZUNvbW1lbnRzLmNyZWF0ZZDqMAGY6jABgtPkkwI5Og1pc3N1ZV9jb21tZW50IigvdjEve3BhcmVudD1wcm9qZWN0cy8qL2lzc3Vlcy8qfTpjb21tZW50Et8BChJVcGRhdGVJc3N1ZUNvbW1lbnQSJi5ieXRlYmFzZS52MS5VcGRhdGVJc3N1ZUNvbW1lbnRSZXF1ZXN0GhkuYnl0ZWJhc2UudjEuSXNzdWVDb21tZW50IoUB2kEgcGFyZW50LGlzc3VlX2NvbW1lbnQsdXBkYXRlX21hc2uK6jAXYmIuaXNzdWVDb21tZW50cy51cGRhdGWQ6jABmOowAYLT5JMCOToNaXNzdWVfY29tbWVudDIoL3YxL3twYXJlbnQ9cHJvamVjdHMvKi9pc3N1ZXMvKn06Y29tbWVudBLNAQoXQmF0Y2hVcGRhdGVJc3N1ZXNTdGF0dXMSKy5ieXRlYmFzZS52MS5CYXRjaFVwZGF0ZUlzc3Vlc1N0YXR1c1JlcXVlc3QaLC5ieXRlYmFzZS52MS5CYXRjaFVwZGF0ZUlzc3Vlc1N0YXR1c1Jlc3BvbnNlIleK6jAQYmIuaXNzdWVzLnVwZGF0ZZDqMAGY6jABgtPkkwI1OgEqIjAvdjEve3BhcmVudD1wcm9qZWN0cy8qfS9pc3N1ZXM6YmF0Y2hVcGRhdGVTdGF0dXMSfwoMQXBwcm92ZUlzc3VlEiAuYnl0ZWJhc2UudjEuQXBwcm92ZUlzc3VlUmVxdWVzdBoSLmJ5dGViYXNlLnYxLklzc3VlIjmQ6jACmOowAYLT5JMCKzoBKiImL3YxL3tuYW1lPXByb2plY3RzLyovaXNzdWVzLyp9OmFwcHJvdmUSfAoLUmVqZWN0SXNzdWUSHy5ieXRlYmFzZS52MS5SZWplY3RJc3N1ZVJlcXVlc3QaEi5ieXRlYmFzZS52MS5Jc3N1ZSI4kOowApjqMAGC0+STAio6ASoiJS92MS97bmFtZT1wcm9qZWN0cy8qL2lzc3Vlcy8qfTpyZWplY3QSfwoMUmVxdWVzdElzc3VlEiAuYnl0ZWJhc2UudjEuUmVxdWVzdElzc3VlUmVxdWVzdBoSLmJ5dGViYXNlLnYxLklzc3VlIjmQ6jACmOowAYLT5JMCKzoBKiImL3YxL3tuYW1lPXByb2plY3RzLyovaXNzdWVzLyp9OnJlcXVlc3QSkQEKElJldHJ5SXNzdWVBcHByb3ZhbBImLmJ5dGViYXNlLnYxLlJldHJ5SXNzdWVBcHByb3ZhbFJlcXVlc3QaEi5ieXRlYmFzZS52MS5Jc3N1ZSI/kOowApjqMAGC0+STAjE6ASoiLC92MS97bmFtZT1wcm9qZWN0cy8qL2lzc3Vlcy8qfTpyZXRyeUFwcHJvdmFsQqcBCg9jb20uYnl0ZWJhc2UudjFCEUlzc3VlU2VydmljZVByb3RvUAFaNGdpdGh1Yi5jb20vYnl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [file_buf_validate_validate, file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_field_mask, file_google_protobuf_timestamp, file_google_type_expr, file_v1_annotation, file_v1_common, file_v1_plan_service]);+ fileDesc("ChZ2MS9pc3N1ZV9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSJKCg9HZXRJc3N1ZVJlcXVlc3QSKAoEbmFtZRgBIAEoCUIa4EEC+kEUChJieXRlYmFzZS5jb20vSXNzdWUSDQoFZm9yY2UYAiABKAgiagoSQ3JlYXRlSXNzdWVSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBImCgVpc3N1ZRgCIAEoCzISLmJ5dGViYXNlLnYxLklzc3VlQgPgQQIimQEKEUxpc3RJc3N1ZXNSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIRCglwYWdlX3NpemUYAiABKAUSEgoKcGFnZV90b2tlbhgDIAEoCRIOCgZmaWx0ZXIYBCABKAkSDQoFcXVlcnkYBSABKAkSEAoIb3JkZXJfYnkYBiABKAkiUQoSTGlzdElzc3Vlc1Jlc3BvbnNlEiIKBmlzc3VlcxgBIAMoCzISLmJ5dGViYXNlLnYxLklzc3VlEhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSKCAQoTU2VhcmNoSXNzdWVzUmVxdWVzdBITCgZwYXJlbnQYASABKAlCA+BBAhIRCglwYWdlX3NpemUYAiABKAUSEgoKcGFnZV90b2tlbhgDIAEoCRIOCgZmaWx0ZXIYBCABKAkSDQoFcXVlcnkYBSABKAkSEAoIb3JkZXJfYnkYBiABKAkiUwoUU2VhcmNoSXNzdWVzUmVzcG9uc2USIgoGaXNzdWVzGAEgAygLMhIuYnl0ZWJhc2UudjEuSXNzdWUSFwoPbmV4dF9wYWdlX3Rva2VuGAIgASgJIqABChJVcGRhdGVJc3N1ZVJlcXVlc3QSPQoFaXNzdWUYASABKAsyEi5ieXRlYmFzZS52MS5Jc3N1ZUIa4EEC+kEUChJieXRlYmFzZS5jb20vSXNzdWUSNAoLdXBkYXRlX21hc2sYAiABKAsyGi5nb29nbGUucHJvdG9idWYuRmllbGRNYXNrQgPgQQISFQoNYWxsb3dfbWlzc2luZxgDIAEoCCKYAQoeQmF0Y2hVcGRhdGVJc3N1ZXNTdGF0dXNSZXF1ZXN0EiwKBnBhcmVudBgBIAEoCUIc4EEC+kEWChRieXRlYmFzZS5jb20vUHJvamVjdBIOCgZpc3N1ZXMYAiADKAkSKAoGc3RhdHVzGAMgASgOMhguYnl0ZWJhc2UudjEuSXNzdWVTdGF0dXMSDgoGcmVhc29uGAQgASgJIiEKH0JhdGNoVXBkYXRlSXNzdWVzU3RhdHVzUmVzcG9uc2UiUAoTQXBwcm92ZUlzc3VlUmVxdWVzdBIoCgRuYW1lGAEgASgJQhrgQQL6QRQKEmJ5dGViYXNlLmNvbS9Jc3N1ZRIPCgdjb21tZW50GAIgASgJIk8KElJlamVjdElzc3VlUmVxdWVzdBIoCgRuYW1lGAEgASgJQhrgQQL6QRQKEmJ5dGViYXNlLmNvbS9Jc3N1ZRIPCgdjb21tZW50GAIgASgJIlAKE1JlcXVlc3RJc3N1ZVJlcXVlc3QSKAoEbmFtZRgBIAEoCUIa4EEC+kEUChJieXRlYmFzZS5jb20vSXNzdWUSDwoHY29tbWVudBgCIAEoCSJFChlSZXRyeUlzc3VlQXBwcm92YWxSZXF1ZXN0EigKBG5hbWUYASABKAlCGuBBAvpBFAoSYnl0ZWJhc2UuY29tL0lzc3VlIswHCgVJc3N1ZRIMCgRuYW1lGAEgASgJEhcKBXRpdGxlGAIgASgJQgi6SAVyAxjIARIdCgtkZXNjcmlwdGlvbhgDIAEoCUIIukgFcgMYkE4SJQoEdHlwZRgEIAEoDjIXLmJ5dGViYXNlLnYxLklzc3VlLlR5cGUSKAoGc3RhdHVzGAUgASgOMhguYnl0ZWJhc2UudjEuSXNzdWVTdGF0dXMSLgoJYXBwcm92ZXJzGAYgAygLMhsuYnl0ZWJhc2UudjEuSXNzdWUuQXBwcm92ZXISOAoRYXBwcm92YWxfdGVtcGxhdGUYByABKAsyHS5ieXRlYmFzZS52MS5BcHByb3ZhbFRlbXBsYXRlEhQKB2NyZWF0b3IYCCABKAlCA+BBAxI0CgtjcmVhdGVfdGltZRgJIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBCA+BBAxI0Cgt1cGRhdGVfdGltZRgKIAEoCzIaLmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXBCA+BBAxIMCgRwbGFuGAsgASgJEioKCnJvbGVfZ3JhbnQYDSABKAsyFi5ieXRlYmFzZS52MS5Sb2xlR3JhbnQSKgoKcmlza19sZXZlbBgPIAEoDjIWLmJ5dGViYXNlLnYxLlJpc2tMZXZlbBIOCgZsYWJlbHMYESADKAkSOQoPYXBwcm92YWxfc3RhdHVzGBIgASgOMhsuYnl0ZWJhc2UudjEuQXBwcm92YWxTdGF0dXNCA+BBAxI2CgxhY2Nlc3NfZ3JhbnQYEyABKAlCIOBBA/pBGgoYYnl0ZWJhc2UuY29tL0FjY2Vzc0dyYW50EhIKBWRyYWZ0GBQgASgIQgPgQQEanAEKCEFwcHJvdmVyEjIKBnN0YXR1cxgBIAEoDjIiLmJ5dGViYXNlLnYxLklzc3VlLkFwcHJvdmVyLlN0YXR1cxIRCglwcmluY2lwYWwYAiABKAkiSQoGU3RhdHVzEhYKElNUQVRVU19VTlNQRUNJRklFRBAAEgsKB1BFTkRJTkcQARIMCghBUFBST1ZFRBACEgwKCFJFSkVDVEVEEAMiaAoEVHlwZRIUChBUWVBFX1VOU1BFQ0lGSUVEEAASEwoPREFUQUJBU0VfQ0hBTkdFEAESDgoKUk9MRV9HUkFOVBACEhMKD0RBVEFCQVNFX0VYUE9SVBADEhAKDEFDQ0VTU19HUkFOVBAEOjrqQTcKEmJ5dGViYXNlLmNvbS9Jc3N1ZRIhcHJvamVjdHMve3Byb2plY3R9L2lzc3Vlcy97aXNzdWV9InwKCVJvbGVHcmFudBIMCgRyb2xlGAEgASgJEgwKBHVzZXIYAiABKAkSJAoJY29uZGl0aW9uGAMgASgLMhEuZ29vZ2xlLnR5cGUuRXhwchItCgpleHBpcmF0aW9uGAQgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uIl8KEEFwcHJvdmFsVGVtcGxhdGUSJwoEZmxvdxgBIAEoCzIZLmJ5dGViYXNlLnYxLkFwcHJvdmFsRmxvdxINCgV0aXRsZRgCIAEoCRITCgtkZXNjcmlwdGlvbhgDIAEoCSIdCgxBcHByb3ZhbEZsb3cSDQoFcm9sZXMYASADKAkibQoYTGlzdElzc3VlQ29tbWVudHNSZXF1ZXN0EioKBnBhcmVudBgBIAEoCUIa4EEC+kEUChJieXRlYmFzZS5jb20vSXNzdWUSEQoJcGFnZV9zaXplGAIgASgFEhIKCnBhZ2VfdG9rZW4YAyABKAkiZwoZTGlzdElzc3VlQ29tbWVudHNSZXNwb25zZRIxCg5pc3N1ZV9jb21tZW50cxgBIAMoCzIZLmJ5dGViYXNlLnYxLklzc3VlQ29tbWVudBIXCg9uZXh0X3BhZ2VfdG9rZW4YAiABKAkieQoZQ3JlYXRlSXNzdWVDb21tZW50UmVxdWVzdBIqCgZwYXJlbnQYASABKAlCGuBBAvpBFAoSYnl0ZWJhc2UuY29tL0lzc3VlEjAKDWlzc3VlX2NvbW1lbnQYAiABKAsyGS5ieXRlYmFzZS52MS5Jc3N1ZUNvbW1lbnQixgEKGVVwZGF0ZUlzc3VlQ29tbWVudFJlcXVlc3QSKgoGcGFyZW50GAEgASgJQhrgQQL6QRQKEmJ5dGViYXNlLmNvbS9Jc3N1ZRIwCg1pc3N1ZV9jb21tZW50GAIgASgLMhkuYnl0ZWJhc2UudjEuSXNzdWVDb21tZW50EjQKC3VwZGF0ZV9tYXNrGAMgASgLMhouZ29vZ2xlLnByb3RvYnVmLkZpZWxkTWFza0ID4EECEhUKDWFsbG93X21pc3NpbmcYBCABKAgiyAgKDElzc3VlQ29tbWVudBIMCgRuYW1lGAEgASgJEhoKB2NvbW1lbnQYAiABKAlCCbpIBnIEGICABBIPCgdwYXlsb2FkGAMgASgJEjQKC2NyZWF0ZV90aW1lGAQgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEjQKC3VwZGF0ZV90aW1lGAUgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcEID4EEDEhQKB2NyZWF0b3IYBiABKAlCA+BBAxI2CghhcHByb3ZhbBgHIAEoCzIiLmJ5dGViYXNlLnYxLklzc3VlQ29tbWVudC5BcHByb3ZhbEgAEj0KDGlzc3VlX3VwZGF0ZRgIIAEoCzIlLmJ5dGViYXNlLnYxLklzc3VlQ29tbWVudC5Jc3N1ZVVwZGF0ZUgAEjsKC3BsYW5fdXBkYXRlGAwgASgLMiQuYnl0ZWJhc2UudjEuSXNzdWVDb21tZW50LlBsYW5VcGRhdGVIABJHChFyZXZpZXdfc3VibWlzc2lvbhgNIAEoCzIqLmJ5dGViYXNlLnYxLklzc3VlQ29tbWVudC5SZXZpZXdTdWJtaXNzaW9uSAAakAEKCEFwcHJvdmFsEjkKBnN0YXR1cxgBIAEoDjIpLmJ5dGViYXNlLnYxLklzc3VlQ29tbWVudC5BcHByb3ZhbC5TdGF0dXMiSQoGU3RhdHVzEhYKElNUQVRVU19VTlNQRUNJRklFRBAAEgsKB1BFTkRJTkcQARIMCghBUFBST1ZFRBACEgwKCFJFSkVDVEVEEAMa6QIKC0lzc3VlVXBkYXRlEhcKCmZyb21fdGl0bGUYASABKAlIAIgBARIVCgh0b190aXRsZRgCIAEoCUgBiAEBEh0KEGZyb21fZGVzY3JpcHRpb24YAyABKAlIAogBARIbCg50b19kZXNjcmlwdGlvbhgEIAEoCUgDiAEBEjIKC2Zyb21fc3RhdHVzGAUgASgOMhguYnl0ZWJhc2UudjEuSXNzdWVTdGF0dXNIBIgBARIwCgl0b19zdGF0dXMYBiABKA4yGC5ieXRlYmFzZS52MS5Jc3N1ZVN0YXR1c0gFiAEBEhMKC2Zyb21fbGFiZWxzGAcgAygJEhEKCXRvX2xhYmVscxgIIAMoCUINCgtfZnJvbV90aXRsZUILCglfdG9fdGl0bGVCEwoRX2Zyb21fZGVzY3JpcHRpb25CEQoPX3RvX2Rlc2NyaXB0aW9uQg4KDF9mcm9tX3N0YXR1c0IMCgpfdG9fc3RhdHVzGhIKEFJldmlld1N1Ym1pc3Npb24aYgoKUGxhblVwZGF0ZRIqCgpmcm9tX3NwZWNzGAEgAygLMhYuYnl0ZWJhc2UudjEuUGxhbi5TcGVjEigKCHRvX3NwZWNzGAIgAygLMhYuYnl0ZWJhc2UudjEuUGxhbi5TcGVjQgcKBWV2ZW50Kk0KC0lzc3VlU3RhdHVzEhwKGElTU1VFX1NUQVRVU19VTlNQRUNJRklFRBAAEggKBE9QRU4QARIICgRET05FEAISDAoIQ0FOQ0VMRUQQAzLsEAoMSXNzdWVTZXJ2aWNlEoABCghHZXRJc3N1ZRIcLmJ5dGViYXNlLnYxLkdldElzc3VlUmVxdWVzdBoSLmJ5dGViYXNlLnYxLklzc3VlIkLaQQRuYW1liuowDWJiLmlzc3Vlcy5nZXSQ6jABgtPkkwIgEh4vdjEve25hbWU9cHJvamVjdHMvKi9pc3N1ZXMvKn0SnAEKC0NyZWF0ZUlzc3VlEh8uYnl0ZWJhc2UudjEuQ3JlYXRlSXNzdWVSZXF1ZXN0GhIuYnl0ZWJhc2UudjEuSXNzdWUiWNpBDHBhcmVudCxpc3N1ZYrqMBBiYi5pc3N1ZXMuY3JlYXRlkOowAZjqMAGC0+STAic6BWlzc3VlIh4vdjEve3BhcmVudD1wcm9qZWN0cy8qfS9pc3N1ZXMSlAEKCkxpc3RJc3N1ZXMSHi5ieXRlYmFzZS52MS5MaXN0SXNzdWVzUmVxdWVzdBofLmJ5dGViYXNlLnYxLkxpc3RJc3N1ZXNSZXNwb25zZSJF2kEGcGFyZW50iuowDmJiLmlzc3Vlcy5saXN0kOowAYLT5JMCIBIeL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vaXNzdWVzEpoBCgxTZWFyY2hJc3N1ZXMSIC5ieXRlYmFzZS52MS5TZWFyY2hJc3N1ZXNSZXF1ZXN0GiEuYnl0ZWJhc2UudjEuU2VhcmNoSXNzdWVzUmVzcG9uc2UiRYrqMA1iYi5pc3N1ZXMuZ2V0kOowAoLT5JMCKjoBKiIlL3YxL3twYXJlbnQ9cHJvamVjdHMvKn0vaXNzdWVzOnNlYXJjaBKnAQoLVXBkYXRlSXNzdWUSHy5ieXRlYmFzZS52MS5VcGRhdGVJc3N1ZVJlcXVlc3QaEi5ieXRlYmFzZS52MS5Jc3N1ZSJj2kERaXNzdWUsdXBkYXRlX21hc2uK6jAQYmIuaXNzdWVzLnVwZGF0ZZDqMAGY6jABgtPkkwItOgVpc3N1ZTIkL3YxL3tpc3N1ZS5uYW1lPXByb2plY3RzLyovaXNzdWVzLyp9EsABChFMaXN0SXNzdWVDb21tZW50cxIlLmJ5dGViYXNlLnYxLkxpc3RJc3N1ZUNvbW1lbnRzUmVxdWVzdBomLmJ5dGViYXNlLnYxLkxpc3RJc3N1ZUNvbW1lbnRzUmVzcG9uc2UiXNpBBnBhcmVudIrqMBViYi5pc3N1ZUNvbW1lbnRzLmxpc3SQ6jABgtPkkwIwEi4vdjEve3BhcmVudD1wcm9qZWN0cy8qL2lzc3Vlcy8qfS9pc3N1ZUNvbW1lbnRzEtIBChJDcmVhdGVJc3N1ZUNvbW1lbnQSJi5ieXRlYmFzZS52MS5DcmVhdGVJc3N1ZUNvbW1lbnRSZXF1ZXN0GhkuYnl0ZWJhc2UudjEuSXNzdWVDb21tZW50InnaQRRwYXJlbnQsaXNzdWVfY29tbWVudIrqMBdiYi5pc3N1ZUNvbW1lbnRzLmNyZWF0ZZDqMAGY6jABgtPkkwI5Og1pc3N1ZV9jb21tZW50IigvdjEve3BhcmVudD1wcm9qZWN0cy8qL2lzc3Vlcy8qfTpjb21tZW50Et8BChJVcGRhdGVJc3N1ZUNvbW1lbnQSJi5ieXRlYmFzZS52MS5VcGRhdGVJc3N1ZUNvbW1lbnRSZXF1ZXN0GhkuYnl0ZWJhc2UudjEuSXNzdWVDb21tZW50IoUB2kEgcGFyZW50LGlzc3VlX2NvbW1lbnQsdXBkYXRlX21hc2uK6jAXYmIuaXNzdWVDb21tZW50cy51cGRhdGWQ6jABmOowAYLT5JMCOToNaXNzdWVfY29tbWVudDIoL3YxL3twYXJlbnQ9cHJvamVjdHMvKi9pc3N1ZXMvKn06Y29tbWVudBLNAQoXQmF0Y2hVcGRhdGVJc3N1ZXNTdGF0dXMSKy5ieXRlYmFzZS52MS5CYXRjaFVwZGF0ZUlzc3Vlc1N0YXR1c1JlcXVlc3QaLC5ieXRlYmFzZS52MS5CYXRjaFVwZGF0ZUlzc3Vlc1N0YXR1c1Jlc3BvbnNlIleK6jAQYmIuaXNzdWVzLnVwZGF0ZZDqMAGY6jABgtPkkwI1OgEqIjAvdjEve3BhcmVudD1wcm9qZWN0cy8qfS9pc3N1ZXM6YmF0Y2hVcGRhdGVTdGF0dXMSfwoMQXBwcm92ZUlzc3VlEiAuYnl0ZWJhc2UudjEuQXBwcm92ZUlzc3VlUmVxdWVzdBoSLmJ5dGViYXNlLnYxLklzc3VlIjmQ6jACmOowAYLT5JMCKzoBKiImL3YxL3tuYW1lPXByb2plY3RzLyovaXNzdWVzLyp9OmFwcHJvdmUSfAoLUmVqZWN0SXNzdWUSHy5ieXRlYmFzZS52MS5SZWplY3RJc3N1ZVJlcXVlc3QaEi5ieXRlYmFzZS52MS5Jc3N1ZSI4kOowApjqMAGC0+STAio6ASoiJS92MS97bmFtZT1wcm9qZWN0cy8qL2lzc3Vlcy8qfTpyZWplY3QSfwoMUmVxdWVzdElzc3VlEiAuYnl0ZWJhc2UudjEuUmVxdWVzdElzc3VlUmVxdWVzdBoSLmJ5dGViYXNlLnYxLklzc3VlIjmQ6jACmOowAYLT5JMCKzoBKiImL3YxL3tuYW1lPXByb2plY3RzLyovaXNzdWVzLyp9OnJlcXVlc3QSkQEKElJldHJ5SXNzdWVBcHByb3ZhbBImLmJ5dGViYXNlLnYxLlJldHJ5SXNzdWVBcHByb3ZhbFJlcXVlc3QaEi5ieXRlYmFzZS52MS5Jc3N1ZSI/kOowApjqMAGC0+STAjE6ASoiLC92MS97bmFtZT1wcm9qZWN0cy8qL2lzc3Vlcy8qfTpyZXRyeUFwcHJvdmFsQqcBCg9jb20uYnl0ZWJhc2UudjFCEUlzc3VlU2VydmljZVByb3RvUAFaNGdpdGh1Yi5jb20vYnl0ZWJhc2UvYnl0ZWJhc2UvYmFja2VuZC9nZW5lcmF0ZWQtZ28vdjGiAgNCWFiqAgtCeXRlYmFzZS5WMcoCC0J5dGViYXNlXFYx4gIXQnl0ZWJhc2VcVjFcR1BCTWV0YWRhdGHqAgxCeXRlYmFzZTo6VjFiBnByb3RvMw", [file_buf_validate_validate, file_google_api_annotations, file_google_api_client, file_google_api_field_behavior, file_google_api_resource, file_google_protobuf_duration, file_google_protobuf_field_mask, file_google_protobuf_timestamp, file_google_type_expr, file_v1_annotation, file_v1_common, file_v1_plan_service]);/*** Describes the message bytebase.v1.GetIssueRequest.@@ -237,12 +237,19 @@ export const IssueComment_Approval_Status = /*@__PURE__*/export const IssueComment_IssueUpdateSchema = /*@__PURE__*/messageDesc(file_v1_issue_service, 21, 1);+/**+ * Describes the message bytebase.v1.IssueComment.ReviewSubmission.+ * Use `create(IssueComment_ReviewSubmissionSchema)` to create a new message.+ */+export const IssueComment_ReviewSubmissionSchema = /*@__PURE__*/+ messageDesc(file_v1_issue_service, 21, 2);+/*** Describes the message bytebase.v1.IssueComment.PlanUpdate.* Use `create(IssueComment_PlanUpdateSchema)` to create a new message.*/export const IssueComment_PlanUpdateSchema = /*@__PURE__*/- messageDesc(file_v1_issue_service, 21, 2);+ messageDesc(file_v1_issue_service, 21, 3);/*** Describes the enum bytebase.v1.IssueStatus.diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yamlindex a9522fa805..cbec23bc9c 100644--- a/proto/gen/grpc-doc/openapi.yaml+++ b/proto/gen/grpc-doc/openapi.yaml@@ -21034,6 +21034,15 @@ components:title: plan_updaterequired:- planUpdate+ - type: object+ properties:+ reviewSubmission:+ title: review_submission+ description: Review submission event.+ $ref: '#/components/schemas/bytebase.v1.IssueComment.ReviewSubmission'+ title: review_submission+ required:+ - reviewSubmissiontitle: IssueCommentadditionalProperties: falsedescription: A comment on an issue.@@ -21120,6 +21129,11 @@ components:description: |-Plan update event information (snapshot of plan.config.specs beforeand after a PlanService.UpdatePlan call that mutated specs).+ bytebase.v1.IssueComment.ReviewSubmission:+ type: object+ title: ReviewSubmission+ additionalProperties: false+ description: Review submission event information.bytebase.v1.IssueStatus:type: stringtitle: IssueStatusdiff --git a/proto/gen/grpc-doc/store/README.md b/proto/gen/grpc-doc/store/README.mdindex d29ca3d04b..0b5593d99e 100644--- a/proto/gen/grpc-doc/store/README.md+++ b/proto/gen/grpc-doc/store/README.md@@ -171,6 +171,7 @@- [IssueCommentPayload.Approval](#bytebase-store-IssueCommentPayload-Approval)- [IssueCommentPayload.IssueUpdate](#bytebase-store-IssueCommentPayload-IssueUpdate)- [IssueCommentPayload.PlanUpdate](#bytebase-store-IssueCommentPayload-PlanUpdate)+ - [IssueCommentPayload.ReviewSubmission](#bytebase-store-IssueCommentPayload-ReviewSubmission)- [store/oauth2.proto](#store_oauth2-proto)- [OAuth2AuthorizationCodeConfig](#bytebase-store-OAuth2AuthorizationCodeConfig)@@ -3006,6 +3007,7 @@ Type represents the category of issue.| approval | [IssueCommentPayload.Approval](#bytebase-store-IssueCommentPayload-Approval) | | || issue_update | [IssueCommentPayload.IssueUpdate](#bytebase-store-IssueCommentPayload-IssueUpdate) | | || plan_update | [IssueCommentPayload.PlanUpdate](#bytebase-store-IssueCommentPayload-PlanUpdate) | | |+| review_submission | [IssueCommentPayload.ReviewSubmission](#bytebase-store-IssueCommentPayload-ReviewSubmission) | | |@@ -3067,6 +3069,16 @@ add/remove/update from the snapshot pair.++<a name="bytebase-store-IssueCommentPayload-ReviewSubmission"></a>++### IssueCommentPayload.ReviewSubmission+ReviewSubmission records that an issue entered review.+++++diff --git a/proto/gen/grpc-doc/store/index.html b/proto/gen/grpc-doc/store/index.htmlindex b702396733..5177c9f638 100644--- a/proto/gen/grpc-doc/store/index.html+++ b/proto/gen/grpc-doc/store/index.html@@ -848,6 +848,10 @@<a href="#bytebase.store.IssueCommentPayload.PlanUpdate"><span class="badge">M</span>IssueCommentPayload.PlanUpdate</a></li>+ <li>+ <a href="#bytebase.store.IssueCommentPayload.ReviewSubmission"><span class="badge">M</span>IssueCommentPayload.ReviewSubmission</a>+ </li>+@@ -8968,6 +8972,13 @@ Leave it empty if there is no need to encrypt the zip file. </p></td><td><p> </p></td></tr>+ <tr>+ <td>review_submission</td>+ <td><a href="#bytebase.store.IssueCommentPayload.ReviewSubmission">IssueCommentPayload.ReviewSubmission</a></td>+ <td></td>+ <td><p> </p></td>+ </tr>+</tbody></table>@@ -9103,6 +9114,13 @@ Leave it empty if there is no need to encrypt the zip file. </p></td>+ <h3 id="bytebase.store.IssueCommentPayload.ReviewSubmission">IssueCommentPayload.ReviewSubmission</h3>+ <p>ReviewSubmission records that an issue entered review.</p>+++++diff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.mdindex c967b9517f..6dd1436e7b 100644--- a/proto/gen/grpc-doc/v1/README.md+++ b/proto/gen/grpc-doc/v1/README.md@@ -308,6 +308,7 @@- [IssueComment.Approval](#bytebase-v1-IssueComment-Approval)- [IssueComment.IssueUpdate](#bytebase-v1-IssueComment-IssueUpdate)- [IssueComment.PlanUpdate](#bytebase-v1-IssueComment-PlanUpdate)+ - [IssueComment.ReviewSubmission](#bytebase-v1-IssueComment-ReviewSubmission)- [ListIssueCommentsRequest](#bytebase-v1-ListIssueCommentsRequest)- [ListIssueCommentsResponse](#bytebase-v1-ListIssueCommentsResponse)- [ListIssuesRequest](#bytebase-v1-ListIssuesRequest)@@ -1094,7 +1095,7 @@ can reference it without a circular import.| Name | Number | Description || ---- | ------ | ----------- |-| APPROVAL_STATUS_UNSPECIFIED | 0 | Unspecified approval status. |+| APPROVAL_STATUS_UNSPECIFIED | 0 | No approval workflow has started, including for a linked draft issue. || CHECKING | 1 | Approval checks are being evaluated. || PENDING | 2 | Approval is pending. || APPROVED | 3 | Issue has been approved. |@@ -5660,6 +5661,7 @@ A comment on an issue.| approval | [IssueComment.Approval](#bytebase-v1-IssueComment-Approval) | | Approval event. || issue_update | [IssueComment.IssueUpdate](#bytebase-v1-IssueComment-IssueUpdate) | | Issue update event. || plan_update | [IssueComment.PlanUpdate](#bytebase-v1-IssueComment-PlanUpdate) | | Plan update event. |+| review_submission | [IssueComment.ReviewSubmission](#bytebase-v1-IssueComment-ReviewSubmission) | | Review submission event. |@@ -5720,6 +5722,16 @@ and after a PlanService.UpdatePlan call that mutated specs).+<a name="bytebase-v1-IssueComment-ReviewSubmission"></a>++### IssueComment.ReviewSubmission+Review submission event information.++++++<a name="bytebase-v1-ListIssueCommentsRequest"></a>### ListIssueCommentsRequestdiff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.htmlindex e9fa7a4ded..6b25c2ed9b 100644--- a/proto/gen/grpc-doc/v1/index.html+++ b/proto/gen/grpc-doc/v1/index.html@@ -1361,6 +1361,10 @@<a href="#bytebase.v1.IssueComment.PlanUpdate"><span class="badge">M</span>IssueComment.PlanUpdate</a></li>+ <li>+ <a href="#bytebase.v1.IssueComment.ReviewSubmission"><span class="badge">M</span>IssueComment.ReviewSubmission</a>+ </li>+<li><a href="#bytebase.v1.ListIssueCommentsRequest"><span class="badge">M</span>ListIssueCommentsRequest</a></li>@@ -3903,7 +3907,7 @@ Examples:<tr><td>APPROVAL_STATUS_UNSPECIFIED</td><td>0</td>- <td><p>Unspecified approval status.</p></td>+ <td><p>No approval workflow has started, including for a linked draft issue.</p></td></tr><tr>@@ -16865,6 +16869,13 @@ Format: projects/{project}/accessGrants/{access_grant} </p></td><td><p>Plan update event. </p></td></tr>+ <tr>+ <td>review_submission</td>+ <td><a href="#bytebase.v1.IssueComment.ReviewSubmission">IssueComment.ReviewSubmission</a></td>+ <td></td>+ <td><p>Review submission event. </p></td>+ </tr>+</tbody></table>@@ -17000,6 +17011,13 @@ Format: projects/{project}/accessGrants/{access_grant} </p></td>+ <h3 id="bytebase.v1.IssueComment.ReviewSubmission">IssueComment.ReviewSubmission</h3>+ <p>Review submission event information.</p>+++++<h3 id="bytebase.v1.ListIssueCommentsRequest">ListIssueCommentsRequest</h3><p></p>diff --git a/proto/store/store/issue_comment.proto b/proto/store/store/issue_comment.protoindex ef5dde555e..e23a36ef50 100644--- a/proto/store/store/issue_comment.proto+++ b/proto/store/store/issue_comment.proto@@ -15,6 +15,7 @@ message IssueCommentPayload {Approval approval = 2;IssueUpdate issue_update = 3;PlanUpdate plan_update = 7;+ ReviewSubmission review_submission = 8;}message Approval {@@ -32,6 +33,9 @@ message IssueCommentPayload {repeated string to_labels = 8;}+ // ReviewSubmission records that an issue entered review.+ message ReviewSubmission {}+// PlanUpdate carries before/after snapshots of plan.config.specs,// emitted once per PlanService.UpdatePlan call whose specs branch// produces a non-cosmetic diff. The renderer computes per-specdiff --git a/proto/v1/v1/common.proto b/proto/v1/v1/common.protoindex c1ccb518d3..30dd31c4d8 100644--- a/proto/v1/v1/common.proto+++ b/proto/v1/v1/common.proto@@ -101,7 +101,7 @@ enum ExportFormat {// Lives at the top level so both plan_service.proto and issue_service.proto// can reference it without a circular import.enum ApprovalStatus {- // Unspecified approval status.+ // No approval workflow has started, including for a linked draft issue.APPROVAL_STATUS_UNSPECIFIED = 0;// Approval checks are being evaluated.CHECKING = 1;diff --git a/proto/v1/v1/issue_service.proto b/proto/v1/v1/issue_service.protoindex d1a4006b18..62b4760ae9 100644--- a/proto/v1/v1/issue_service.proto+++ b/proto/v1/v1/issue_service.proto@@ -611,6 +611,8 @@ message IssueComment {IssueUpdate issue_update = 8;// Plan update event.PlanUpdate plan_update = 12;+ // Review submission event.+ ReviewSubmission review_submission = 13;}// Approval event information.@@ -644,6 +646,9 @@ message IssueComment {repeated string to_labels = 8;}+ // Review submission event information.+ message ReviewSubmission {}+// Plan update event information (snapshot of plan.config.specs before// and after a PlanService.UpdatePlan call that mutated specs).message PlanUpdate {