Skip to content

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

fix(BYT-9310): respect project.enforceIssueTitle across issue-creation journeys (#20050)

zchpeter265e784ee497
diff --git a/backend/api/v1/issue_service.go b/backend/api/v1/issue_service.go
index acd3bde840..566f2b039c 100644
--- a/backend/api/v1/issue_service.go
+++ b/backend/api/v1/issue_service.go
@@ -398,6 +398,10 @@ func (s *IssueService) CreateIssue(ctx context.Context, req *connect.Request[v1p
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("require issue labels"))
}
+ // enforceIssueTitle is enforced on CreatePlan (plan.Name is gated there). Issues
+ // with empty Title inherit plan.Name via buildIssueMessage; ROLE_GRANT issues
+ // have their own title-required check below. No gate needed here.
+
user, ok := GetUserFromContext(ctx)
if !ok {
return nil, connect.NewError(connect.CodeInternal, errors.Errorf("user not found"))
@@ -434,7 +438,7 @@ func (s *IssueService) buildIssueMessage(ctx context.Context, project *store.Pro
switch request.Issue.Type {
case v1pb.Issue_ROLE_GRANT:
// Title is required for role grant requests.
- if request.Issue.Title == "" {
+ if strings.TrimSpace(request.Issue.Title) == "" {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("issue title is required"))
}
@@ -481,7 +485,7 @@ func (s *IssueService) buildIssueMessage(ctx context.Context, project *store.Pro
Expiration: request.Issue.RoleGrant.Expiration,
}
- title = request.Issue.Title
+ title = strings.TrimSpace(request.Issue.Title)
description = request.Issue.Description
case v1pb.Issue_DATABASE_CHANGE, v1pb.Issue_DATABASE_EXPORT:
@@ -505,7 +509,7 @@ func (s *IssueService) buildIssueMessage(ctx context.Context, project *store.Pro
planUID = &plan.UID
// Use plan's title and description as defaults if not provided by request
- title = request.Issue.Title
+ title = strings.TrimSpace(request.Issue.Title)
if title == "" {
title = plan.Name
}
@@ -895,11 +899,12 @@ func (s *IssueService) UpdateIssue(ctx context.Context, req *connect.Request[v1p
updateMasks[path] = true
switch path {
case "title":
- if req.Msg.Issue.Title == "" {
+ trimmed := strings.TrimSpace(req.Msg.Issue.Title)
+ if trimmed == "" {
return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("title cannot be empty"))
}
- patch.Title = &req.Msg.Issue.Title
+ patch.Title = &trimmed
issueCommentCreates = append(issueCommentCreates, &store.IssueCommentMessage{
IssueUID: issue.UID,
@@ -907,7 +912,7 @@ func (s *IssueService) UpdateIssue(ctx context.Context, req *connect.Request[v1p
Event: &storepb.IssueCommentPayload_IssueUpdate_{
IssueUpdate: &storepb.IssueCommentPayload_IssueUpdate{
FromTitle: &issue.Title,
- ToTitle: &req.Msg.Issue.Title,
+ ToTitle: &trimmed,
},
},
},
diff --git a/backend/api/v1/plan_service.go b/backend/api/v1/plan_service.go
index f92fa4232a..7402295b96 100644
--- a/backend/api/v1/plan_service.go
+++ b/backend/api/v1/plan_service.go
@@ -4,6 +4,7 @@ import (
"context"
"log/slog"
"slices"
+ "strings"
"connectrpc.com/connect"
"github.com/pkg/errors"
@@ -184,6 +185,11 @@ func (s *PlanService) CreatePlan(ctx context.Context, request *connect.Request[v
return nil, connect.NewError(connect.CodeNotFound, errors.Errorf("project not found for id: %v", projectID))
}
+ trimmedTitle := strings.TrimSpace(req.Plan.Title)
+ if project.Setting.EnforceIssueTitle && trimmedTitle == "" {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("project %q requires a manual plan title (enforce_issue_title is enabled)", req.Parent))
+ }
+
// Validate plan specs
databaseGroup, err := validateSpecs(ctx, s.store, projectID, req.Plan.Specs)
if err != nil {
@@ -192,7 +198,7 @@ func (s *PlanService) CreatePlan(ctx context.Context, request *connect.Request[v
planMessage := &store.PlanMessage{
ProjectID: projectID,
- Name: req.Plan.Title,
+ Name: trimmedTitle,
Description: req.Plan.Description,
Config: convertPlan(req.Plan),
}
@@ -299,7 +305,11 @@ func (s *PlanService) UpdatePlan(ctx context.Context, request *connect.Request[v
for _, path := range req.UpdateMask.Paths {
switch path {
case "title":
- planUpdate.Name = new(req.Plan.Title)
+ trimmed := strings.TrimSpace(req.Plan.Title)
+ if project.Setting.EnforceIssueTitle && trimmed == "" {
+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("project %q requires a manual plan title (enforce_issue_title is enabled)", common.FormatProject(project.ResourceID)))
+ }
+ planUpdate.Name = &trimmed
case "description":
planUpdate.Description = new(req.Plan.Description)
case "state":
diff --git a/frontend/src/components/CreateDatabasePrepForm/CreateDatabasePrepPanel.vue b/frontend/src/components/CreateDatabasePrepForm/CreateDatabasePrepPanel.vue
deleted file mode 100644
index 93dec376be..0000000000
--- a/frontend/src/components/CreateDatabasePrepForm/CreateDatabasePrepPanel.vue
+++ /dev/null
@@ -1,424 +0,0 @@
-<template>
- <DrawerContent
- :title="$t('quick-action.create-db')"
- class="w-[40rem] max-w-[100vw]"
- >
- <div class="mx-auto flex flex-col gap-y-4">
- <div class="w-full">
- <label for="project" class="textlabel">
- {{ $t("common.project") }}
- <RequiredStar />
- </label>
- <ProjectSelect
- class="mt-1 w-full!"
- required
- :disabled="isValidProjectName(currentProject.name)"
- v-model:value="state.projectName"
- />
- </div>
-
- <IssueLabels
- v-if="selectedProject"
- :project="selectedProject"
- v-model:value="state.labels"
- />
-
- <div class="w-full">
- <label for="instance" class="textlabel">
- {{ $t("common.instance") }} <RequiredStar />
- </label>
- <InstanceSelect
- class="mt-1"
- name="instance"
- required
- :disabled="!allowEditInstance"
- :value="state.instanceName"
- :allowed-engine-list="supportedEngines"
- @update:value="selectInstance"
- />
- </div>
-
- <div class="w-full">
- <label for="name" class="textlabel">
- {{ $t("create-db.new-database-name") }}
- <RequiredStar />
- </label>
- <NInput
- v-model:value="state.databaseName"
- required
- name="databaseName"
- type="text"
- class="mt-1 w-full"
- :placeholder="$t('create-db.new-database-name')"
- />
- <span v-if="isReservedName" class="text-red-600">
- <i18n-t keypath="create-db.reserved-db-error">
- <template #databaseName>
- {{ state.databaseName }}
- </template>
- </i18n-t>
- </span>
- </div>
-
- <div v-if="selectedInstance.engine === Engine.MONGODB" class="w-full">
- <label for="name" class="textlabel">
- {{ $t("create-db.new-collection-name") }}
- <RequiredStar />
- </label>
- <NInput
- v-model:value="state.tableName"
- required
- name="tableName"
- type="text"
- class="mt-1 w-full"
- />
- </div>
-
- <div v-if="selectedInstance.engine === Engine.CLICKHOUSE" class="w-full">
- <label for="name" class="textlabel">
- {{ $t("create-db.cluster") }}
- </label>
- <NInput
- v-model:value="state.cluster"
- name="cluster"
- type="text"
- class="mt-1 w-full"
- />
- </div>
-
- <div class="w-full">
- <label for="environment" class="textlabel">
- {{ $t("common.environment") }}
- </label>
- <EnvironmentSelect
- v-model:value="state.environmentName"
- class="mt-1"
- required
- name="environment"
- />
- </div>
-
- <div v-if="requireDatabaseOwnerName && state.instanceName" class="w-full">
- <label for="name" class="textlabel">
- {{ $t("create-db.database-owner-name") }}
- <RequiredStar />
- </label>
- <InstanceRoleSelect
- class="mt-1"
- name="instance-user"
- :instance-name="state.instanceName"
- :role="state.instanceRole?.name"
- :filter="filterInstanceRole"
- @update:instance-role="selectInstanceRole"
- />
- </div>
-
- <template v-if="showCollationAndCharacterSet">
- <div class="w-full">
- <label for="charset" class="textlabel">
- {{
- selectedInstance.engine === Engine.POSTGRES ||
- selectedInstance.engine === Engine.REDSHIFT
- ? $t("db.encoding")
- : $t("db.character-set")
- }}</label
- >
- <NInput
- v-model:value="state.characterSet"
- name="charset"
- type="text"
- class="mt-1 w-full"
- :placeholder="defaultCharsetOfEngineV1(selectedInstance.engine)"
- />
- </div>
-
- <div class="w-full">
- <label for="collation" class="textlabel">
- {{ $t("db.collation") }}
- </label>
- <NInput
- v-model:value="state.collation"
- name="collation"
- type="text"
- class="mt-1 w-full"
- :placeholder="
- defaultCollationOfEngineV1(selectedInstance.engine) || 'default'
- "
- />
- </div>
- </template>
- </div>
-
- <div
- v-if="state.creating"
- class="absolute inset-0 z-10 bg-white/70 flex items-center justify-center"
- >
- <BBSpin />
- </div>
- <template #footer>
- <div class="flex justify-end gap-x-3">
- <NButton quaternary @click.prevent="cancel">
- {{ $t("common.cancel") }}
- </NButton>
- <NButton
- type="primary"
- :disabled="!allowCreate"
- @click.prevent="create"
- >
- {{ $t("common.create") }}
- </NButton>
- </div>
- </template>
- </DrawerContent>
-</template>
-
-<script lang="ts" setup>
-import { create as createProto } from "@bufbuild/protobuf";
-import { isEmpty } from "lodash-es";
-import { NButton, NInput } from "naive-ui";
-import { v4 as uuidv4 } from "uuid";
-import { computed, reactive, watch } from "vue";
-import { useI18n } from "vue-i18n";
-import { useRouter } from "vue-router";
-import { BBSpin } from "@/bbkit";
-import InstanceRoleSelect from "@/components/InstanceRoleSelect.vue";
-import IssueLabels from "@/components/IssueV1/components/Sidebar/IssueLabels.vue";
-import RequiredStar from "@/components/RequiredStar.vue";
-import {
- DrawerContent,
- EnvironmentSelect,
- InstanceSelect,
- ProjectSelect,
-} from "@/components/v2";
-import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
-import {
- experimentalCreateIssueByPlan,
- useCurrentProjectV1,
- useCurrentUserV1,
- useInstanceResourceByName,
- useProjectV1Store,
-} from "@/store";
-import {
- defaultCharsetOfEngineV1,
- defaultCollationOfEngineV1,
- isValidInstanceName,
- isValidProjectName,
-} from "@/types";
-import { Engine } from "@/types/proto-es/v1/common_pb";
-import type { InstanceRole } from "@/types/proto-es/v1/instance_role_service_pb";
-import { Issue_Type, IssueSchema } from "@/types/proto-es/v1/issue_service_pb";
-import type { Plan_CreateDatabaseConfig } from "@/types/proto-es/v1/plan_service_pb";
-import {
- Plan_CreateDatabaseConfigSchema,
- Plan_SpecSchema,
- PlanSchema,
-} from "@/types/proto-es/v1/plan_service_pb";
-import {
- enginesSupportCreateDatabase,
- extractIssueUID,
- extractProjectResourceName,
- instanceV1HasCollationAndCharacterSet,
-} from "@/utils";
-
-const INTERNAL_RDS_INSTANCE_USER_LIST = ["rds_ad", "rdsadmin", "rds_iam"];
-
-interface LocalState {
- projectName?: string;
- environmentName?: string;
- instanceName?: string;
- instanceRole?: InstanceRole;
- databaseName: string;
- tableName: string;
- characterSet: string;
- collation: string;
- cluster: string;
- creating: boolean;
- labels: string[];
-}
-
-const props = defineProps<{
- environmentName?: string;
- instanceName?: string;
-}>();
-
-const emit = defineEmits<{
- (event: "dismiss"): void;
-}>();
-
-const { t } = useI18n();
-const router = useRouter();
-const currentUserV1 = useCurrentUserV1();
-const projectStore = useProjectV1Store();
-const { project: currentProject } = useCurrentProjectV1();
-
-const state = reactive<LocalState>({
- databaseName: "",
- projectName: isValidProjectName(currentProject.value.name)
- ? currentProject.value.name
- : undefined,
- environmentName: props.environmentName,
- instanceName: props.instanceName,
- tableName: "",
- characterSet: "",
- collation: "",
- cluster: "",
- creating: false,
- labels: [],
-});
-
-watch(
- () => state.projectName,
- () => (state.labels = [])
-);
-
-const selectedProject = computed(() => {
- if (!state.projectName) {
- return;
- }
- const project = projectStore.getProjectByName(state.projectName);
- if (!isValidProjectName(project.name)) {
- return;
- }
- return project;
-});
-
-const isReservedName = computed(() => {
- return state.databaseName.toLowerCase() === "bytebase";
-});
-
-const supportedEngines = computed(() => enginesSupportCreateDatabase());
-
-const haveValidIssueLabel = computed(() => {
- if (!selectedProject.value) {
- return false;
- }
- if (!selectedProject.value.forceIssueLabels) {
- return true;
- }
- return state.labels.length > 0;
-});
-
-const allowCreate = computed(() => {
- return (
- haveValidIssueLabel.value &&
- isValidProjectName(state.projectName) &&
- isValidInstanceName(state.instanceName) &&
- !isEmpty(state.databaseName) &&
- validDatabaseOwnerName.value &&
- !isReservedName.value
- );
-});
-
-// If instance has been specified, then we disallow changing it.
-const allowEditInstance = computed(() => !props.instanceName);
-
-const selectedInstance = computed(
- () => useInstanceResourceByName(state.instanceName ?? "").instance.value
-);
-
-const showCollationAndCharacterSet = computed(() =>
- instanceV1HasCollationAndCharacterSet(selectedInstance.value)
-);
-
-const requireDatabaseOwnerName = computed(() => {
- const instance = selectedInstance.value;
- return (
- isValidInstanceName(instance.name) &&
- [Engine.POSTGRES, Engine.REDSHIFT, Engine.COCKROACHDB].includes(
- instance.engine
- )
- );
-});
-
-const validDatabaseOwnerName = computed(
- () => !requireDatabaseOwnerName.value || state.instanceRole !== undefined
-);
-
-const selectInstance = (instanceName: string | undefined) => {
- state.instanceName = instanceName;
- state.environmentName = selectedInstance.value.environment;
-};
-
-const selectInstanceRole = (role?: InstanceRole) => {
- state.instanceRole = role;
-};
-
-const filterInstanceRole = (user: InstanceRole) =>
- !INTERNAL_RDS_INSTANCE_USER_LIST.includes(user.roleName);
-
-const cancel = () => {
- emit("dismiss");
-};
-
-const create = async () => {
- if (!allowCreate.value) {
- return;
- }
-
- const { databaseName, tableName } = state;
- const owner =
- requireDatabaseOwnerName.value && state.instanceRole
- ? state.instanceRole.roleName
- : "";
-
- const createDatabaseConfig: Plan_CreateDatabaseConfig = createProto(
- Plan_CreateDatabaseConfigSchema,
- {
- target: state.instanceName,
- database: databaseName,
- table: tableName,
- environment: state.environmentName,
-
- characterSet:
- state.characterSet ||
- defaultCharsetOfEngineV1(selectedInstance.value.engine),
- collation:
- state.collation ||
- defaultCollationOfEngineV1(selectedInstance.value.engine),
- cluster: state.cluster,
- owner,
- }
- );
- const spec = createProto(Plan_SpecSchema, {
- id: uuidv4(),
- config: {
- case: "createDatabaseConfig",
- value: createDatabaseConfig,
- },
- });
-
- const title = `${t("issue.title.create-database")} '${databaseName}'`;
- state.creating = true;
- try {
- const planCreate = createProto(PlanSchema, {
- title,
- specs: [spec],
- creator: currentUserV1.value.name,
- });
- const issueCreate = createProto(IssueSchema, {
- title,
- type: Issue_Type.DATABASE_CHANGE,
- creator: `users/${currentUserV1.value.email}`,
- labels: state.labels,
- });
- const project = await projectStore.getOrFetchProjectByName(
- state.projectName!
- );
- const { createdIssue } = await experimentalCreateIssueByPlan(
- project,
- issueCreate,
- planCreate,
- { skipRollout: true }
- );
- router.push({
- name: PROJECT_V1_ROUTE_ISSUE_DETAIL,
- params: {
- projectId: extractProjectResourceName(createdIssue.name),
- issueId: extractIssueUID(createdIssue.name),
- },
- });
- } finally {
- state.creating = false;
- }
-};
-</script>
diff --git a/frontend/src/components/CreateDatabasePrepForm/index.ts b/frontend/src/components/CreateDatabasePrepForm/index.ts
deleted file mode 100644
index 023aefe896..0000000000
--- a/frontend/src/components/CreateDatabasePrepForm/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import CreateDatabasePrepPanel from "./CreateDatabasePrepPanel.vue";
-
-export { CreateDatabasePrepPanel };
diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/create/CreateButton.vue b/frontend/src/components/Plan/components/HeaderSection/Actions/create/CreateButton.vue
index 8828da325e..3b9fbca18f 100644
--- a/frontend/src/components/Plan/components/HeaderSection/Actions/create/CreateButton.vue
+++ b/frontend/src/components/Plan/components/HeaderSection/Actions/create/CreateButton.vue
@@ -105,6 +105,7 @@ import {
extractProjectResourceName,
extractSheetUID,
hasProjectPermissionV2,
+ normalizeTitle,
} from "@/utils";
const { t } = useI18n();
@@ -141,7 +142,7 @@ const planCreateErrorList = computed(() => {
if (!hasProjectPermissionV2(project.value, "bb.plans.create")) {
errorList.push(t("common.missing-required-permission"));
}
- if (!plan.value.title.trim()) {
+ if (!normalizeTitle(plan.value.title)) {
errorList.push("Missing plan title");
}
if (plan.value.specs.some((spec) => isSpecEmpty(spec))) {
diff --git a/frontend/src/components/Plan/logic/index.ts b/frontend/src/components/Plan/logic/index.ts
index 323be23831..7f8daf4596 100644
--- a/frontend/src/components/Plan/logic/index.ts
+++ b/frontend/src/components/Plan/logic/index.ts
@@ -12,3 +12,4 @@ export * from "./sidebar";
export * from "./usePlanCheckStatus";
export * from "./usePlanLink";
export * from "./rolloutPreview";
+export * from "./title";
diff --git a/frontend/src/components/Plan/logic/issue.ts b/frontend/src/components/Plan/logic/issue.ts
index 418774047a..6ca960b51b 100644
--- a/frontend/src/components/Plan/logic/issue.ts
+++ b/frontend/src/components/Plan/logic/issue.ts
@@ -1,4 +1,3 @@
-import type { LocationQueryRaw } from "vue-router";
import { router } from "@/router";
import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";
import {
@@ -13,6 +12,7 @@ import {
extractProjectResourceName,
generatePlanTitle,
} from "@/utils";
+import { applyPlanTitleToQuery } from "./title";
export const preCreateIssue = async (project: string, targets: string[]) => {
const type = "bb.plan.change-database";
@@ -39,31 +39,24 @@ export const preCreateIssue = async (project: string, targets: string[]) => {
const projectEntity = await projectStore.getOrFetchProjectByName(project);
// Navigate to plan detail page
- const query: LocationQueryRaw = {
+ const query: Record<string, string> = {
template: type,
};
if (isDatabaseGroup) {
const databaseGroupName = targets[0];
query.databaseGroupName = databaseGroupName;
- // Only set title from generated if enforceIssueTitle is false.
- if (!projectEntity.enforceIssueTitle) {
- query.name = generatePlanTitle(type, [
- extractDatabaseGroupName(databaseGroupName),
- ]);
- }
+ applyPlanTitleToQuery(query, projectEntity, () =>
+ generatePlanTitle(type, [extractDatabaseGroupName(databaseGroupName)])
+ );
} else {
query.databaseList = targets.join(",");
- // Only set title from generated if enforceIssueTitle is false.
- if (!projectEntity.enforceIssueTitle) {
- query.name = generatePlanTitle(
+ applyPlanTitleToQuery(query, projectEntity, () =>
+ generatePlanTitle(
type,
- targets.map((db) => {
- const { databaseName } = extractDatabaseResourceName(db);
- return databaseName;
- })
- );
- }
+ targets.map((db) => extractDatabaseResourceName(db).databaseName)
+ )
+ );
}
router.push({
diff --git a/frontend/src/components/Plan/logic/title.test.ts b/frontend/src/components/Plan/logic/title.test.ts
new file mode 100644
index 0000000000..cab61594cc
--- /dev/null
+++ b/frontend/src/components/Plan/logic/title.test.ts
@@ -0,0 +1,91 @@
+import { describe, expect, it, vi } from "vitest";
+import { applyPlanTitleToQuery, planQueryNameForProject } from "./title";
+
+describe("planQueryNameForProject", () => {
+ it("returns undefined when the project enforces manual title", () => {
+ const result = planQueryNameForProject(
+ { enforceIssueTitle: true },
+ () => "Auto Title"
+ );
+ expect(result).toBeUndefined();
+ });
+
+ it("returns the generated title when the project does not enforce manual title", () => {
+ const result = planQueryNameForProject(
+ { enforceIssueTitle: false },
+ () => "Auto Title"
+ );
+ expect(result).toBe("Auto Title");
+ });
+
+ it("does not invoke the generator when manual title is enforced", () => {
+ const generate = vi.fn(() => "Auto Title");
+ planQueryNameForProject({ enforceIssueTitle: true }, generate);
+ expect(generate).not.toHaveBeenCalled();
+ });
+
+ it("invokes the generator exactly once when manual title is not enforced", () => {
+ const generate = vi.fn(() => "Auto Title");
+ planQueryNameForProject({ enforceIssueTitle: false }, generate);
+ expect(generate).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("applyPlanTitleToQuery", () => {
+ it("does not set query.name when the project enforces manual title", () => {
+ const query: Record<string, string> = {
+ template: "bb.plan.change-database",
+ };
+ applyPlanTitleToQuery(
+ query,
+ { enforceIssueTitle: true },
+ () => "Auto Title"
+ );
+ expect(query).toEqual({ template: "bb.plan.change-database" });
+ expect(query.name).toBeUndefined();
+ });
+
+ it("sets query.name to the generator output when manual title is not enforced", () => {
+ const query: Record<string, string> = {};
+ applyPlanTitleToQuery(
+ query,
+ { enforceIssueTitle: false },
+ () => "Auto Title"
+ );
+ expect(query.name).toBe("Auto Title");
+ });
+
+ it("does not invoke the generator when manual title is enforced", () => {
+ const generate = vi.fn(() => "Auto Title");
+ const query: Record<string, string> = {};
+ applyPlanTitleToQuery(query, { enforceIssueTitle: true }, generate);
+ expect(generate).not.toHaveBeenCalled();
+ });
+
+ it("preserves pre-existing keys on the query", () => {
+ const query: Record<string, string> = {
+ template: "bb.plan.change-database",
+ databaseList: "db1,db2",
+ };
+ applyPlanTitleToQuery(
+ query,
+ { enforceIssueTitle: false },
+ () => "Auto Title"
+ );
+ expect(query).toEqual({
+ template: "bb.plan.change-database",
+ databaseList: "db1,db2",
+ name: "Auto Title",
+ });
+ });
+
+ it("clears a pre-existing query.name when enforceIssueTitle is true", () => {
+ const query: Record<string, string> = {
+ template: "bb.plan.change-database",
+ name: "stale auto title",
+ };
+ applyPlanTitleToQuery(query, { enforceIssueTitle: true }, () => "fresh");
+ expect(query.name).toBeUndefined();
+ expect(query.template).toBe("bb.plan.change-database"); // untouched
+ });
+});
diff --git a/frontend/src/components/Plan/logic/title.ts b/frontend/src/components/Plan/logic/title.ts
new file mode 100644
index 0000000000..3e43d49ec6
--- /dev/null
+++ b/frontend/src/components/Plan/logic/title.ts
@@ -0,0 +1,48 @@
+import type { Project } from "@/types/proto-es/v1/project_service_pb";
+
+/**
+ * Governance gate for auto-generated plan/issue titles.
+ *
+ * Returns the auto-generated title for the plan-create route's `query.name`,
+ * or `undefined` when the project has `enforceIssueTitle=true` ("Require manual
+ * title"). Leaving `query.name` undefined forces the plan-create page to open
+ * with an empty title; `CreateButton.vue` then blocks submit until the user
+ * types a deliberate title that will appear in the audit log.
+ *
+ * DO NOT inline this gate away. It is the load-bearing check that makes an
+ * audited project's setting mean what it says. Removing it silently reintroduces
+ * auto-generated titles in the audit trail.
+ *
+ * The generator is invoked lazily so callers that build the auto-title via
+ * store lookups or string formatting don't pay that cost when the gate returns.
+ */
+export const planQueryNameForProject = (
+ project: Pick<Project, "enforceIssueTitle">,
+ generate: () => string
+): string | undefined => (project.enforceIssueTitle ? undefined : generate());
+
+/**
+ * Writes the auto-generated plan title into `query.name` unless the project
+ * enforces manual titles. When `enforceIssueTitle` is true, leaves `query.name`
+ * unset so the plan-create page opens with an empty title — the user must type
+ * a deliberate title before `CreateButton.vue` allows submit.
+ *
+ * If `query.name` is already set by the caller, this helper clears it when
+ * enforcement is on, to prevent a stale pre-fill from reaching an enforced
+ * project.
+ *
+ * Use this at every plan-route launcher. It centralizes the governance contract
+ * in one callable so there's exactly one place to audit.
+ */
+export const applyPlanTitleToQuery = (
+ query: Record<string, string>,
+ project: Pick<Project, "enforceIssueTitle">,
+ generate: () => string
+): void => {
+ const name = planQueryNameForProject(project, generate);
+ if (name === undefined) {
+ delete query.name;
+ } else {
+ query.name = name;
+ }
+};
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 0e9210b710..425f4d86ae 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1286,7 +1286,8 @@
},
"title": {
"change-database": "Change database",
- "create-database": "Create database",
+ "change-from-sql-editor": "Change from SQL Editor",
+ "edit-schema": "Edit schema",
"export-data": "Export data",
"request-role": "Request role",
"request-specific-role": "Request \"{role}\" role"
@@ -2604,6 +2605,7 @@
"next-row": "Next Row",
"no-access-requests": "No access requests",
"no-data-available": "No data available",
+ "no-database-selected": "No database selected",
"no-history-found": "No history found",
"no-project": {
"contact-the-admin-to-grant-access": "Contact to the admin to grant access.",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 41484b0c20..bfd88558cf 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1286,7 +1286,8 @@
},
"title": {
"change-database": "Modificar base de datos",
- "create-database": "Crear base de datos",
+ "change-from-sql-editor": "Modificar desde el editor SQL",
+ "edit-schema": "Editar esquema",
"export-data": "Exportar datos",
"request-role": "Rol de solicitud",
"request-specific-role": "Solicitar rol \"{role}\""
@@ -2604,6 +2605,7 @@
"next-row": "siguiente fila",
"no-access-requests": "No access requests",
"no-data-available": "No hay datos disponibles",
+ "no-database-selected": "No se ha seleccionado una base de datos",
"no-history-found": "No se encontró historial",
"no-project": {
"contact-the-admin-to-grant-access": "Póngase en contacto con el administrador para otorgar acceso.",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index ed9c4754ad..ee894b0846 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -1286,7 +1286,8 @@
},
"title": {
"change-database": "データベースの変更",
- "create-database": "データベースを作成する",
+ "change-from-sql-editor": "SQL エディタからの変更",
+ "edit-schema": "スキーマを編集",
"export-data": "データをエクスポート",
"request-role": "ロールをリクエスト",
"request-specific-role": "「{role}」ロールをリクエスト"
@@ -2604,6 +2605,7 @@
"next-row": "次の行",
"no-access-requests": "No access requests",
"no-data-available": "データなし",
+ "no-database-selected": "データベースが選択されていません",
"no-history-found": "まだ履歴がありません",
"no-project": {
"contact-the-admin-to-grant-access": "管理者に連絡してアクセスを許可してください。",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 449d480e21..bde8ac462a 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -1286,7 +1286,8 @@
},
"title": {
"change-database": "Thay đổi cơ sở dữ liệu",
- "create-database": "Tạo cơ sở dữ liệu",
+ "change-from-sql-editor": "Thay đổi từ SQL Editor",
+ "edit-schema": "Chỉnh sửa schema",
"export-data": "Xuất dữ liệu",
"request-role": "Yêu cầu vai trò",
"request-specific-role": "Yêu cầu vai trò \"{role}\""
@@ -2604,6 +2605,7 @@
"next-row": "Dòng tiếp theo",
"no-access-requests": "No access requests",
"no-data-available": "Không có dữ liệu",
+ "no-database-selected": "Chưa chọn cơ sở dữ liệu",
"no-history-found": "Không tìm thấy lịch sử",
"no-project": {
"contact-the-admin-to-grant-access": "Liên hệ với quản trị viên để cấp quyền truy cập.",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 97c2b0eeb7..fdc1dfe2cb 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1286,7 +1286,8 @@
},
"title": {
"change-database": "变更数据库",
- "create-database": "创建数据库",
+ "change-from-sql-editor": "从 SQL 编辑器变更",
+ "edit-schema": "编辑 Schema",
"export-data": "导出数据",
"request-role": "请求角色",
"request-specific-role": "请求“{role}”角色"
@@ -2604,6 +2605,7 @@
"next-row": "下一行",
"no-access-requests": "暂无访问请求",
"no-data-available": "暂无数据",
+ "no-database-selected": "未选择数据库",
"no-history-found": "暂无历史记录",
"no-project": {
"contact-the-admin-to-grant-access": "联系管理员以授予访问权限。",
diff --git a/frontend/src/react/components/EnvironmentMultiSelect.tsx b/frontend/src/react/components/EnvironmentMultiSelect.tsx
new file mode 100644
index 0000000000..353d5606a5
--- /dev/null
+++ b/frontend/src/react/components/EnvironmentMultiSelect.tsx
@@ -0,0 +1,119 @@
+import { Check, ChevronDown, X } from "lucide-react";
+import { useCallback, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";
+import { useClickOutside } from "@/react/hooks/useClickOutside";
+import { useVueState } from "@/react/hooks/useVueState";
+import { cn } from "@/react/lib/utils";
+import { useEnvironmentV1Store } from "@/store";
+
+export function EnvironmentMultiSelect({
+ value,
+ onChange,
+}: Readonly<{
+ value: string[];
+ onChange: (envs: string[]) => void;
+}>) {
+ const { t } = useTranslation();
+ const environmentStore = useEnvironmentV1Store();
+ const environmentList = useVueState(
+ () => environmentStore.environmentList ?? []
+ );
+ const [open, setOpen] = useState(false);
+ const containerRef = useRef<HTMLDivElement>(null);
+
+ const handleClickOutside = useCallback(() => setOpen(false), []);
+ useClickOutside(containerRef, open, handleClickOutside);
+
+ const toggle = (name: string) => {
+ onChange(
+ value.includes(name) ? value.filter((v) => v !== name) : [...value, name]
+ );
+ };
+
+ const remove = (name: string) => {
+ onChange(value.filter((v) => v !== name));
+ };
+
+ // Use native <button> elements for the trigger and option rows so they
+ // get keyboard (Enter/Space) and focus semantics for free — SonarCloud's
+ // S6848 / S1082 a11y rules require interactive content to be native.
+ // The selected-chip X buttons are rendered as siblings of the trigger
+ // (not children) to avoid nested <button>, which is invalid HTML.
+ return (
+ <div ref={containerRef} className="relative">
+ <div
+ className={cn(
+ "flex items-center flex-wrap gap-1 min-h-[2.25rem] w-full rounded-xs border border-control-border bg-transparent px-2 py-1 text-sm",
+ open && "border-accent"
+ )}
+ >
+ {value.length === 0 && (
+ <span className="text-control-placeholder">
+ {t("environment.select")}
+ </span>
+ )}
+ {value.map((name) => (
+ <span
+ key={name}
+ className="inline-flex items-center gap-x-1 rounded-xs border border-control-border px-1 py-0.5 text-xs"
+ >
+ <EnvironmentLabel environmentName={name} className="text-xs" />
+ <button
+ type="button"
+ className="text-control-light hover:text-control"
+ onClick={() => remove(name)}
+ aria-label={t("common.delete")}
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </span>
+ ))}
+ <button
+ type="button"
+ className="ml-auto flex items-center text-control-light cursor-pointer"
+ onClick={() => setOpen(!open)}
+ aria-haspopup="listbox"
+ aria-expanded={open}
+ aria-label={t("environment.select")}
+ >
+ <ChevronDown className="h-4 w-4 shrink-0" />
+ </button>
+ </div>
+
+ {open && (
+ <div className="absolute z-50 mt-1 w-full bg-background border border-control-border rounded-sm shadow-lg max-h-60 overflow-auto">
+ {environmentList.length === 0 && (
+ <div className="px-3 py-2 text-sm text-control-light">
+ {t("common.no-data")}
+ </div>
+ )}
+ {environmentList.map((env) => {
+ const selected = value.includes(env.name);
+ return (
+ <button
+ key={env.name}
+ type="button"
+ className="flex items-center gap-x-2 px-3 py-1.5 text-sm hover:bg-control-bg cursor-pointer w-full text-left"
+ onClick={() => toggle(env.name)}
+ aria-pressed={selected}
+ >
+ <div
+ className={cn(
+ "size-4 rounded-xs border flex items-center justify-center shrink-0",
+ selected
+ ? "bg-accent border-accent text-accent-text"
+ : "border-control-border"
+ )}
+ >
+ {selected && <Check className="h-3 w-3" />}
+ </div>
+ <EnvironmentLabel environment={env} />
+ </button>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/database/CreateDatabaseSheet.test.tsx b/frontend/src/react/components/database/CreateDatabaseSheet.test.tsx
new file mode 100644
index 0000000000..e96df9961c
--- /dev/null
+++ b/frontend/src/react/components/database/CreateDatabaseSheet.test.tsx
@@ -0,0 +1,477 @@
+import type {
+ ButtonHTMLAttributes,
+ InputHTMLAttributes,
+ ReactNode,
+} from "react";
+import { act, createElement } 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";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+vi.mock("@/react/components/InstanceSelect", () => ({
+ InstanceSelect: (props: {
+ onChange: (name: string, instance: unknown) => void;
+ value: string;
+ }) =>
+ createElement("input", {
+ "data-testid": "instance-select",
+ value: props.value,
+ onChange: (e: React.ChangeEvent<HTMLInputElement>) =>
+ props.onChange(e.target.value, undefined),
+ }),
+}));
+
+vi.mock("@/react/components/EnvironmentLabel", () => ({
+ EnvironmentLabel: () => null,
+}));
+
+vi.mock("@/react/components/ui/sheet", () => ({
+ Sheet: ({ children, open }: { children: ReactNode; open: boolean }) =>
+ open ? createElement("div", { "data-testid": "sheet" }, children) : null,
+ SheetContent: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ SheetHeader: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ SheetTitle: ({ children }: { children: ReactNode }) =>
+ createElement("h2", {}, children),
+ SheetBody: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ SheetFooter: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+}));
+
+vi.mock("@/react/components/ui/button", () => ({
+ Button: ({
+ children,
+ disabled,
+ onClick,
+ variant: _v,
+ }: ButtonHTMLAttributes<HTMLButtonElement> & { variant?: string }) =>
+ createElement("button", { disabled, onClick }, children),
+}));
+
+vi.mock("@/react/components/ui/input", () => ({
+ Input: ({ className: _c, ...props }: InputHTMLAttributes<HTMLInputElement>) =>
+ createElement("input", props),
+}));
+
+vi.mock("@/react/components/ui/combobox", () => ({
+ Combobox: ({
+ value,
+ onChange,
+ placeholder,
+ }: {
+ value: string;
+ onChange: (v: string) => void;
+ placeholder?: string;
+ noResultsText?: string;
+ options?: unknown[];
+ onSearch?: (q: string) => void;
+ renderValue?: (opt: unknown) => ReactNode;
+ }) =>
+ createElement("input", {
+ "data-testid": "combobox",
+ value,
+ placeholder,
+ onChange: (e: React.ChangeEvent<HTMLInputElement>) =>
+ onChange(e.target.value),
+ }),
+}));
+
+vi.mock("@/react/hooks/useClickOutside", () => ({
+ useClickOutside: () => undefined,
+}));
+
+vi.mock("@/react/lib/utils", () => ({
+ cn: (...cls: (string | false | null | undefined)[]) =>
+ cls.filter(Boolean).join(" "),
+}));
+
+vi.mock("@bufbuild/protobuf", () => ({
+ create: (_schema: unknown, init?: Record<string, unknown>) => ({ ...init }),
+}));
+
+vi.mock("@/types/proto-es/v1/plan_service_pb", () => ({
+ Plan_CreateDatabaseConfigSchema: {},
+ Plan_SpecSchema: {},
+ PlanSchema: {},
+}));
+
+vi.mock("@/types/proto-es/v1/issue_service_pb", () => ({
+ Issue_Type: { DATABASE_CHANGE: 1 },
+ IssueSchema: {},
+}));
+
+const mocks = vi.hoisted(() => ({
+ getOrFetchProjectByName: vi.fn(),
+ getProjectByName: vi.fn(),
+ getOrFetchInstanceByName: vi.fn(),
+ experimentalCreateIssueByPlan: vi.fn(),
+ currentUser: { name: "users/[email protected]", email: "[email protected]" },
+}));
+
+// Stable store singletons — returning a new object on every render causes the
+// useEffect([..., projectStore]) dependency to fire on every render, creating
+// an infinite update loop that exhausts the V8 heap.
+const stableProjectStore = {
+ get getOrFetchProjectByName() {
+ return mocks.getOrFetchProjectByName;
+ },
+ get getProjectByName() {
+ return mocks.getProjectByName;
+ },
+ fetchProjectList: vi.fn().mockResolvedValue({ projects: [] }),
+};
+const stableInstanceStore = {
+ get getOrFetchInstanceByName() {
+ return mocks.getOrFetchInstanceByName;
+ },
+};
+
+vi.mock("@/store", () => ({
+ useProjectV1Store: () => stableProjectStore,
+ useInstanceV1Store: () => stableInstanceStore,
+ useEnvironmentV1Store: () => ({ environmentList: [] }),
+ useCurrentUserV1: () => ({ value: mocks.currentUser }),
+ experimentalCreateIssueByPlan: mocks.experimentalCreateIssueByPlan,
+ pushNotification: vi.fn(),
+}));
+
+vi.mock("@/react/hooks/useVueState", () => ({
+ useVueState: (getter: () => unknown) => getter(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/router", () => ({ router: { push: vi.fn() } }));
+
+vi.mock("@/types", () => ({
+ isValidProjectName: (name: string) =>
+ typeof name === "string" && name.startsWith("projects/"),
+ isValidInstanceName: (name: string) =>
+ typeof name === "string" && name.startsWith("instances/"),
+ defaultCharsetOfEngineV1: () => "utf8",
+ defaultCollationOfEngineV1: () => "utf8_general_ci",
+}));
+
+vi.mock("@/utils", () => ({
+ enginesSupportCreateDatabase: () => [],
+ getDefaultPagination: () => 20,
+ getIssueRoute: vi.fn(() => "/issues/1"),
+ instanceV1HasCollationAndCharacterSet: () => false,
+ normalizeTitle: (s: string) => s.trim(),
+}));
+
+import { nativeChange } from "@/react/test-utils/nativeChange";
+import { CreateDatabaseSheet } from "./CreateDatabaseSheet";
+
+const TEST_INSTANCE = {
+ name: "instances/test-instance",
+ engine: Engine.MYSQL,
+ environment: "environments/dev",
+};
+
+let container: HTMLDivElement;
+let root: ReturnType<typeof createRoot>;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ document.body.removeChild(container);
+});
+
+function setupProjectMock(enforceIssueTitle: boolean) {
+ mocks.getProjectByName.mockReturnValue({
+ enforceIssueTitle,
+ issueLabels: [],
+ forceIssueLabels: false,
+ });
+ mocks.getOrFetchProjectByName.mockResolvedValue({
+ enforceIssueTitle,
+ issueLabels: [],
+ forceIssueLabels: false,
+ });
+ mocks.getOrFetchInstanceByName.mockResolvedValue(TEST_INSTANCE);
+}
+
+async function renderSheet(enforceIssueTitle: boolean): Promise<void> {
+ setupProjectMock(enforceIssueTitle);
+ await act(async () => {
+ root.render(
+ createElement(CreateDatabaseSheet, {
+ open: true,
+ onClose: () => {},
+ projectName: "projects/foo",
+ })
+ );
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+}
+
+async function fillInstance(): Promise<void> {
+ const input = container.querySelector(
+ "[data-testid='instance-select']"
+ ) as HTMLInputElement;
+ await act(async () => {
+ nativeChange(input, TEST_INSTANCE.name);
+ });
+}
+
+async function fillDatabaseName(name: string): Promise<void> {
+ const input = container.querySelector(
+ "input[placeholder='create-db.new-database-name']"
+ ) as HTMLInputElement;
+ await act(async () => {
+ nativeChange(input, name);
+ });
+}
+
+function getTitleInput(): HTMLInputElement {
+ return container.querySelector(
+ "input[placeholder='common.title']"
+ ) as HTMLInputElement;
+}
+
+function getCreateButton(): HTMLButtonElement {
+ return [...container.querySelectorAll("button")].find((b) =>
+ b.textContent?.includes("common.create")
+ ) as HTMLButtonElement;
+}
+
+async function flush(): Promise<void> {
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+}
+
+describe("CreateDatabaseSheet — enforceIssueTitle (BYT-9310)", () => {
+ it("auto-fills title from database name when enforceIssueTitle is false", async () => {
+ await renderSheet(false);
+ await fillInstance();
+ await fillDatabaseName("widgets");
+ await flush();
+
+ const titleInput = getTitleInput();
+ expect(titleInput).toBeTruthy();
+ expect(titleInput.value).toBe("quick-action.create-db 'widgets'");
+ });
+
+ it("does not auto-fill title when enforceIssueTitle is true", async () => {
+ await renderSheet(true);
+ await fillInstance();
+ await fillDatabaseName("widgets");
+ await flush();
+
+ const titleInput = getTitleInput();
+ expect(titleInput).toBeTruthy();
+ expect(titleInput.value).toBe("");
+ });
+
+ it("resumes auto-fill after the user clears a manually-typed title then retypes the database name (BYT-9310 titleEdited invariant)", async () => {
+ // Design-cell lock: titleEdited must follow the invariant
+ // title === "" ⇒ titleEdited === false
+ // so a stale titleEdited=true doesn't freeze the guard after the user
+ // clears their manual title. User scenario:
+ // 1. type title, 2. type dbName (preserved), 3. clear title,
+ // 4. clear dbName, 5. retype dbName → auto-fill should track
+ // each keystroke, not stick at the first character.
+ await renderSheet(false);
+ await fillInstance();
+ await fillDatabaseName("widgets");
+ await flush();
+ expect(getTitleInput().value).toBe("quick-action.create-db 'widgets'");
+
+ // Step 1: type a custom title.
+ await act(async () => {
+ nativeChange(getTitleInput(), "my title");
+ });
+ // Step 2: dbName preserved across manual title.
+ await fillDatabaseName("cogs");
+ await flush();
+ expect(getTitleInput().value).toBe("my title");
+
+ // Step 3: clear title manually (invariant reset).
+ await act(async () => {
+ nativeChange(getTitleInput(), "");
+ });
+ // Step 4: clear dbName.
+ await fillDatabaseName("");
+ await flush();
+
+ // Step 5: retype dbName and verify each keystroke tracks.
+ await fillDatabaseName("f");
+ await flush();
+ expect(getTitleInput().value).toBe("quick-action.create-db 'f'");
+ await fillDatabaseName("fo");
+ await flush();
+ expect(getTitleInput().value).toBe("quick-action.create-db 'fo'");
+ await fillDatabaseName("foo");
+ await flush();
+ expect(getTitleInput().value).toBe("quick-action.create-db 'foo'");
+ });
+
+ it("clears the auto-filled title when the database name is cleared (BYT-9310 stale-ghost fix)", async () => {
+ // Design-cell lock: the auto-fill effect must handle the empty-
+ // databaseName transition by clearing the title, not by early-
+ // returning and leaving a stale `Create database 'T'` ghost from
+ // the last non-empty keystroke.
+ await renderSheet(false);
+ await fillInstance();
+ await fillDatabaseName("widgets");
+ await flush();
+ expect(getTitleInput().value).toBe("quick-action.create-db 'widgets'");
+
+ // Clear the database name.
+ await fillDatabaseName("");
+ await flush();
+
+ expect(getTitleInput().value).toBe("");
+ });
+
+ it("preserves a user-typed title across database-name changes", async () => {
+ await renderSheet(false);
+ await fillInstance();
+ await fillDatabaseName("widgets");
+ await flush();
+
+ expect(getTitleInput().value).toBe("quick-action.create-db 'widgets'");
+
+ await act(async () => {
+ nativeChange(getTitleInput(), "my custom title");
+ });
+
+ await fillDatabaseName("cogs");
+ await flush();
+
+ expect(getTitleInput().value).toBe("my custom title");
+ });
+
+ it("disables Create when enforceIssueTitle is true and title is empty, enables when typed", async () => {
+ await renderSheet(true);
+ await fillInstance();
+ await fillDatabaseName("widgets");
+ await flush();
+
+ expect(getCreateButton().disabled).toBe(true);
+
+ await act(async () => {
+ nativeChange(getTitleInput(), "my title");
+ });
+
+ 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);
+ mocks.getOrFetchInstanceByName.mockResolvedValue(TEST_INSTANCE);
+
+ await act(async () => {
+ root.render(
+ createElement(CreateDatabaseSheet, {
+ open: true,
+ onClose: () => {},
+ projectName: "projects/foo",
+ })
+ );
+ await Promise.resolve();
+ });
+
+ await fillInstance();
+ await fillDatabaseName("widgets");
+ await flush();
+
+ expect(getCreateButton().disabled).toBe(true);
+
+ await act(async () => {
+ resolveHydration({
+ enforceIssueTitle: false,
+ issueLabels: [],
+ forceIssueLabels: false,
+ });
+ mocks.getProjectByName.mockReturnValue({
+ enforceIssueTitle: false,
+ issueLabels: [],
+ forceIssueLabels: false,
+ });
+ await Promise.resolve();
+ 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(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")
+ );
+ 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);
+
+ // 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).
+ await act(async () => {
+ nativeChange(getTitleInput(), "");
+ });
+ // 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.
+ expect(getCreateButton().disabled).toBe(false);
+ });
+});
diff --git a/frontend/src/react/components/database/CreateDatabaseSheet.tsx b/frontend/src/react/components/database/CreateDatabaseSheet.tsx
index f42553a8ee..6814c9e027 100644
--- a/frontend/src/react/components/database/CreateDatabaseSheet.tsx
+++ b/frontend/src/react/components/database/CreateDatabaseSheet.tsx
@@ -47,6 +47,7 @@ import {
getDefaultPagination,
getIssueRoute,
instanceV1HasCollationAndCharacterSet,
+ normalizeTitle,
} from "@/utils";
const INTERNAL_RDS_USERS = ["rds_ad", "rdsadmin", "rds_iam"];
@@ -197,6 +198,8 @@ export function CreateDatabaseSheet({
const [characterSet, setCharacterSet] = useState("");
const [collation, setCollation] = useState("");
const [creating, setCreating] = useState(false);
+ const [title, setTitle] = useState("");
+ const [titleEdited, setTitleEdited] = useState(false);
const [issueLabels, setIssueLabels] = useState<string[]>([]);
const [instanceRoles, setInstanceRoles] = useState<
{ name: string; roleName: string }[]
@@ -222,6 +225,28 @@ export function CreateDatabaseSheet({
const effectiveProjectName = fixedProjectName || projectName;
+ // Intentional split: enforceIssueTitle is read reactively via useVueState
+ // because it's a governance gate that MUST reflect the live project 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 projectReactive = useVueState(() =>
+ effectiveProjectName
+ ? projectStore.getProjectByName(effectiveProjectName)
+ : undefined
+ );
+
+ // 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;
+ const enforceIssueTitle =
+ projectHydrated && (projectReactive?.enforceIssueTitle ?? false);
+
const projectFetchRef = useRef(0);
useEffect(() => {
setIssueLabels([]);
@@ -236,9 +261,50 @@ export function CreateDatabaseSheet({
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 });
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.error"),
+ description: String(
+ (error as { message?: string })?.message ?? 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, projectStore]);
+ // Auto-fill when the project doesn't enforce manual titles.
+ // Intentional omissions from the dep array: `title` and `titleEdited` are
+ // read inside the guard (not reactive triggers); `t` is stable.
+ useEffect(() => {
+ if (!projectHydrated) return;
+ if (enforceIssueTitle) return;
+ if (titleEdited && normalizeTitle(title)) return;
+ // Derive from databaseName; clear when input is empty so the title
+ // doesn't retain a stale derivation from the prior keystroke (the
+ // `Create database 'T'` ghost after the user backspaces to empty).
+ setTitle(
+ databaseName ? `${t("quick-action.create-db")} '${databaseName}'` : ""
+ );
+ }, [databaseName, enforceIssueTitle, projectHydrated]);
+
const projectIssueLabels = selectedProject?.issueLabels ?? [];
const forceIssueLabels = selectedProject?.forceIssueLabels ?? false;
@@ -255,7 +321,9 @@ export function CreateDatabaseSheet({
!!databaseName &&
!isReservedName &&
(!requireOwner || !!ownerName) &&
- (!forceIssueLabels || issueLabels.length > 0);
+ (!forceIssueLabels || issueLabels.length > 0) &&
+ projectHydrated &&
+ !(enforceIssueTitle && !normalizeTitle(title));
const searchProjects = useCallback(
(query: string) => {
@@ -286,6 +354,8 @@ export function CreateDatabaseSheet({
setCollation("");
setCreating(false);
setInstanceRoles([]);
+ setTitle("");
+ setTitleEdited(false);
if (!fixedProjectName) searchProjects("");
}, [open, searchProjects, fixedProjectName]);
@@ -341,12 +411,16 @@ export function CreateDatabaseSheet({
id: uuidv4(),
config: { case: "createDatabaseConfig", value: createDatabaseConfig },
});
+ const effectiveTitle =
+ normalizeTitle(title) ||
+ `${t("quick-action.create-db")} '${databaseName}'`;
const planCreate = create(PlanSchema, {
- title: `${t("quick-action.create-db")} '${databaseName}'`,
+ title: effectiveTitle,
specs: [spec],
creator: currentUser.value.name,
});
const issueCreate = create(IssueSchema, {
+ title: effectiveTitle,
type: Issue_Type.DATABASE_CHANGE,
creator: `users/${currentUser.value.email}`,
labels: issueLabels,
@@ -442,6 +516,27 @@ export function CreateDatabaseSheet({
)}
</div>
+ <div className="flex flex-col gap-y-2">
+ <label className="block text-sm font-medium">
+ {t("common.title")}
+ {enforceIssueTitle && <span className="text-error"> *</span>}
+ </label>
+ <Input
+ value={title}
+ placeholder={t("common.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 !== "");
+ }}
+ />
+ </div>
+
{selectedInstance?.engine === Engine.MONGODB && (
<div>
<label className="block text-sm font-medium mb-1">
diff --git a/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx b/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx
index 317bdf1dac..b3afd268f2 100644
--- a/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx
+++ b/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx
@@ -13,6 +13,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { v4 as uuidv4 } from "uuid";
import { EngineIconPath } from "@/components/InstanceForm/constants";
+import { applyPlanTitleToQuery } from "@/components/Plan/logic/title";
import {
AdvancedSearch,
type ScopeOption,
@@ -263,22 +264,22 @@ export function ProjectPlanDashboardPage({ projectId }: { projectId: string }) {
const databaseGroupName = targets[0];
if (!databaseGroupName) return;
query.databaseGroupName = databaseGroupName;
- if (!project.enforceIssueTitle) {
- query.name = generatePlanTitle(template, [
+ applyPlanTitleToQuery(query, project, () =>
+ generatePlanTitle(template, [
extractDatabaseGroupName(databaseGroupName),
- ]);
- }
+ ])
+ );
} else {
query.databaseList = targets.join(",");
- if (!project.enforceIssueTitle) {
- query.name = generatePlanTitle(
+ applyPlanTitleToQuery(query, project, () =>
+ generatePlanTitle(
template,
targets.map((db) => {
const { databaseName } = extractDatabaseResourceName(db);
return databaseName;
})
- );
- }
+ )
+ );
}
await router.push({
diff --git a/frontend/src/react/pages/project/ProjectSyncSchemaPage.tsx b/frontend/src/react/pages/project/ProjectSyncSchemaPage.tsx
index de1eca4589..e6a5a4256c 100644
--- a/frontend/src/react/pages/project/ProjectSyncSchemaPage.tsx
+++ b/frontend/src/react/pages/project/ProjectSyncSchemaPage.tsx
@@ -14,6 +14,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { v4 as uuidv4 } from "uuid";
import { EngineIconPath } from "@/components/InstanceForm/constants";
+import { applyPlanTitleToQuery } from "@/components/Plan/logic/title";
import { DatabaseSelect } from "@/react/components/DatabaseSelect";
import { EnvironmentSelect } from "@/react/components/EnvironmentSelect";
import { LearnMoreLink } from "@/react/components/LearnMoreLink";
@@ -393,10 +394,13 @@ export function ProjectSyncSchemaPage({ projectId }: { projectId: string }) {
const sqlMapStorageKey = `bb.issues.sql-map.${uuidv4()}`;
useStorageStore().put(sqlMapStorageKey, sqlMap);
query.sqlMapStorageKey = sqlMapStorageKey;
- query.name = generatePlanTitle(
- "bb.plan.change-database",
- targetDatabases.map(
- (db) => extractDatabaseResourceName(db.name).databaseName
+ if (!project) return; // defensive: should not happen if the page rendered
+ applyPlanTitleToQuery(query, project, () =>
+ generatePlanTitle(
+ "bb.plan.change-database",
+ targetDatabases.map(
+ (db) => extractDatabaseResourceName(db.name).databaseName
+ )
)
);
diff --git a/frontend/src/react/pages/project/export-center/DataExportPrepSheet.test.tsx b/frontend/src/react/pages/project/export-center/DataExportPrepSheet.test.tsx
new file mode 100644
index 0000000000..d954609df1
--- /dev/null
+++ b/frontend/src/react/pages/project/export-center/DataExportPrepSheet.test.tsx
@@ -0,0 +1,425 @@
+import type {
+ ButtonHTMLAttributes,
+ InputHTMLAttributes,
+ ReactNode,
+} from "react";
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+// ---------------------------------------------------------------------------
+// UI primitive mocks
+// ---------------------------------------------------------------------------
+
+vi.mock("@/react/components/EnvironmentLabel", () => ({
+ EnvironmentLabel: () => null,
+}));
+
+vi.mock("@/react/components/IssueLabelSelect", () => ({
+ IssueLabelSelect: () => null,
+}));
+
+vi.mock("@/react/components/ui/sheet", () => ({
+ Sheet: ({ children, open }: { children: ReactNode; open: boolean }) =>
+ open ? createElement("div", { "data-testid": "sheet" }, children) : null,
+ SheetContent: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ SheetHeader: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ SheetTitle: ({ children }: { children: ReactNode }) =>
+ createElement("h2", {}, children),
+ SheetBody: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ SheetFooter: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+}));
+
+vi.mock("@/react/components/ui/button", () => ({
+ Button: ({
+ children,
+ disabled,
+ onClick,
+ variant: _v,
+ size: _s,
+ }: ButtonHTMLAttributes<HTMLButtonElement> & {
+ variant?: string;
+ size?: string;
+ }) => createElement("button", { disabled, onClick }, children),
+}));
+
+vi.mock("@/react/components/ui/input", () => ({
+ Input: ({ className: _c, ...props }: InputHTMLAttributes<HTMLInputElement>) =>
+ createElement("input", props),
+}));
+
+vi.mock("@/react/components/ui/search-input", () => ({
+ SearchInput: ({
+ className: _c,
+ wrapperClassName: _w,
+ ...props
+ }: InputHTMLAttributes<HTMLInputElement> & {
+ wrapperClassName?: string;
+ }) => createElement("input", props),
+}));
+
+vi.mock("@/react/components/ui/switch", () => ({
+ Switch: ({
+ checked,
+ onCheckedChange,
+ }: {
+ checked: boolean;
+ onCheckedChange: (v: boolean) => void;
+ }) =>
+ createElement("input", {
+ type: "checkbox",
+ checked,
+ onChange: (e: React.ChangeEvent<HTMLInputElement>) =>
+ onCheckedChange(e.target.checked),
+ }),
+}));
+
+vi.mock("@/react/lib/utils", () => ({
+ cn: (...cls: (string | false | null | undefined)[]) =>
+ cls.filter(Boolean).join(" "),
+}));
+
+vi.mock("@/react/hooks/useVueState", () => ({
+ useVueState: (getter: () => unknown) => getter(),
+}));
+
+vi.mock("@/react/hooks/useSessionPageSize", () => ({
+ useSessionPageSize: () => [20, () => {}],
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+// ---------------------------------------------------------------------------
+// Infra / external mocks
+// ---------------------------------------------------------------------------
+
+vi.mock("@bufbuild/protobuf", () => ({
+ create: (_schema: unknown, init?: Record<string, unknown>) => ({ ...init }),
+}));
+
+vi.mock("@/types/proto-es/v1/common_pb", () => ({
+ ExportFormat: { CSV: 1, JSON: 2, SQL: 3, XLSX: 4 },
+}));
+
+vi.mock("@/types/proto-es/v1/database_group_service_pb", () => ({
+ DatabaseGroupView: { BASIC: 1, FULL: 2 },
+}));
+
+vi.mock("@/types/proto-es/v1/issue_service_pb", () => ({
+ Issue_Type: { DATABASE_EXPORT: 1 },
+ IssueSchema: {},
+}));
+
+vi.mock("@/types/proto-es/v1/plan_service_pb", () => ({
+ Plan_ExportDataConfigSchema: {},
+ Plan_SpecSchema: {},
+ PlanSchema: {},
+}));
+
+vi.mock("@/types/proto-es/v1/sheet_service_pb", () => ({
+ SheetSchema: {},
+}));
+
+vi.mock("@/router", () => ({ router: { push: vi.fn() } }));
+
+vi.mock("@/router/dashboard/projectV1", () => ({
+ PROJECT_V1_ROUTE_ISSUE_DETAIL: "issue-detail",
+}));
+
+vi.mock("@/components/InstanceForm/constants", () => ({
+ EngineIconPath: {},
+}));
+
+vi.mock("@/types", () => ({
+ isValidDatabaseName: (name: string) =>
+ typeof name === "string" && name.includes("/databases/"),
+ isValidDatabaseGroupName: (name: string) =>
+ typeof name === "string" && name.includes("/databaseGroups/"),
+}));
+
+vi.mock("@/utils", () => ({
+ DEFAULT_MAX_RESULT_SIZE_IN_MB: 100,
+ extractDatabaseGroupName: (name: string) =>
+ name.split("/databaseGroups/")[1] ?? name,
+ extractDatabaseResourceName: (name: string) => {
+ const parts = name.split("/databases/");
+ return { databaseName: parts[1] ?? name };
+ },
+ extractIssueUID: (name: string) => name.split("/").pop() ?? "",
+ extractProjectResourceName: (name: string) => name.split("/")[1] ?? name,
+ generatePlanTitle: (_template: string, names?: string[]) => {
+ if (!names || names.length === 0) return "[All databases] export";
+ if (names.length === 1) return `[${names[0]}] export`;
+ return `[${names.length} databases] export`;
+ },
+ getDatabaseEnvironment: () => undefined,
+ getInstanceResource: () => undefined,
+ normalizeTitle: (s: string) => s.trim(),
+ setSheetStatement: () => {},
+}));
+
+// ---------------------------------------------------------------------------
+// Store mocks — stable singletons to avoid useEffect dependency churn
+// ---------------------------------------------------------------------------
+
+const mocks = vi.hoisted(() => ({
+ getProjectByName: vi.fn(),
+ getOrFetchDatabaseByName: vi.fn(),
+ getDatabaseByName: vi.fn(),
+ fetchDatabases: vi.fn(),
+ getOrFetchDBGroupByName: vi.fn(),
+ fetchDBGroupListByProjectName: vi.fn(),
+ createSheet: vi.fn(),
+ experimentalCreateIssueByPlan: vi.fn(),
+ pushNotification: vi.fn(),
+ currentUser: { name: "users/[email protected]", email: "[email protected]" },
+}));
+
+const stableProjectStore = {
+ get getProjectByName() {
+ return mocks.getProjectByName;
+ },
+};
+
+const stableDatabaseStore = {
+ get fetchDatabases() {
+ return mocks.fetchDatabases;
+ },
+ get getOrFetchDatabaseByName() {
+ return mocks.getOrFetchDatabaseByName;
+ },
+ get getDatabaseByName() {
+ return mocks.getDatabaseByName;
+ },
+};
+
+const stableDBGroupStore = {
+ get getOrFetchDBGroupByName() {
+ return mocks.getOrFetchDBGroupByName;
+ },
+ get fetchDBGroupListByProjectName() {
+ return mocks.fetchDBGroupListByProjectName;
+ },
+};
+
+const stableSheetStore = {
+ get createSheet() {
+ return mocks.createSheet;
+ },
+};
+
+const stableSettingStore = {
+ workspaceProfile: { sqlResultSize: BigInt(100 * 1024 * 1024) },
+};
+
+vi.mock("@/store", () => ({
+ DEFAULT_MAX_RESULT_SIZE_IN_MB: 100,
+ useProjectV1Store: () => stableProjectStore,
+ useDatabaseV1Store: () => stableDatabaseStore,
+ useDBGroupStore: () => stableDBGroupStore,
+ useSheetV1Store: () => stableSheetStore,
+ useSettingV1Store: () => stableSettingStore,
+ useCurrentUserV1: () => ({ value: mocks.currentUser }),
+ experimentalCreateIssueByPlan: mocks.experimentalCreateIssueByPlan,
+ pushNotification: mocks.pushNotification,
+}));
+
+import { nativeChange } from "@/react/test-utils/nativeChange";
+import { DataExportPrepSheet } from "./DataExportPrepSheet";
+
+// ---------------------------------------------------------------------------
+// Test helpers
+// ---------------------------------------------------------------------------
+
+const DB_WIDGETS = "instances/test/databases/widgets";
+const DB_COGS = "instances/test/databases/cogs";
+
+let container: HTMLDivElement;
+let root: ReturnType<typeof createRoot>;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.fetchDatabases.mockResolvedValue({
+ databases: [
+ { name: DB_WIDGETS, engine: 1 },
+ { name: DB_COGS, engine: 1 },
+ ],
+ nextPageToken: "",
+ });
+ mocks.fetchDBGroupListByProjectName.mockResolvedValue([]);
+ mocks.getOrFetchDatabaseByName.mockResolvedValue(undefined);
+ mocks.getDatabaseByName.mockReturnValue(undefined);
+
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ document.body.removeChild(container);
+});
+
+function setupProjectMock(enforceIssueTitle: boolean): void {
+ mocks.getProjectByName.mockReturnValue({
+ name: "projects/foo",
+ enforceIssueTitle,
+ forceIssueLabels: false,
+ issueLabels: [],
+ });
+}
+
+/** Render with the widgets database pre-selected at step 1, then advance to
+ * step 2. Going via step 1 (rather than seeding `step: 2`) keeps the "Back"
+ * button able to return to step 1 — when `seed.step` is set, handleCancel
+ * closes the sheet instead of navigating back. */
+async function renderSheet(enforceIssueTitle: boolean): Promise<void> {
+ setupProjectMock(enforceIssueTitle);
+ await act(async () => {
+ root.render(
+ createElement(DataExportPrepSheet, {
+ open: true,
+ onClose: () => {},
+ projectName: "projects/foo",
+ seed: { selectedDatabaseNames: [DB_WIDGETS] },
+ })
+ );
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ // Wait for async database list load.
+ await flush();
+ // Advance to step 2 with widgets selected.
+ await act(async () => {
+ getNextButton().click();
+ });
+ await flush();
+}
+
+function getTitleInput(): HTMLInputElement {
+ return container.querySelector(
+ "input[placeholder='common.title']"
+ ) as HTMLInputElement;
+}
+
+function getStatementTextarea(): HTMLTextAreaElement {
+ return container.querySelector(
+ "textarea[placeholder='SELECT ...']"
+ ) as HTMLTextAreaElement;
+}
+
+function getCreateButton(): HTMLButtonElement {
+ return [...container.querySelectorAll("button")].find((b) =>
+ b.textContent?.includes("common.create")
+ ) as HTMLButtonElement;
+}
+
+function getBackButton(): HTMLButtonElement {
+ return [...container.querySelectorAll("button")].find((b) =>
+ b.textContent?.includes("common.back")
+ ) as HTMLButtonElement;
+}
+
+function getNextButton(): HTMLButtonElement {
+ return [...container.querySelectorAll("button")].find((b) =>
+ b.textContent?.includes("common.next")
+ ) as HTMLButtonElement;
+}
+
+async function flush(): Promise<void> {
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+}
+
+/** Toggle a database checkbox in step 1 by matching its row text. */
+async function toggleDatabaseRow(databaseName: string): Promise<void> {
+ const rows = [...container.querySelectorAll("tr")];
+ const row = rows.find((tr) => tr.textContent?.includes(databaseName));
+ if (!row) throw new Error(`Row for ${databaseName} not found`);
+ await act(async () => {
+ row.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+}
+
+describe("DataExportPrepSheet — enforceIssueTitle (BYT-9310)", () => {
+ it("auto-fills title from targets when enforceIssueTitle is false", async () => {
+ await renderSheet(false);
+
+ const titleInput = getTitleInput();
+ expect(titleInput).toBeTruthy();
+ expect(titleInput.value).toBe(`[widgets] export`);
+ });
+
+ it("does not auto-fill title when enforceIssueTitle is true", async () => {
+ await renderSheet(true);
+
+ const titleInput = getTitleInput();
+ expect(titleInput).toBeTruthy();
+ expect(titleInput.value).toBe("");
+ });
+
+ it("preserves a user-typed title across target changes", async () => {
+ await renderSheet(false);
+
+ expect(getTitleInput().value).toBe(`[widgets] export`);
+
+ // User overrides the auto-filled title.
+ await act(async () => {
+ nativeChange(getTitleInput(), "my custom title");
+ });
+ expect(getTitleInput().value).toBe("my custom title");
+
+ // Navigate back to step 1 (state is preserved across step nav).
+ await act(async () => {
+ getBackButton().click();
+ });
+ await flush();
+
+ // Add another database to the selection.
+ await toggleDatabaseRow("cogs");
+ await flush();
+
+ // Advance back to step 2 with the expanded target list.
+ await act(async () => {
+ getNextButton().click();
+ });
+ await flush();
+
+ // Custom title must be preserved — auto-fill must not overwrite it.
+ expect(getTitleInput().value).toBe("my custom title");
+ });
+
+ it("disables Create when enforceIssueTitle is true and title is empty, enables when typed", async () => {
+ await renderSheet(true);
+
+ // Fill statement so the only gating condition left is the title.
+ await act(async () => {
+ nativeChange(getStatementTextarea(), "SELECT 1");
+ });
+ await flush();
+
+ expect(getTitleInput().value).toBe("");
+ expect(getCreateButton().disabled).toBe(true);
+
+ await act(async () => {
+ nativeChange(getTitleInput(), "my title");
+ });
+ await flush();
+
+ expect(getCreateButton().disabled).toBe(false);
+ });
+});
diff --git a/frontend/src/react/pages/project/export-center/DataExportPrepSheet.tsx b/frontend/src/react/pages/project/export-center/DataExportPrepSheet.tsx
index 94d6924a66..67c1639f58 100644
--- a/frontend/src/react/pages/project/export-center/DataExportPrepSheet.tsx
+++ b/frontend/src/react/pages/project/export-center/DataExportPrepSheet.tsx
@@ -54,6 +54,7 @@ import {
generatePlanTitle,
getDatabaseEnvironment,
getInstanceResource,
+ normalizeTitle,
setSheetStatement,
} from "@/utils";
@@ -149,15 +150,15 @@ export function DataExportPrepSheet({
const canCreate = useMemo(() => {
if (!validSelectState) return false;
- if (project?.enforceIssueTitle && !title.trim()) return false;
+ if (project?.enforceIssueTitle && !normalizeTitle(title)) return false;
if (project?.forceIssueLabels && labels.length === 0) return false;
if (!statement.trim()) return false;
return true;
}, [validSelectState, project, title, labels, statement]);
const effectiveTitle = useMemo(() => {
- const trimmed = title.trim();
- if (trimmed) return trimmed;
+ const normalized = normalizeTitle(title);
+ if (normalized) return normalized;
return generatePlanTitle("bb.plan.export-data", targetTitleNames);
}, [title, targetTitleNames]);
@@ -166,7 +167,7 @@ export function DataExportPrepSheet({
useEffect(() => {
if (project?.enforceIssueTitle) return;
if (targetTitleNames.length === 0) return;
- if (titleEdited && title.trim()) return;
+ if (titleEdited && normalizeTitle(title)) return;
setTitle(generatePlanTitle("bb.plan.export-data", targetTitleNames));
}, [targetKey]);
@@ -358,8 +359,11 @@ export function DataExportPrepSheet({
value={title}
placeholder={t("common.title")}
onChange={(e) => {
- setTitle(e.target.value);
- setTitleEdited(true);
+ const next = e.target.value;
+ setTitle(next);
+ // Invariant: titleEdited ⇒ title is non-empty user intent.
+ // See CreateDatabaseSheet for the detailed rationale.
+ setTitleEdited(next !== "");
}}
/>
</div>
diff --git a/frontend/src/react/pages/settings/MembersPage.tsx b/frontend/src/react/pages/settings/MembersPage.tsx
index 9b377b704e..5b0c1da288 100644
--- a/frontend/src/react/pages/settings/MembersPage.tsx
+++ b/frontend/src/react/pages/settings/MembersPage.tsx
@@ -1,9 +1,6 @@
import { create } from "@bufbuild/protobuf";
-import { DurationSchema } from "@bufbuild/protobuf/wkt";
-import dayjs from "dayjs";
import {
Building2,
- Check,
ChevronDown,
ChevronRight,
Info,
@@ -29,21 +26,11 @@ import {
roleHasDatabaseLimitation,
roleHasEnvironmentLimitation,
} from "@/components/ProjectMember/utils";
-import { issueServiceClientConnect } from "@/connect";
-import type { ConditionGroupExpr, Factor, Operator } from "@/plugins/cel";
-import {
- buildCELExpr,
- emptySimpleExpr,
- validateSimpleExpr,
- wrapAsGroup,
-} from "@/plugins/cel";
import { AccountMultiSelect } from "@/react/components/AccountMultiSelect";
import { DatabaseResourceSelector as DatabaseResourceSelectorComponent } from "@/react/components/DatabaseResourceSelector";
import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";
-import type { OptionConfig } from "@/react/components/ExprEditor";
-import { ExprEditor } from "@/react/components/ExprEditor";
+import { EnvironmentMultiSelect } from "@/react/components/EnvironmentMultiSelect";
import { FeatureBadge } from "@/react/components/FeatureBadge";
-import { IssueLabelSelect } from "@/react/components/IssueLabelSelect";
import { LearnMoreLink } from "@/react/components/LearnMoreLink";
import { PermissionGuard } from "@/react/components/PermissionGuard";
import { RoleSelect } from "@/react/components/RoleSelect";
@@ -55,36 +42,22 @@ import {
} from "@/react/components/ui/alert";
import { Badge } from "@/react/components/ui/badge";
import { Button } from "@/react/components/ui/button";
-import { ExpirationPicker } from "@/react/components/ui/expiration-picker";
import { Input } from "@/react/components/ui/input";
import { SearchInput } from "@/react/components/ui/search-input";
-import {
- Sheet,
- SheetBody,
- SheetContent,
- SheetFooter,
- SheetHeader,
- SheetTitle,
-} from "@/react/components/ui/sheet";
import {
Tabs,
TabsList,
TabsPanel,
TabsTrigger,
} from "@/react/components/ui/tabs";
-import { Textarea } from "@/react/components/ui/textarea";
import { Tooltip } from "@/react/components/ui/tooltip";
-import { useClickOutside } from "@/react/hooks/useClickOutside";
import { useEscapeKey } from "@/react/hooks/useEscapeKey";
import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
import {
pushNotification,
useActuatorV1Store,
useCurrentUserV1,
- useEnvironmentV1Store,
useProjectIamPolicyStore,
useProjectV1Store,
useRoleStore,
@@ -97,49 +70,33 @@ import {
ALL_USERS_USER_EMAIL,
type DatabaseResource,
isDefaultProject,
- PresetRoleType,
userBindingPrefix,
} from "@/types";
import { ExprSchema as ConditionExprSchema } from "@/types/proto-es/google/type/expr_pb";
import { State } from "@/types/proto-es/v1/common_pb";
import { type Binding, BindingSchema } from "@/types/proto-es/v1/iam_policy_pb";
-import {
- CreateIssueRequestSchema,
- Issue_Type,
- IssueSchema,
- RoleGrantSchema,
-} from "@/types/proto-es/v1/issue_service_pb";
-import type { Project } from "@/types/proto-es/v1/project_service_pb";
import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import { AccountType, getAccountTypeByEmail } from "@/types/v1/user";
import {
- batchConvertParsedExprToCELString,
displayRoleTitle,
- extractIssueUID,
- extractProjectResourceName,
formatAbsoluteDateTime,
- formatIssueTitle,
- getDatabaseNameOptionConfig,
hasProjectPermissionV2,
hasWorkspacePermissionV2,
sortRoles,
} from "@/utils";
-import {
- CEL_ATTRIBUTE_RESOURCE_DATABASE,
- CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME,
- CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,
-} from "@/utils/cel-attributes";
import {
buildConditionExpr,
convertFromExpr,
stringifyConditionExpression,
} from "@/utils/issue/cel";
import { getSetIamPolicyPermissionGuardConfig } from "./membersPageActions";
+import { RequestRoleSheet } from "./RequestRoleSheet";
import {
getRequestRoleButtonState,
REQUEST_ROLE_REQUIRED_PERMISSIONS,
} from "./requestRoleButton";
+import type { DatabaseMode } from "./types";
const EMPTY_ROLE_SET = new Set<string>();
@@ -659,8 +616,6 @@ function formatExpirationDate(timestampMs?: number): string {
// ProjectRoleBindingForm — one role binding form in create mode
// ============================================================
-type DatabaseMode = "ALL" | "EXPRESSION" | "SELECT";
-
interface RoleBindingFormState {
id: string;
role: string;
@@ -673,108 +628,6 @@ interface RoleBindingFormState {
environments: string[];
}
-// ============================================================
-// EnvironmentMultiSelect
-// ============================================================
-
-function EnvironmentMultiSelect({
- value,
- onChange,
-}: {
- value: string[];
- onChange: (envs: string[]) => void;
-}) {
- const { t } = useTranslation();
- const environmentStore = useEnvironmentV1Store();
- const environmentList = useVueState(
- () => environmentStore.environmentList ?? []
- );
- const [open, setOpen] = useState(false);
- const containerRef = useRef<HTMLDivElement>(null);
-
- const handleClickOutside = useCallback(() => setOpen(false), []);
- useClickOutside(containerRef, open, handleClickOutside);
-
- const toggle = (name: string) => {
- onChange(
- value.includes(name) ? value.filter((v) => v !== name) : [...value, name]
- );
- };
-
- const remove = (name: string) => {
- onChange(value.filter((v) => v !== name));
- };
-
- return (
- <div ref={containerRef} className="relative">
- <div
- className={cn(
- "flex items-center flex-wrap gap-1 min-h-[2.25rem] w-full rounded-xs border border-control-border bg-transparent px-2 py-1 text-sm cursor-pointer",
- open && "border-accent"
- )}
- onClick={() => setOpen(!open)}
- >
- {value.length === 0 && (
- <span className="text-control-placeholder">
- {t("environment.select")}
- </span>
- )}
- {value.map((name) => (
- <span
- key={name}
- className="inline-flex items-center gap-x-1 rounded-xs border border-control-border px-1 py-0.5 text-xs"
- >
- <EnvironmentLabel environmentName={name} className="text-xs" />
- <button
- type="button"
- className="text-control-light hover:text-control"
- onClick={(e) => {
- e.stopPropagation();
- remove(name);
- }}
- >
- <X className="h-3 w-3" />
- </button>
- </span>
- ))}
- <ChevronDown className="ml-auto h-4 w-4 shrink-0 text-control-light" />
- </div>
-
- {open && (
- <div className="absolute z-50 mt-1 w-full bg-background border border-control-border rounded-sm shadow-lg max-h-60 overflow-auto">
- {environmentList.length === 0 && (
- <div className="px-3 py-2 text-sm text-control-light">
- {t("common.no-data")}
- </div>
- )}
- {environmentList.map((env) => {
- const selected = value.includes(env.name);
- return (
- <div
- key={env.name}
- className="flex items-center gap-x-2 px-3 py-1.5 text-sm hover:bg-control-bg cursor-pointer"
- onClick={() => toggle(env.name)}
- >
- <div
- className={cn(
- "size-4 rounded-xs border flex items-center justify-center shrink-0",
- selected
- ? "bg-accent border-accent text-accent-text"
- : "border-control-border"
- )}
- >
- {selected && <Check className="h-3 w-3" />}
- </div>
- <EnvironmentLabel environment={env} />
- </div>
- );
- })}
- </div>
- )}
- </div>
- );
-}
-
// ============================================================
// DatabaseResourceSection — radio modes + selector
// ============================================================
@@ -1702,475 +1555,6 @@ function EditMemberRoleDrawer({
);
}
-// ============================================================
-// RequestRoleDialog — lets a project member without
-// `bb.projects.setIamPolicy` open a role-grant issue to request
-// access for themselves. This is the React equivalent of the old
-// Vue `RoleGrantPanel` entry point that lived on the project
-// members page before the React migration.
-// ============================================================
-
-interface RequestRoleSheetProps {
- open: boolean;
- project: Project;
- onClose: () => void;
-}
-
-function RequestRoleSheet(props: RequestRoleSheetProps) {
- const { open, project, onClose } = props;
- return (
- <Sheet open={open} onOpenChange={(next) => !next && onClose()}>
- <SheetContent width="standard">
- {/* Base UI's Dialog.Portal unmounts after the close animation,
- so the inner form mounts/unmounts with the Sheet's lifecycle
- without needing an explicit {open && ...} guard. The `key`
- forces a fresh mount if the project switches while open. */}
- <RequestRoleForm key={project.name} {...props} />
- </SheetContent>
- </Sheet>
- );
-}
-
-function RequestRoleForm({
- project,
- onClose,
-}: Omit<RequestRoleSheetProps, "open">) {
- const { t } = useTranslation();
- const currentUser = useVueState(() => useCurrentUserV1().value);
- const [role, setRole] = useState("");
- const [reason, setReason] = useState("");
- const [expirationTimestamp, setExpirationTimestamp] = useState<
- string | undefined
- >(undefined);
- const [labels, setLabels] = useState<string[]>([]);
- // Role-scope fields — only rendered for roles that require them, but kept
- // in state so switching roles back and forth preserves user input.
- const [databaseMode, setDatabaseMode] = useState<DatabaseMode>("ALL");
- const [databaseResources, setDatabaseResources] = useState<
- DatabaseResource[]
- >([]);
- // CEL expression for EXPRESSION mode is held as a structured group so it
- // can render in ExprEditor (matching the old Vue DatabaseResourceForm).
- const [exprGroup, setExprGroup] = useState<ConditionGroupExpr>(() =>
- wrapAsGroup(emptySimpleExpr())
- );
- const [environments, setEnvironments] = useState<string[]>([]);
- const [submitting, setSubmitting] = useState(false);
-
- const settingStore = useSettingV1Store();
-
- // Workspace-configured maximum role expiration, in days. Matches the old
- // Vue ExpirationSelector: PROJECT_OWNER grants are exempted (project
- // owners can request unbounded expirations), otherwise the workspace cap
- // applies. Returns undefined when no cap is set.
- const maximumRoleExpirationDays = useVueState(() => {
- if (role === PresetRoleType.PROJECT_OWNER) return undefined;
- const seconds =
- settingStore.workspaceProfile.maximumRoleExpiration?.seconds;
- if (!seconds) return undefined;
- return Math.floor(Number(seconds) / (60 * 60 * 24));
- });
-
- // ExprEditor factor/option config — mirrors the old Vue
- // DatabaseResourceForm config for role-grant requests.
- const factorList = useMemo<Factor[]>(
- () => [
- CEL_ATTRIBUTE_RESOURCE_DATABASE,
- CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,
- CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME,
- ],
- []
- );
- const factorOperatorOverrideMap = useMemo(
- () =>
- new Map<Factor, Operator[]>([
- [CEL_ATTRIBUTE_RESOURCE_DATABASE, ["_==_", "@in"]],
- [CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME, ["_==_"]],
- [CEL_ATTRIBUTE_RESOURCE_TABLE_NAME, ["_==_", "@in"]],
- ]),
- []
- );
- const factorOptionConfigMap = useMemo(
- () =>
- factorList.reduce((map, factor) => {
- if (factor === CEL_ATTRIBUTE_RESOURCE_DATABASE) {
- map.set(factor, getDatabaseNameOptionConfig(project.name));
- } else {
- map.set(factor, { options: [] });
- }
- return map;
- }, new Map<Factor, OptionConfig>()),
- [factorList, project.name]
- );
-
- // Bind the datetime-local picker's min to the current minute so users
- // can't silently pick a time earlier today and submit a zero-duration
- // role grant.
- const minDatetime = dayjs().format("YYYY-MM-DDTHH:mm");
- const maxDatetime = maximumRoleExpirationDays
- ? dayjs().add(maximumRoleExpirationDays, "days").format("YYYY-MM-DDTHH:mm")
- : undefined;
-
- const expirationIsInPast =
- !!expirationTimestamp &&
- dayjs(expirationTimestamp).unix() <= dayjs().unix();
-
- // Workspace policy may cap role expiration; block submit when the picked
- // timestamp would exceed that cap (matches Vue ExpirationSelector which
- // disables over-cap dates in its picker).
- const expirationExceedsMax =
- !!expirationTimestamp &&
- !!maximumRoleExpirationDays &&
- dayjs(expirationTimestamp).isAfter(
- dayjs().add(maximumRoleExpirationDays, "days")
- );
-
- const labelsMisconfigured =
- project.forceIssueLabels && project.issueLabels.length === 0;
-
- // Match the old Vue AddProjectMemberForm behavior: reason is only required
- // when the project enforces issue titles (where the reason becomes the
- // title). Otherwise the title is auto-generated and the reason is optional.
- const reasonRequired = project.enforceIssueTitle;
-
- // SQL-permission roles need a database scope (and sometimes an environment
- // scope). Submitting without one produces a project-wide binding which is
- // broader than the user typically intends.
- const showDatabases = !!role && roleHasDatabaseLimitation(role);
- const showEnvironments = !!role && roleHasEnvironmentLimitation(role);
-
- const databaseScopeComplete =
- !showDatabases ||
- databaseMode === "ALL" ||
- (databaseMode === "SELECT" && databaseResources.length > 0) ||
- (databaseMode === "EXPRESSION" && validateSimpleExpr(exprGroup));
-
- // When the workspace enforces a maximum role expiration, the user MUST
- // pick an expiration — leaving it empty sends `roleGrant.expiration` as
- // `undefined`, which the backend's approval runner treats as effectively
- // unbounded (math.MaxInt32 days), bypassing the cap entirely.
- const expirationRequired = maximumRoleExpirationDays !== undefined;
-
- const canSubmit =
- !submitting &&
- !!role &&
- (!reasonRequired || reason.trim().length > 0) &&
- (!expirationRequired || !!expirationTimestamp) &&
- !expirationIsInPast &&
- !expirationExceedsMax &&
- !labelsMisconfigured &&
- databaseScopeComplete &&
- (!project.forceIssueLabels || labels.length > 0);
-
- const handleSubmit = async () => {
- if (!canSubmit) return;
- setSubmitting(true);
- try {
- const trimmedReason = reason.trim();
- const expirationTimestampInMS = expirationTimestamp
- ? dayjs(expirationTimestamp).valueOf()
- : undefined;
-
- // Only pass scope filters when the selected role actually requires
- // them, matching EditMemberRoleDrawer's submit logic.
- const scopedDatabaseResources =
- showDatabases &&
- databaseMode === "SELECT" &&
- databaseResources.length > 0
- ? databaseResources
- : undefined;
- const scopedEnvironments = showEnvironments ? environments : undefined;
-
- // The backend uses two fields on the RoleGrant message:
- // 1. `condition.expression` — CEL evaluated by
- // UpdateProjectPolicyFromRoleGrantIssue to gate the resulting
- // project IAM binding (access control).
- // 2. `expiration` — Duration consumed by
- // backend/runner/approval/runner.go (request.expiration_days) to
- // route the approval chain; unset defaults to math.MaxInt32 days.
- // Both must be populated — the condition controls what the grant
- // allows, the expiration controls which approvers review it.
- let condition;
- if (showDatabases && databaseMode === "EXPRESSION") {
- // Convert the structured ExprEditor group to a raw CEL string and
- // combine it with any environment/expiration clauses. Mirrors
- // ProjectMaskingExemptionCreatePage's EXPRESSION-mode submit path.
- const parsedExpr = await buildCELExpr(exprGroup);
- if (!parsedExpr) {
- throw new Error("failed to build CEL expression");
- }
- const [exprString] = await batchConvertParsedExprToCELString([
- parsedExpr,
- ]);
- // `batchConvertParsedExprToCELString` swallows deparse errors and
- // returns an empty string on failure. Submitting anyway would
- // silently drop the database scope filter and produce a broader
- // grant than the user requested — refuse instead and surface an
- // error so the user can retry.
- if (!exprString || !exprString.trim()) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("project.members.request-role.failed-to-build-expression"),
- });
- return;
- }
- const extraParts = stringifyConditionExpression({
- expirationTimestampInMS,
- environments: scopedEnvironments,
- });
- const fullExpression = extraParts
- ? `(${exprString}) && ${extraParts}`
- : exprString;
- condition = create(ConditionExprSchema, {
- expression: fullExpression,
- description: trimmedReason,
- });
- } else {
- condition = buildConditionExpr({
- role,
- description: trimmedReason,
- expirationTimestampInMS,
- databaseResources: scopedDatabaseResources,
- environments: scopedEnvironments,
- });
- }
-
- const expiration = expirationTimestamp
- ? create(DurationSchema, {
- seconds: BigInt(
- Math.max(0, dayjs(expirationTimestamp).unix() - dayjs().unix())
- ),
- })
- : undefined;
-
- const roleGrant = create(RoleGrantSchema, {
- role,
- user: `users/${currentUser.email}`,
- condition,
- expiration,
- });
-
- // Collect the scoped database names so the auto-generated title shows
- // `[db1]` / `[N databases]` instead of defaulting to `[All databases]`
- // — matches the old Vue RoleGrantPanel behavior. EXPRESSION mode
- // currently falls through to `[All databases]` since parsing CEL back
- // into concrete database names would require an async round-trip.
- const titleDatabaseNames =
- scopedDatabaseResources && scopedDatabaseResources.length > 0
- ? [...new Set(scopedDatabaseResources.map((r) => r.databaseFullName))]
- : undefined;
-
- // When the project enforces issue titles, the user-provided reason is
- // treated as the title (matching the old Vue RoleGrantPanel behavior).
- const title = project.enforceIssueTitle
- ? `[${t("issue.title.request-role")}] ${trimmedReason}`
- : formatIssueTitle(
- t("issue.title.request-specific-role", {
- role: displayRoleTitle(role),
- }),
- titleDatabaseNames
- );
-
- const newIssue = create(IssueSchema, {
- title,
- description: trimmedReason,
- type: Issue_Type.ROLE_GRANT,
- roleGrant,
- labels,
- });
- const response = await issueServiceClientConnect.createIssue(
- create(CreateIssueRequestSchema, {
- parent: project.name,
- issue: newIssue,
- })
- );
- const route = router.resolve({
- name: PROJECT_V1_ROUTE_ISSUE_DETAIL,
- params: {
- projectId: extractProjectResourceName(response.name),
- issueId: extractIssueUID(response.name),
- },
- });
- window.open(route.fullPath, "_blank", "noopener,noreferrer");
- onClose();
- } catch {
- // Error notification is pushed by the client middleware.
- } finally {
- setSubmitting(false);
- }
- };
-
- const showLabelSelect =
- project.issueLabels.length > 0 || project.forceIssueLabels;
-
- return (
- <>
- <SheetHeader>
- <SheetTitle>{t("issue.title.request-role")}</SheetTitle>
- </SheetHeader>
- <SheetBody>
- <div className="flex flex-col gap-y-4">
- {labelsMisconfigured && (
- <Alert variant="warning">
- <AlertTitle>
- {t("project.members.request-role.labels-misconfigured.title")}
- </AlertTitle>
- <AlertDescription>
- {t(
- "project.members.request-role.labels-misconfigured.description"
- )}
- </AlertDescription>
- </Alert>
- )}
- <div className="flex flex-col gap-y-1">
- <label className="text-sm font-medium">
- {t("common.role.self")}
- <span className="text-error ml-0.5">*</span>
- </label>
- <RoleSelect
- scope="project"
- multiple={false}
- value={role ? [role] : []}
- onChange={(roles) => {
- setRole(roles[0] ?? "");
- // Reset scope when switching roles since DB/env fields only
- // apply to some roles and the new role may not use them.
- setDatabaseMode("ALL");
- setDatabaseResources([]);
- setExprGroup(wrapAsGroup(emptySimpleExpr()));
- setEnvironments([]);
- }}
- />
- </div>
- <div className="flex flex-col gap-y-1">
- <label className="text-sm font-medium">
- {t("common.reason")}
- {reasonRequired && <span className="text-error ml-0.5">*</span>}
- </label>
- <Textarea
- value={reason}
- onChange={(e) => setReason(e.target.value)}
- placeholder={t("common.reason")}
- rows={3}
- />
- </div>
- {showDatabases && (
- <div className="flex flex-col gap-y-2">
- <label className="text-sm font-medium">
- {t("common.databases")}
- <span className="text-error ml-0.5">*</span>
- </label>
- <div className="flex items-center gap-x-4">
- {(["ALL", "EXPRESSION", "SELECT"] as DatabaseMode[]).map(
- (m) => (
- <label
- key={m}
- className="flex items-center gap-x-2 text-sm cursor-pointer"
- >
- <input
- type="radio"
- name="request-role-db-mode"
- checked={databaseMode === m}
- onChange={() => {
- setDatabaseMode(m);
- setDatabaseResources([]);
- setExprGroup(wrapAsGroup(emptySimpleExpr()));
- }}
- />
- {m === "ALL"
- ? t("issue.role-grant.all-databases")
- : m === "EXPRESSION"
- ? t("issue.role-grant.use-cel")
- : t("issue.role-grant.manually-select")}
- </label>
- )
- )}
- </div>
- {databaseMode === "EXPRESSION" && (
- <ExprEditor
- expr={exprGroup}
- factorList={factorList}
- optionConfigMap={factorOptionConfigMap}
- factorOperatorOverrideMap={factorOperatorOverrideMap}
- onUpdate={setExprGroup}
- />
- )}
- {databaseMode === "SELECT" && (
- <DatabaseResourceSelectorComponent
- projectName={project.name}
- value={databaseResources}
- onChange={setDatabaseResources}
- />
- )}
- </div>
- )}
- {showEnvironments && (
- <div className="flex flex-col gap-y-1">
- <label className="text-sm font-medium">
- {t("common.environments")}
- </label>
- <EnvironmentMultiSelect
- value={environments}
- onChange={setEnvironments}
- />
- </div>
- )}
- <div className="flex flex-col gap-y-1">
- <label className="text-sm font-medium">
- {t("common.expiration")}
- {expirationRequired && (
- <span className="text-error ml-0.5">*</span>
- )}
- </label>
- <ExpirationPicker
- value={expirationTimestamp}
- onChange={setExpirationTimestamp}
- minDate={minDatetime}
- maxDate={maxDatetime}
- />
- {maximumRoleExpirationDays !== undefined && (
- <p className="text-xs text-control-light">
- {t("project.members.request-role.max-expiration-hint", {
- days: maximumRoleExpirationDays,
- })}
- </p>
- )}
- {expirationIsInPast && (
- <p className="text-xs text-error">
- {t("project.members.request-role.expiration-must-be-future")}
- </p>
- )}
- {expirationExceedsMax && (
- <p className="text-xs text-error">
- {t("project.members.request-role.expiration-exceeds-max", {
- days: maximumRoleExpirationDays,
- })}
- </p>
- )}
- </div>
- {showLabelSelect && (
- <IssueLabelSelect
- labels={project.issueLabels}
- selected={labels}
- required={project.forceIssueLabels}
- onChange={setLabels}
- />
- )}
- </div>
- </SheetBody>
- <SheetFooter>
- <Button variant="outline" onClick={onClose} disabled={submitting}>
- {t("common.cancel")}
- </Button>
- <Button disabled={!canSubmit} onClick={handleSubmit}>
- {t("common.submit")}
- </Button>
- </SheetFooter>
- </>
- );
-}
-
// ============================================================
// MembersPage
// ============================================================
diff --git a/frontend/src/react/pages/settings/RequestRoleSheet.test.tsx b/frontend/src/react/pages/settings/RequestRoleSheet.test.tsx
new file mode 100644
index 0000000000..17ff0bf3f4
--- /dev/null
+++ b/frontend/src/react/pages/settings/RequestRoleSheet.test.tsx
@@ -0,0 +1,374 @@
+import type {
+ ButtonHTMLAttributes,
+ ReactNode,
+ TextareaHTMLAttributes,
+} from "react";
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+// ---------------------------------------------------------------------------
+// Stub EnvironmentMultiSelect — the real component mounts Pinia-backed
+// environment state that's not worth wiring up for these tests.
+// ---------------------------------------------------------------------------
+
+vi.mock("@/react/components/EnvironmentMultiSelect", () => ({
+ EnvironmentMultiSelect: () =>
+ createElement("div", { "data-testid": "env-multi-select" }),
+}));
+
+// ---------------------------------------------------------------------------
+// UI primitive mocks — mirror the Task 7/8 test harness so the sheet renders
+// as inert DOM and submit button text is the literal i18n key.
+// ---------------------------------------------------------------------------
+
+vi.mock("@/react/components/ui/sheet", () => ({
+ Sheet: ({ children, open }: { children: ReactNode; open: boolean }) =>
+ open ? createElement("div", { "data-testid": "sheet" }, children) : null,
+ SheetContent: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ SheetHeader: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ SheetTitle: ({ children }: { children: ReactNode }) =>
+ createElement("h2", {}, children),
+ SheetBody: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ SheetFooter: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+}));
+
+vi.mock("@/react/components/ui/button", () => ({
+ Button: ({
+ children,
+ disabled,
+ onClick,
+ variant: _v,
+ }: ButtonHTMLAttributes<HTMLButtonElement> & { variant?: string }) =>
+ createElement("button", { disabled, onClick }, children),
+}));
+
+vi.mock("@/react/components/ui/textarea", () => ({
+ Textarea: ({
+ className: _c,
+ size: _s,
+ ...props
+ }: TextareaHTMLAttributes<HTMLTextAreaElement> & {
+ size?: string;
+ }) => createElement("textarea", props),
+}));
+
+vi.mock("@/react/components/ui/expiration-picker", () => ({
+ ExpirationPicker: () => null,
+}));
+
+vi.mock("@/react/components/ui/alert", () => ({
+ Alert: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ AlertTitle: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+ AlertDescription: ({ children }: { children: ReactNode }) =>
+ createElement("div", {}, children),
+}));
+
+vi.mock("@/react/components/IssueLabelSelect", () => ({
+ IssueLabelSelect: () => null,
+}));
+
+vi.mock("@/react/components/DatabaseResourceSelector", () => ({
+ DatabaseResourceSelector: () => null,
+}));
+
+vi.mock("@/react/components/ExprEditor", () => ({
+ ExprEditor: () => null,
+}));
+
+// RoleSelect: test-only stub that exposes a plain <select> so tests can pick a
+// role by setting value. We drive role selection via a hidden input bound to
+// onChange([value]).
+vi.mock("@/react/components/RoleSelect", () => ({
+ RoleSelect: ({
+ value,
+ onChange,
+ }: {
+ value: string[];
+ onChange: (roles: string[]) => void;
+ scope?: string;
+ multiple?: boolean;
+ }) =>
+ createElement("input", {
+ "data-testid": "role-select",
+ value: value[0] ?? "",
+ onChange: (e: React.ChangeEvent<HTMLInputElement>) =>
+ onChange(e.target.value ? [e.target.value] : []),
+ }),
+}));
+
+vi.mock("@/react/hooks/useVueState", () => ({
+ useVueState: (getter: () => unknown) => getter(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+// ---------------------------------------------------------------------------
+// Infra / cross-module mocks
+// ---------------------------------------------------------------------------
+
+// Preserve `create` from the real @bufbuild/protobuf so the production
+// `create(IssueSchema, {...})` call still returns a plain object containing
+// the `title` field we assert on.
+vi.mock("@bufbuild/protobuf", () => ({
+ create: (_schema: unknown, init?: Record<string, unknown>) => ({ ...init }),
+}));
+
+vi.mock("@bufbuild/protobuf/wkt", () => ({
+ DurationSchema: {},
+}));
+
+vi.mock("@/types/proto-es/google/type/expr_pb", () => ({
+ ExprSchema: {},
+}));
+
+vi.mock("@/types/proto-es/v1/issue_service_pb", () => ({
+ CreateIssueRequestSchema: {},
+ Issue_Type: { ROLE_GRANT: 1 },
+ IssueSchema: {},
+ RoleGrantSchema: {},
+}));
+
+vi.mock("@/types/proto-es/v1/project_service_pb", () => ({}));
+
+vi.mock("@/router", () => ({
+ router: {
+ resolve: () => ({ fullPath: "/issues/1" }),
+ },
+}));
+
+vi.mock("@/router/dashboard/projectV1", () => ({
+ PROJECT_V1_ROUTE_ISSUE_DETAIL: "issue-detail",
+}));
+
+vi.mock("@/components/ProjectMember/utils", () => ({
+ // PROJECT_OWNER is not a SQL-permission role — these return false, so the
+ // database/environment scope sections stay hidden in the tests.
+ roleHasDatabaseLimitation: () => false,
+ roleHasEnvironmentLimitation: () => false,
+}));
+
+vi.mock("@/plugins/cel", () => ({
+ buildCELExpr: vi.fn(),
+ emptySimpleExpr: () => ({}),
+ validateSimpleExpr: () => true,
+ wrapAsGroup: (e: unknown) => e,
+}));
+
+vi.mock("@/utils/cel-attributes", () => ({
+ CEL_ATTRIBUTE_RESOURCE_DATABASE: "resource.database",
+ CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME: "resource.schema_name",
+ CEL_ATTRIBUTE_RESOURCE_TABLE_NAME: "resource.table_name",
+}));
+
+vi.mock("@/utils/issue/cel", () => ({
+ buildConditionExpr: (args: Record<string, unknown>) => ({ ...args }),
+ stringifyConditionExpression: () => "",
+}));
+
+vi.mock("@/utils", () => ({
+ batchConvertParsedExprToCELString: vi.fn(),
+ displayRoleTitle: (role: string) => `TITLE(${role})`,
+ extractIssueUID: (name: string) => name.split("/").pop() ?? "",
+ extractProjectResourceName: (name: string) => name.split("/")[1] ?? name,
+ formatIssueTitle: (title: string) => `FMT(${title})`,
+ getDatabaseNameOptionConfig: () => ({ options: [] }),
+ normalizeTitle: (s: string) => s.trim(),
+}));
+
+vi.mock("@/types", () => ({
+ PresetRoleType: {
+ PROJECT_OWNER: "roles/projectOwner",
+ },
+}));
+
+// ---------------------------------------------------------------------------
+// Store / connect mocks — stable singletons for Pinia-adjacent bridges.
+// ---------------------------------------------------------------------------
+
+const mocks = vi.hoisted(() => ({
+ createIssue: vi.fn(),
+ pushNotification: vi.fn(),
+ currentUser: { name: "users/[email protected]", email: "[email protected]" },
+}));
+
+const stableSettingStore = {
+ workspaceProfile: { maximumRoleExpiration: undefined },
+};
+
+vi.mock("@/connect", () => ({
+ issueServiceClientConnect: {
+ createIssue: (req: unknown) => mocks.createIssue(req),
+ },
+}));
+
+vi.mock("@/store", () => ({
+ useCurrentUserV1: () => ({ value: mocks.currentUser }),
+ useSettingV1Store: () => stableSettingStore,
+ pushNotification: (...args: unknown[]) => mocks.pushNotification(...args),
+}));
+
+// ---------------------------------------------------------------------------
+// Import SUT after mocks are registered.
+// ---------------------------------------------------------------------------
+
+import { nativeChange } from "@/react/test-utils/nativeChange";
+import { RequestRoleSheet } from "./RequestRoleSheet";
+
+const PROJECT_BASE = {
+ name: "projects/foo",
+ issueLabels: [],
+ forceIssueLabels: false,
+};
+
+let container: HTMLDivElement;
+let root: ReturnType<typeof createRoot>;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.createIssue.mockResolvedValue({
+ name: "projects/foo/issues/1",
+ });
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ document.body.removeChild(container);
+});
+
+async function flush(): Promise<void> {
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+}
+
+async function renderSheet(enforceIssueTitle: boolean): Promise<void> {
+ const project = {
+ ...PROJECT_BASE,
+ enforceIssueTitle,
+ } as never;
+ await act(async () => {
+ root.render(
+ createElement(RequestRoleSheet, {
+ open: true,
+ project,
+ onClose: () => {},
+ })
+ );
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+}
+
+function getRoleInput(): HTMLInputElement {
+ return container.querySelector(
+ "[data-testid='role-select']"
+ ) as HTMLInputElement;
+}
+
+function getReasonTextarea(): HTMLTextAreaElement {
+ return container.querySelector("textarea") as HTMLTextAreaElement;
+}
+
+function getSubmitButton(): HTMLButtonElement {
+ return [...container.querySelectorAll("button")].find((b) =>
+ b.textContent?.includes("common.submit")
+ ) as HTMLButtonElement;
+}
+
+async function selectRole(role: string): Promise<void> {
+ await act(async () => {
+ nativeChange(getRoleInput(), role);
+ });
+}
+
+async function typeReason(text: string): Promise<void> {
+ await act(async () => {
+ nativeChange(getReasonTextarea(), text);
+ });
+}
+
+// Stub window.open — production handler opens the created issue in a new tab.
+beforeEach(() => {
+ vi.spyOn(window, "open").mockImplementation(() => null);
+});
+
+describe("RequestRoleSheet — enforceIssueTitle (BYT-9310)", () => {
+ it("Submit is enabled with empty reason when enforceIssueTitle is false", async () => {
+ await renderSheet(false);
+ await selectRole("roles/projectOwner");
+ await flush();
+
+ expect(getReasonTextarea().value).toBe("");
+ expect(getSubmitButton().disabled).toBe(false);
+ });
+
+ it("Submit is disabled until reason is typed when enforceIssueTitle is true", async () => {
+ await renderSheet(true);
+ await selectRole("roles/projectOwner");
+ await flush();
+
+ expect(getSubmitButton().disabled).toBe(true);
+
+ await typeReason("need access for oncall");
+ await flush();
+
+ expect(getSubmitButton().disabled).toBe(false);
+ });
+
+ it("title is `[request-role] <reason>` when enforceIssueTitle is true", async () => {
+ await renderSheet(true);
+ await selectRole("roles/projectOwner");
+ await typeReason("my reason");
+ await flush();
+
+ await act(async () => {
+ getSubmitButton().click();
+ });
+ await flush();
+
+ expect(mocks.createIssue).toHaveBeenCalledTimes(1);
+ const req = mocks.createIssue.mock.calls[0][0] as {
+ issue: { title: string };
+ };
+ expect(req.issue.title).toBe("[issue.title.request-role] my reason");
+ });
+
+ it("title uses request-specific-role auto-format when enforceIssueTitle is false", async () => {
+ await renderSheet(false);
+ await selectRole("roles/projectOwner");
+ // No reason typed — auto-title path.
+ await flush();
+
+ await act(async () => {
+ getSubmitButton().click();
+ });
+ await flush();
+
+ expect(mocks.createIssue).toHaveBeenCalledTimes(1);
+ const req = mocks.createIssue.mock.calls[0][0] as {
+ issue: { title: string };
+ };
+ // formatIssueTitle sentinel: mock wraps in FMT(...) so if the production
+ // code drops the formatIssueTitle() call, this assertion fails.
+ expect(req.issue.title).toBe("FMT(issue.title.request-specific-role)");
+ });
+});
diff --git a/frontend/src/react/pages/settings/RequestRoleSheet.tsx b/frontend/src/react/pages/settings/RequestRoleSheet.tsx
new file mode 100644
index 0000000000..6ce9b08462
--- /dev/null
+++ b/frontend/src/react/pages/settings/RequestRoleSheet.tsx
@@ -0,0 +1,547 @@
+import { create } from "@bufbuild/protobuf";
+import { DurationSchema } from "@bufbuild/protobuf/wkt";
+import dayjs from "dayjs";
+import { useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ roleHasDatabaseLimitation,
+ roleHasEnvironmentLimitation,
+} from "@/components/ProjectMember/utils";
+import { issueServiceClientConnect } from "@/connect";
+import type { ConditionGroupExpr, Factor, Operator } from "@/plugins/cel";
+import {
+ buildCELExpr,
+ emptySimpleExpr,
+ validateSimpleExpr,
+ wrapAsGroup,
+} from "@/plugins/cel";
+import { DatabaseResourceSelector as DatabaseResourceSelectorComponent } from "@/react/components/DatabaseResourceSelector";
+import { EnvironmentMultiSelect } from "@/react/components/EnvironmentMultiSelect";
+import type { OptionConfig } from "@/react/components/ExprEditor";
+import { ExprEditor } from "@/react/components/ExprEditor";
+import { IssueLabelSelect } from "@/react/components/IssueLabelSelect";
+import { RoleSelect } from "@/react/components/RoleSelect";
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+} from "@/react/components/ui/alert";
+import { Button } from "@/react/components/ui/button";
+import { ExpirationPicker } from "@/react/components/ui/expiration-picker";
+import {
+ Sheet,
+ SheetBody,
+ SheetContent,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from "@/react/components/ui/sheet";
+import { Textarea } from "@/react/components/ui/textarea";
+import { useVueState } from "@/react/hooks/useVueState";
+import { router } from "@/router";
+import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
+import { pushNotification, useCurrentUserV1, useSettingV1Store } from "@/store";
+import { type DatabaseResource, PresetRoleType } from "@/types";
+import { ExprSchema as ConditionExprSchema } from "@/types/proto-es/google/type/expr_pb";
+import {
+ CreateIssueRequestSchema,
+ Issue_Type,
+ IssueSchema,
+ RoleGrantSchema,
+} from "@/types/proto-es/v1/issue_service_pb";
+import type { Project } from "@/types/proto-es/v1/project_service_pb";
+import {
+ batchConvertParsedExprToCELString,
+ displayRoleTitle,
+ extractIssueUID,
+ extractProjectResourceName,
+ formatIssueTitle,
+ getDatabaseNameOptionConfig,
+ normalizeTitle,
+} from "@/utils";
+import {
+ CEL_ATTRIBUTE_RESOURCE_DATABASE,
+ CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME,
+ CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,
+} from "@/utils/cel-attributes";
+import {
+ buildConditionExpr,
+ stringifyConditionExpression,
+} from "@/utils/issue/cel";
+import type { DatabaseMode } from "./types";
+
+export interface RequestRoleSheetProps {
+ open: boolean;
+ project: Project;
+ onClose: () => void;
+}
+
+// i18n key lookup for the three DatabaseMode radio labels. Kept as a flat
+// function to avoid nested ternaries in the render tree.
+const databaseModeLabelKey = (mode: DatabaseMode): string => {
+ switch (mode) {
+ case "ALL":
+ return "issue.role-grant.all-databases";
+ case "EXPRESSION":
+ return "issue.role-grant.use-cel";
+ case "SELECT":
+ return "issue.role-grant.manually-select";
+ }
+};
+
+export function RequestRoleSheet(props: Readonly<RequestRoleSheetProps>) {
+ const { open, project, onClose } = props;
+ return (
+ <Sheet open={open} onOpenChange={(next) => !next && onClose()}>
+ <SheetContent width="standard">
+ {/* Base UI's Dialog.Portal unmounts after the close animation,
+ so the inner form mounts/unmounts with the Sheet's lifecycle
+ without needing an explicit {open && ...} guard. The `key`
+ forces a fresh mount if the project switches while open. */}
+ <RequestRoleForm key={project.name} {...props} />
+ </SheetContent>
+ </Sheet>
+ );
+}
+
+function RequestRoleForm({
+ project,
+ onClose,
+}: Readonly<Omit<RequestRoleSheetProps, "open">>) {
+ const { t } = useTranslation();
+ // Call the Pinia store accessor at the top level of the component so
+ // SonarCloud's React-hook-rule doesn't flag the `use*` call inside
+ // a subscription getter. `useCurrentUserV1()` returns a cached Pinia
+ // computed ref, so calling it once and reading `.value` inside the
+ // getter produces identical reactive semantics.
+ const currentUserRef = useCurrentUserV1();
+ const currentUser = useVueState(() => currentUserRef.value);
+ const [role, setRole] = useState("");
+ const [reason, setReason] = useState("");
+ const [expirationTimestamp, setExpirationTimestamp] = useState<
+ string | undefined
+ >(undefined);
+ const [labels, setLabels] = useState<string[]>([]);
+ // Role-scope fields — only rendered for roles that require them, but kept
+ // in state so switching roles back and forth preserves user input.
+ const [databaseMode, setDatabaseMode] = useState<DatabaseMode>("ALL");
+ const [databaseResources, setDatabaseResources] = useState<
+ DatabaseResource[]
+ >([]);
+ // CEL expression for EXPRESSION mode is held as a structured group so it
+ // can render in ExprEditor (matching the old Vue DatabaseResourceForm).
+ const [exprGroup, setExprGroup] = useState<ConditionGroupExpr>(() =>
+ wrapAsGroup(emptySimpleExpr())
+ );
+ const [environments, setEnvironments] = useState<string[]>([]);
+ const [submitting, setSubmitting] = useState(false);
+
+ const settingStore = useSettingV1Store();
+
+ // Workspace-configured maximum role expiration, in days. Matches the old
+ // Vue ExpirationSelector: PROJECT_OWNER grants are exempted (project
+ // owners can request unbounded expirations), otherwise the workspace cap
+ // applies. Returns undefined when no cap is set.
+ const maximumRoleExpirationDays = useVueState(() => {
+ if (role === PresetRoleType.PROJECT_OWNER) return undefined;
+ const seconds =
+ settingStore.workspaceProfile.maximumRoleExpiration?.seconds;
+ if (!seconds) return undefined;
+ return Math.floor(Number(seconds) / (60 * 60 * 24));
+ });
+
+ // ExprEditor factor/option config — mirrors the old Vue
+ // DatabaseResourceForm config for role-grant requests.
+ const factorList = useMemo<Factor[]>(
+ () => [
+ CEL_ATTRIBUTE_RESOURCE_DATABASE,
+ CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,
+ CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME,
+ ],
+ []
+ );
+ const factorOperatorOverrideMap = useMemo(
+ () =>
+ new Map<Factor, Operator[]>([
+ [CEL_ATTRIBUTE_RESOURCE_DATABASE, ["_==_", "@in"]],
+ [CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME, ["_==_"]],
+ [CEL_ATTRIBUTE_RESOURCE_TABLE_NAME, ["_==_", "@in"]],
+ ]),
+ []
+ );
+ const factorOptionConfigMap = useMemo(
+ () =>
+ factorList.reduce((map, factor) => {
+ if (factor === CEL_ATTRIBUTE_RESOURCE_DATABASE) {
+ map.set(factor, getDatabaseNameOptionConfig(project.name));
+ } else {
+ map.set(factor, { options: [] });
+ }
+ return map;
+ }, new Map<Factor, OptionConfig>()),
+ [factorList, project.name]
+ );
+
+ // Bind the datetime-local picker's min to the current minute so users
+ // can't silently pick a time earlier today and submit a zero-duration
+ // role grant.
+ const minDatetime = dayjs().format("YYYY-MM-DDTHH:mm");
+ const maxDatetime = maximumRoleExpirationDays
+ ? dayjs().add(maximumRoleExpirationDays, "days").format("YYYY-MM-DDTHH:mm")
+ : undefined;
+
+ const expirationIsInPast =
+ !!expirationTimestamp &&
+ dayjs(expirationTimestamp).unix() <= dayjs().unix();
+
+ // Workspace policy may cap role expiration; block submit when the picked
+ // timestamp would exceed that cap (matches Vue ExpirationSelector which
+ // disables over-cap dates in its picker).
+ const expirationExceedsMax =
+ !!expirationTimestamp &&
+ !!maximumRoleExpirationDays &&
+ dayjs(expirationTimestamp).isAfter(
+ dayjs().add(maximumRoleExpirationDays, "days")
+ );
+
+ const labelsMisconfigured =
+ project.forceIssueLabels && project.issueLabels.length === 0;
+
+ // Match the old Vue AddProjectMemberForm behavior: reason is only required
+ // when the project enforces issue titles (where the reason becomes the
+ // title). Otherwise the title is auto-generated and the reason is optional.
+ const reasonRequired = project.enforceIssueTitle;
+
+ // SQL-permission roles need a database scope (and sometimes an environment
+ // scope). Submitting without one produces a project-wide binding which is
+ // broader than the user typically intends.
+ const showDatabases = !!role && roleHasDatabaseLimitation(role);
+ const showEnvironments = !!role && roleHasEnvironmentLimitation(role);
+
+ const databaseScopeComplete =
+ !showDatabases ||
+ databaseMode === "ALL" ||
+ (databaseMode === "SELECT" && databaseResources.length > 0) ||
+ (databaseMode === "EXPRESSION" && validateSimpleExpr(exprGroup));
+
+ // When the workspace enforces a maximum role expiration, the user MUST
+ // pick an expiration — leaving it empty sends `roleGrant.expiration` as
+ // `undefined`, which the backend's approval runner treats as effectively
+ // unbounded (math.MaxInt32 days), bypassing the cap entirely.
+ const expirationRequired = maximumRoleExpirationDays !== undefined;
+
+ const canSubmit =
+ !submitting &&
+ !!role &&
+ (!reasonRequired || normalizeTitle(reason).length > 0) &&
+ (!expirationRequired || !!expirationTimestamp) &&
+ !expirationIsInPast &&
+ !expirationExceedsMax &&
+ !labelsMisconfigured &&
+ databaseScopeComplete &&
+ (!project.forceIssueLabels || labels.length > 0);
+
+ const handleSubmit = async () => {
+ if (!canSubmit) return;
+ setSubmitting(true);
+ try {
+ const trimmedReason = normalizeTitle(reason);
+ const expirationTimestampInMS = expirationTimestamp
+ ? dayjs(expirationTimestamp).valueOf()
+ : undefined;
+
+ // Only pass scope filters when the selected role actually requires
+ // them, matching EditMemberRoleDrawer's submit logic.
+ const scopedDatabaseResources =
+ showDatabases &&
+ databaseMode === "SELECT" &&
+ databaseResources.length > 0
+ ? databaseResources
+ : undefined;
+ const scopedEnvironments = showEnvironments ? environments : undefined;
+
+ // The backend uses two fields on the RoleGrant message:
+ // 1. `condition.expression` — CEL evaluated by
+ // UpdateProjectPolicyFromRoleGrantIssue to gate the resulting
+ // project IAM binding (access control).
+ // 2. `expiration` — Duration consumed by
+ // backend/runner/approval/runner.go (request.expiration_days) to
+ // route the approval chain; unset defaults to math.MaxInt32 days.
+ // Both must be populated — the condition controls what the grant
+ // allows, the expiration controls which approvers review it.
+ let condition;
+ if (showDatabases && databaseMode === "EXPRESSION") {
+ // Convert the structured ExprEditor group to a raw CEL string and
+ // combine it with any environment/expiration clauses. Mirrors
+ // ProjectMaskingExemptionCreatePage's EXPRESSION-mode submit path.
+ const parsedExpr = await buildCELExpr(exprGroup);
+ if (!parsedExpr) {
+ throw new Error("failed to build CEL expression");
+ }
+ const [exprString] = await batchConvertParsedExprToCELString([
+ parsedExpr,
+ ]);
+ // `batchConvertParsedExprToCELString` swallows deparse errors and
+ // returns an empty string on failure. Submitting anyway would
+ // silently drop the database scope filter and produce a broader
+ // grant than the user requested — refuse instead and surface an
+ // error so the user can retry.
+ if (!exprString?.trim()) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("project.members.request-role.failed-to-build-expression"),
+ });
+ return;
+ }
+ const extraParts = stringifyConditionExpression({
+ expirationTimestampInMS,
+ environments: scopedEnvironments,
+ });
+ const fullExpression = extraParts
+ ? `(${exprString}) && ${extraParts}`
+ : exprString;
+ condition = create(ConditionExprSchema, {
+ expression: fullExpression,
+ description: trimmedReason,
+ });
+ } else {
+ condition = buildConditionExpr({
+ role,
+ description: trimmedReason,
+ expirationTimestampInMS,
+ databaseResources: scopedDatabaseResources,
+ environments: scopedEnvironments,
+ });
+ }
+
+ const expiration = expirationTimestamp
+ ? create(DurationSchema, {
+ seconds: BigInt(
+ Math.max(0, dayjs(expirationTimestamp).unix() - dayjs().unix())
+ ),
+ })
+ : undefined;
+
+ const roleGrant = create(RoleGrantSchema, {
+ role,
+ user: `users/${currentUser.email}`,
+ condition,
+ expiration,
+ });
+
+ // Collect the scoped database names so the auto-generated title shows
+ // `[db1]` / `[N databases]` instead of defaulting to `[All databases]`
+ // — matches the old Vue RoleGrantPanel behavior. EXPRESSION mode
+ // currently falls through to `[All databases]` since parsing CEL back
+ // into concrete database names would require an async round-trip.
+ const titleDatabaseNames =
+ scopedDatabaseResources && scopedDatabaseResources.length > 0
+ ? [...new Set(scopedDatabaseResources.map((r) => r.databaseFullName))]
+ : undefined;
+
+ // When the project enforces issue titles, the user-provided reason is
+ // treated as the title (matching the old Vue RoleGrantPanel behavior).
+ const title = project.enforceIssueTitle
+ ? `[${t("issue.title.request-role")}] ${trimmedReason}`
+ : formatIssueTitle(
+ t("issue.title.request-specific-role", {
+ role: displayRoleTitle(role),
+ }),
+ titleDatabaseNames
+ );
+
+ const newIssue = create(IssueSchema, {
+ title,
+ description: trimmedReason,
+ type: Issue_Type.ROLE_GRANT,
+ roleGrant,
+ labels,
+ });
+ const response = await issueServiceClientConnect.createIssue(
+ create(CreateIssueRequestSchema, {
+ parent: project.name,
+ issue: newIssue,
+ })
+ );
+ const route = router.resolve({
+ name: PROJECT_V1_ROUTE_ISSUE_DETAIL,
+ params: {
+ projectId: extractProjectResourceName(response.name),
+ issueId: extractIssueUID(response.name),
+ },
+ });
+ window.open(route.fullPath, "_blank", "noopener,noreferrer");
+ onClose();
+ } catch {
+ // Error notification is pushed by the client middleware.
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ const showLabelSelect =
+ project.issueLabels.length > 0 || project.forceIssueLabels;
+
+ return (
+ <>
+ <SheetHeader>
+ <SheetTitle>{t("issue.title.request-role")}</SheetTitle>
+ </SheetHeader>
+ <SheetBody>
+ <div className="flex flex-col gap-y-4">
+ {labelsMisconfigured && (
+ <Alert variant="warning">
+ <AlertTitle>
+ {t("project.members.request-role.labels-misconfigured.title")}
+ </AlertTitle>
+ <AlertDescription>
+ {t(
+ "project.members.request-role.labels-misconfigured.description"
+ )}
+ </AlertDescription>
+ </Alert>
+ )}
+ <div className="flex flex-col gap-y-1">
+ <label className="text-sm font-medium">
+ {t("common.role.self")}
+ <span className="text-error ml-0.5">*</span>
+ </label>
+ <RoleSelect
+ scope="project"
+ multiple={false}
+ value={role ? [role] : []}
+ onChange={(roles) => {
+ setRole(roles[0] ?? "");
+ // Reset scope when switching roles since DB/env fields only
+ // apply to some roles and the new role may not use them.
+ setDatabaseMode("ALL");
+ setDatabaseResources([]);
+ setExprGroup(wrapAsGroup(emptySimpleExpr()));
+ setEnvironments([]);
+ }}
+ />
+ </div>
+ <div className="flex flex-col gap-y-1">
+ <label className="text-sm font-medium">
+ {t("common.reason")}
+ {reasonRequired && <span className="text-error ml-0.5">*</span>}
+ </label>
+ <Textarea
+ value={reason}
+ onChange={(e) => setReason(e.target.value)}
+ placeholder={t("common.reason")}
+ rows={3}
+ />
+ </div>
+ {showDatabases && (
+ <div className="flex flex-col gap-y-2">
+ <label className="text-sm font-medium">
+ {t("common.databases")}
+ <span className="text-error ml-0.5">*</span>
+ </label>
+ <div className="flex items-center gap-x-4">
+ {(["ALL", "EXPRESSION", "SELECT"] as DatabaseMode[]).map(
+ (m) => (
+ <label
+ key={m}
+ className="flex items-center gap-x-2 text-sm cursor-pointer"
+ >
+ <input
+ type="radio"
+ name="request-role-db-mode"
+ checked={databaseMode === m}
+ onChange={() => {
+ setDatabaseMode(m);
+ setDatabaseResources([]);
+ setExprGroup(wrapAsGroup(emptySimpleExpr()));
+ }}
+ />
+ {t(databaseModeLabelKey(m))}
+ </label>
+ )
+ )}
+ </div>
+ {databaseMode === "EXPRESSION" && (
+ <ExprEditor
+ expr={exprGroup}
+ factorList={factorList}
+ optionConfigMap={factorOptionConfigMap}
+ factorOperatorOverrideMap={factorOperatorOverrideMap}
+ onUpdate={setExprGroup}
+ />
+ )}
+ {databaseMode === "SELECT" && (
+ <DatabaseResourceSelectorComponent
+ projectName={project.name}
+ value={databaseResources}
+ onChange={setDatabaseResources}
+ />
+ )}
+ </div>
+ )}
+ {showEnvironments && (
+ <div className="flex flex-col gap-y-1">
+ <label className="text-sm font-medium">
+ {t("common.environments")}
+ </label>
+ <EnvironmentMultiSelect
+ value={environments}
+ onChange={setEnvironments}
+ />
+ </div>
+ )}
+ <div className="flex flex-col gap-y-1">
+ <label className="text-sm font-medium">
+ {t("common.expiration")}
+ {expirationRequired && (
+ <span className="text-error ml-0.5">*</span>
+ )}
+ </label>
+ <ExpirationPicker
+ value={expirationTimestamp}
+ onChange={setExpirationTimestamp}
+ minDate={minDatetime}
+ maxDate={maxDatetime}
+ />
+ {maximumRoleExpirationDays !== undefined && (
+ <p className="text-xs text-control-light">
+ {t("project.members.request-role.max-expiration-hint", {
+ days: maximumRoleExpirationDays,
+ })}
+ </p>
+ )}
+ {expirationIsInPast && (
+ <p className="text-xs text-error">
+ {t("project.members.request-role.expiration-must-be-future")}
+ </p>
+ )}
+ {expirationExceedsMax && (
+ <p className="text-xs text-error">
+ {t("project.members.request-role.expiration-exceeds-max", {
+ days: maximumRoleExpirationDays,
+ })}
+ </p>
+ )}
+ </div>
+ {showLabelSelect && (
+ <IssueLabelSelect
+ labels={project.issueLabels}
+ selected={labels}
+ required={project.forceIssueLabels}
+ onChange={setLabels}
+ />
+ )}
+ </div>
+ </SheetBody>
+ <SheetFooter>
+ <Button variant="outline" onClick={onClose} disabled={submitting}>
+ {t("common.cancel")}
+ </Button>
+ <Button disabled={!canSubmit} onClick={handleSubmit}>
+ {t("common.submit")}
+ </Button>
+ </SheetFooter>
+ </>
+ );
+}
diff --git a/frontend/src/react/pages/settings/types.ts b/frontend/src/react/pages/settings/types.ts
new file mode 100644
index 0000000000..b0d1ec891d
--- /dev/null
+++ b/frontend/src/react/pages/settings/types.ts
@@ -0,0 +1 @@
+export type DatabaseMode = "ALL" | "EXPRESSION" | "SELECT";
diff --git a/frontend/src/react/test-utils/nativeChange.ts b/frontend/src/react/test-utils/nativeChange.ts
new file mode 100644
index 0000000000..aca137d1c0
--- /dev/null
+++ b/frontend/src/react/test-utils/nativeChange.ts
@@ -0,0 +1,25 @@
+/**
+ * Fire a React-compatible change event on an input or textarea element.
+ *
+ * React 18 tracks input value mutations via the native prototype descriptor
+ * setter rather than by diffing the DOM value attribute. Dispatching a plain
+ * `input`/`change` Event without first setting the value through the descriptor
+ * means React never sees the new value and the `onChange` handler never fires.
+ *
+ * This helper applies the descriptor setter trick so that React's synthetic
+ * event system correctly receives the new value — this is NOT optional in
+ * React 18 when driving inputs via raw DOM events without @testing-library/react.
+ */
+export function nativeChange(
+ el: HTMLInputElement | HTMLTextAreaElement,
+ value: string
+): void {
+ const proto =
+ el instanceof HTMLTextAreaElement
+ ? HTMLTextAreaElement.prototype
+ : HTMLInputElement.prototype;
+ const descriptor = Object.getOwnPropertyDescriptor(proto, "value");
+ descriptor?.set?.call(el, value);
+ el.dispatchEvent(new Event("input", { bubbles: true }));
+ el.dispatchEvent(new Event("change", { bubbles: true }));
+}
diff --git a/frontend/src/utils/string.test.ts b/frontend/src/utils/string.test.ts
new file mode 100644
index 0000000000..fea151cade
--- /dev/null
+++ b/frontend/src/utils/string.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from "vitest";
+
+import { normalizeTitle } from "./string";
+
+describe("normalizeTitle", () => {
+ it("trims plain ASCII whitespace", () => {
+ expect(normalizeTitle(" hello ")).toBe("hello");
+ });
+
+ it("trims U+0085 (NEXT LINE)", () => {
+ expect(normalizeTitle("\u0085")).toBe("");
+ expect(normalizeTitle("\u0085hello\u0085")).toBe("hello");
+ });
+
+ it("trims U+00A0 (NBSP)", () => {
+ expect(normalizeTitle("\u00A0\u00A0")).toBe("");
+ });
+
+ it("trims U+3000 (ideographic space)", () => {
+ expect(normalizeTitle("\u3000hello\u3000")).toBe("hello");
+ });
+
+ it("preserves internal whitespace", () => {
+ expect(normalizeTitle(" hello world ")).toBe("hello world");
+ });
+
+ it("returns empty string for empty input", () => {
+ expect(normalizeTitle("")).toBe("");
+ });
+
+ it("does NOT trim U+FEFF (BOM) — Go unicode.IsSpace leaves it intact", () => {
+ // Go's `unicode.IsSpace` does not classify U+FEFF as whitespace, so the
+ // frontend must not trim it either. If someone "helpfully" re-adds
+ // U+FEFF to the regex, this test fails — preventing a frontend/backend
+ // asymmetry in the opposite direction.
+ expect(normalizeTitle("\uFEFF")).toBe("\uFEFF");
+ });
+});
diff --git a/frontend/src/utils/string.ts b/frontend/src/utils/string.ts
index ad18a3030d..bd59dc5766 100644
--- a/frontend/src/utils/string.ts
+++ b/frontend/src/utils/string.ts
@@ -1,3 +1,33 @@
export const escapeMarkdown = (md: string): string => {
return md.replaceAll(/[*_~\-#`[\]()\\]/g, (ch) => `\\${ch}`);
};
+
+// Matches the Go `strings.TrimSpace` / `unicode.IsSpace` predicate so that
+// the frontend's empty-title decision agrees with the backend.
+//
+// We intentionally do NOT use JS `\s` here: ECMAScript's `\s` matches
+// `U+FEFF` (ZERO WIDTH NO-BREAK SPACE / BOM), but Go's `unicode.IsSpace`
+// does NOT — so `\s` alone would trim BOM on the frontend while the
+// backend preserved it, re-introducing the very asymmetry this helper
+// exists to close.
+//
+// The character class below enumerates exactly the code points
+// `unicode.IsSpace` treats as whitespace: ASCII whitespace
+// (`\t`, `\n`, `\v`, `\f`, `\r`, space), `U+0085` (NEXT LINE),
+// `U+00A0` (NBSP), `U+1680` (OGHAM SPACE MARK), `U+2000`–`U+200A`,
+// `U+2028` (LINE SEPARATOR), `U+2029` (PARAGRAPH SEPARATOR),
+// `U+202F` (NARROW NO-BREAK SPACE), `U+205F` (MEDIUM MATHEMATICAL SPACE),
+// and `U+3000` (IDEOGRAPHIC SPACE). No `U+FEFF` — see negative test in
+// `string.test.ts` that locks this invariant.
+//
+// Use this helper everywhere the frontend decides "is this title empty /
+// is Create allowed / should the fallback fire".
+const UNICODE_WHITESPACE_CLASS =
+ "\\t\\n\\v\\f\\r \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000";
+const UNICODE_WHITESPACE = new RegExp(
+ `^[${UNICODE_WHITESPACE_CLASS}]+|[${UNICODE_WHITESPACE_CLASS}]+$`,
+ "g"
+);
+
+export const normalizeTitle = (title: string): string =>
+ title.replace(UNICODE_WHITESPACE, "");
diff --git a/frontend/src/views/sql-editor/EditorCommon/ExecuteHint.vue b/frontend/src/views/sql-editor/EditorCommon/ExecuteHint.vue
index b9cad6dc62..d5b2c579b6 100644
--- a/frontend/src/views/sql-editor/EditorCommon/ExecuteHint.vue
+++ b/frontend/src/views/sql-editor/EditorCommon/ExecuteHint.vue
@@ -45,15 +45,18 @@ import { v4 as uuidv4 } from "uuid";
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
+import { applyPlanTitleToQuery } from "@/components/Plan/logic/title";
import { EnvironmentV1Name } from "@/components/v2";
import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";
import {
+ useDatabaseV1Store as databaseV1Store,
+ useProjectV1Store as projectV1Store,
pushNotification,
- useDatabaseV1Store,
+ useStorageStore as storageStoreAccessor,
useSQLEditorStore,
useSQLEditorTabStore,
- useStorageStore,
} from "@/store";
+import { unknownProject } from "@/types";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import {
extractDatabaseResourceName,
@@ -77,6 +80,14 @@ const router = useRouter();
const { t } = useI18n();
const tabStore = useSQLEditorTabStore();
const editorStore = useSQLEditorStore();
+// Store accessors imported under non-`use*` aliases so SonarCloud's
+// React-hook-rule (typescript:S6440) doesn't misfire on these Pinia
+// calls in a Vue SFC. Pinia stores are module-level singletons; the
+// accessor name is cosmetic. Kept consistent across ExecuteHint.vue
+// and SQLEditorHomePage.vue.
+const databaseStore = databaseV1Store();
+const projectStore = projectV1Store();
+const storageStore = storageStoreAccessor();
const statement = computed(() => {
const tab = tabStore.currentTab;
@@ -126,24 +137,38 @@ const gotoCreateIssue = async () => {
pushNotification({
module: "bytebase",
style: "CRITICAL",
- title: "No database selected",
+ title: t("sql-editor.no-database-selected"),
});
return;
}
emit("close");
- const db = await useDatabaseV1Store().getOrFetchDatabaseByName(database);
+ const db = await databaseStore.getOrFetchDatabaseByName(database);
+ // Project-fetch-failed cell: if the project lookup rejects (transient
+ // network/permission failure), still open the plan page using the
+ // already-known `db.project`. Fall back to `unknownProject()` which
+ // has `enforceIssueTitle=true` — that is the safe governance default:
+ // the launcher drops `query.name` so the plan page opens with a blank
+ // title and the user types a deliberate one before submitting. Backend
+ // remains the source of truth on submit.
+ const project = await projectStore
+ .getOrFetchProjectByName(db.project)
+ .catch(() => unknownProject());
const sqlStorageKey = `bb.issues.sql.${uuidv4()}`;
- useStorageStore().put(sqlStorageKey, statement.value);
+ storageStore.put(sqlStorageKey, statement.value);
const { databaseName } = extractDatabaseResourceName(db.name);
- const query = {
+ const query: Record<string, string> = {
template: "bb.plan.change-database",
- name: `[${databaseName}] Change from SQL Editor`,
databaseList: db.name,
sqlStorageKey,
};
+ applyPlanTitleToQuery(
+ query,
+ project,
+ () => `[${databaseName}] ${t("issue.title.change-from-sql-editor")}`
+ );
const route = router.resolve({
name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
diff --git a/frontend/src/views/sql-editor/SQLEditorHomePage.vue b/frontend/src/views/sql-editor/SQLEditorHomePage.vue
index a2594a6002..927b144384 100644
--- a/frontend/src/views/sql-editor/SQLEditorHomePage.vue
+++ b/frontend/src/views/sql-editor/SQLEditorHomePage.vue
@@ -65,17 +65,25 @@ import { useWindowSize } from "@vueuse/core";
import { NSplit } from "naive-ui";
import { storeToRefs } from "pinia";
import { computed, reactive } from "vue";
+// useI18n imported under a non-`use*` alias so SonarCloud's React-hook-
+// rule (typescript:S6440) doesn't misfire on this Vue composable called
+// at <script setup> top level. Consistent with the projectV1Store alias
+// workaround already in this file. See fd2aca60bf for the pattern.
+import { useI18n as vueI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import IAMRemindModal from "@/components/IAMRemindModal.vue";
+import { applyPlanTitleToQuery } from "@/components/Plan/logic/title";
import Quickstart from "@/components/Quickstart.vue";
import { Drawer } from "@/components/v2";
import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";
import {
+ useProjectV1Store as projectV1Store,
useDatabaseV1Store,
useSQLEditorStore,
useSQLEditorTabStore,
} from "@/store";
+import { unknownProject } from "@/types";
import {
extractDatabaseResourceName,
extractProjectResourceName,
@@ -98,7 +106,13 @@ const state = reactive<LocalState>({
});
const router = useRouter();
+const { t } = vueI18n();
const databaseStore = useDatabaseV1Store();
+// projectStore accessor imported under a non-`use*` alias so SonarCloud's
+// React-hook-rule (typescript:S6440) doesn't misfire on this new Pinia
+// call in a Vue SFC. Consistent with the same workaround in
+// ExecuteHint.vue. Pinia stores are module-level singletons.
+const projectStore = projectV1Store();
const tabStore = useSQLEditorTabStore();
const editorStore = useSQLEditorStore();
@@ -119,6 +133,14 @@ useEmitteryEventListener(
"alter-schema",
async ({ databaseName, schema, table }) => {
const database = await databaseStore.getOrFetchDatabaseByName(databaseName);
+ // Project-fetch-failed cell: if the project lookup rejects, still
+ // launch the plan page using the known `database.project`. Fall back
+ // to `unknownProject()` (enforceIssueTitle=true) — the launcher
+ // drops `query.name` so the user types a deliberate title before
+ // submitting. Backend remains the source of truth on submit.
+ const project = await projectStore
+ .getOrFetchProjectByName(database.project)
+ .catch(() => unknownProject());
const exampleSQL = ["ALTER TABLE"];
if (table) {
if (schema) {
@@ -128,12 +150,16 @@ useEmitteryEventListener(
}
}
const { databaseName: dbName } = extractDatabaseResourceName(database.name);
- const query = {
+ const query: Record<string, string> = {
template: "bb.plan.change-database",
- name: `[${dbName}] Edit schema`,
databaseList: database.name,
sql: exampleSQL.join(" "),
};
+ applyPlanTitleToQuery(
+ query,
+ project,
+ () => `[${dbName}] ${t("issue.title.edit-schema")}`
+ );
const route = router.resolve({
name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
params: {