Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor(frontend): clean up legacy Vue project pages (#20116)
boojack7b06ec89857e
diff --git a/frontend/src/App.vue b/frontend/src/App.vueindex ae6bc96559..94954d72ab 100644--- a/frontend/src/App.vue+++ b/frontend/src/App.vue@@ -46,6 +46,10 @@ import OverlayStackManager from "./components/misc/OverlayStackManager.vue";import { overrideAppProfile } from "./customAppProfile";import NotificationContext from "./NotificationContext.vue";import { locale, t } from "./plugins/i18n";+import {+ type ReactQuickstartResetDetail,+ ReactShellBridgeEvent,+} from "./react/shell-bridge";import { useNotificationStore, useUIStateStore } from "./store";import { isDev, setDocumentTitle } from "./utils";@@ -68,7 +72,7 @@ const handleReactLocaleChange = (event: Event) => {};const handleReactQuickstartReset = (event: Event) => {- const keys = (event as CustomEvent<{ keys?: unknown }>).detail?.keys;+ const keys = (event as CustomEvent<ReactQuickstartResetDetail>).detail?.keys;if (!Array.isArray(keys)) {return;}@@ -85,17 +89,23 @@ const handleReactQuickstartReset = (event: Event) => {};onMounted(() => {- window.addEventListener("bb.react-locale-change", handleReactLocaleChange);window.addEventListener(- "bb.react-quickstart-reset",+ ReactShellBridgeEvent.localeChange,+ handleReactLocaleChange+ );+ window.addEventListener(+ ReactShellBridgeEvent.quickstartReset,handleReactQuickstartReset);});onUnmounted(() => {- window.removeEventListener("bb.react-locale-change", handleReactLocaleChange);window.removeEventListener(- "bb.react-quickstart-reset",+ ReactShellBridgeEvent.localeChange,+ handleReactLocaleChange+ );+ window.removeEventListener(+ ReactShellBridgeEvent.quickstartReset,handleReactQuickstartReset);});diff --git a/frontend/src/NotificationContext.vue b/frontend/src/NotificationContext.vueindex 0c64697855..ba1432d671 100644--- a/frontend/src/NotificationContext.vue+++ b/frontend/src/NotificationContext.vue@@ -5,6 +5,7 @@<script setup lang="ts">import { useNotification } from "naive-ui";import { h, onMounted, onUnmounted, watchEffect } from "vue";+import { ReactShellBridgeEvent } from "@/react/shell-bridge";import { useNotificationStore } from "@/store";import type { BBNotificationStyle, NotificationCreate } from "@/types";@@ -96,9 +97,15 @@ const handleReactNotification = (event: Event) => {watchEffect(watchNotification);onMounted(() => {- window.addEventListener("bb.react-notification", handleReactNotification);+ window.addEventListener(+ ReactShellBridgeEvent.notification,+ handleReactNotification+ );});onUnmounted(() => {- window.removeEventListener("bb.react-notification", handleReactNotification);+ window.removeEventListener(+ ReactShellBridgeEvent.notification,+ handleReactNotification+ );});</script>diff --git a/frontend/src/components/DatabaseDetail/ExportSchemaButton.vue b/frontend/src/components/DatabaseDetail/ExportSchemaButton.vuedeleted file mode 100644index e066ba9c9c..0000000000--- a/frontend/src/components/DatabaseDetail/ExportSchemaButton.vue+++ /dev/null@@ -1,124 +0,0 @@-<template>- <PermissionGuardWrapper- v-if="available"- v-slot="slotProps"- :project="getDatabaseProject(database)"- :permissions="['bb.databases.getSchema']"- >- <div>- <NDropdown- :options="exportOptions"- :disabled="slotProps.disabled"- @select="handleExportFormat"- trigger="hover"- >- <NButton :loading="exporting">- {{ $t("database.export-schema") }}- </NButton>- </NDropdown>- </div>- </PermissionGuardWrapper>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { ConnectError } from "@connectrpc/connect";-import { NButton, NDropdown } from "naive-ui";-import { computed, ref } from "vue";-import { useI18n } from "vue-i18n";-import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";-import { databaseServiceClientConnect } from "@/connect";-import { pushNotification } from "@/store";-import { isValidDatabaseName } from "@/types";-import type { Database } from "@/types/proto-es/v1/database_service_pb";-import {- GetDatabaseSDLSchemaRequest_SDLFormat,- GetDatabaseSDLSchemaRequestSchema,-} from "@/types/proto-es/v1/database_service_pb";-import { extractDatabaseResourceName, getDatabaseProject } from "@/utils";--const props = defineProps<{- database: Database;-}>();--const exporting = ref(false);-const { t } = useI18n();--const available = computed(() => {- return isValidDatabaseName(props.database.name);-});--const exportOptions = computed(() => [- {- label: t("database.export-schema-single-file"),- key: "single",- },- {- label: t("database.export-schema-multi-file"),- key: "multi",- },-]);--const handleExportFormat = (key: string) => {- if (key === "single") {- exportSchema(GetDatabaseSDLSchemaRequest_SDLFormat.SINGLE_FILE);- } else if (key === "multi") {- exportSchema(GetDatabaseSDLSchemaRequest_SDLFormat.MULTI_FILE);- }-};--const exportSchema = async (format: GetDatabaseSDLSchemaRequest_SDLFormat) => {- exporting.value = true;-- try {- const request = create(GetDatabaseSDLSchemaRequestSchema, {- name: `${props.database.name}/sdlSchema`,- format,- });-- const response =- await databaseServiceClientConnect.getDatabaseSDLSchema(request);-- const { databaseName } = extractDatabaseResourceName(props.database.name);- let filename: string;- let blob: Blob;-- // Check the content type to determine how to handle the response- if (response.contentType.includes("application/zip")) {- // Multi-file format - ZIP archive- filename = `${databaseName}_schema.zip`;- // Create a proper ArrayBuffer by slicing- const arrayBuffer = response.schema.slice().buffer;- blob = new Blob([arrayBuffer], { type: "application/zip" });- } else {- // Single file format - text file- filename = `${databaseName}_schema.sql`;- const content = new TextDecoder().decode(response.schema);- blob = new Blob([content], { type: "text/plain" });- }-- const downloadLink = document.createElement("a");- downloadLink.href = URL.createObjectURL(blob);- downloadLink.download = filename;- document.body.appendChild(downloadLink);- downloadLink.click();- document.body.removeChild(downloadLink);- URL.revokeObjectURL(downloadLink.href);-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("database.successfully-exported-schema"),- });- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("database.failed-to-export-schema"),- description: (error as ConnectError).message,- });- } finally {- exporting.value = false;- }-};-</script>diff --git a/frontend/src/components/DatabaseDetail/SQLEditorButtonV1.vue b/frontend/src/components/DatabaseDetail/SQLEditorButtonV1.vuedeleted file mode 100644index 92f3ce4ec0..0000000000--- a/frontend/src/components/DatabaseDetail/SQLEditorButtonV1.vue+++ /dev/null@@ -1,115 +0,0 @@-<template>- <NTooltip :disabled="!showTooltip">- <template #trigger>- <div- class="flex items-center text-sm"- :class="classes"- v-bind="$attrs"- @click.stop.prevent="gotoSQLEditor"- >- <span v-if="label" class="mr-1">{{ $t("sql-editor.self") }}</span>- <heroicons-solid:terminal class="w-5 h-5" />- </div>- </template>-- <div class="whitespace-nowrap">- {{ $t("sql-editor.self") }}- </div>- </NTooltip>-</template>--<script lang="ts" setup>-import { NTooltip } from "naive-ui";-import { computed } from "vue";-import { useRouter } from "vue-router";-import { SQL_EDITOR_DATABASE_MODULE } from "@/router/sqlEditor";-import { defaultProject, isDefaultProject } from "@/types";-import type { Database } from "@/types/proto-es/v1/database_service_pb";-import type { VueClass } from "@/utils";-import {- extractDatabaseResourceName,- extractInstanceResourceName,- extractProjectResourceName,- hasProjectPermissionV2,- isSQLEditorRoute,-} from "@/utils";--const props = withDefaults(- defineProps<{- database: Database;- table?: string;- schema?: string;- label?: boolean;- disabled?: boolean;- tooltip?: boolean;- class?: VueClass;- }>(),- {- label: false,- disabled: false,- tooltip: false,- class: undefined,- table: undefined,- schema: undefined,- }-);--const emit = defineEmits<{- (name: "failed", database: Database): void;-}>();--const router = useRouter();--const disabled = computed(() => props.disabled || !props.database);--const showTooltip = computed((): boolean => {- return !props.disabled && props.tooltip;-});--const classes = computed(() => {- const classes: string[] = [];- if (props.disabled) {- classes.push("text-gray-400");- } else {- classes.push("textlabel", "cursor-pointer", "hover:text-accent");- }- return [...classes, props.class];-});--const gotoSQLEditor = () => {- if (disabled.value) {- return;- }-- const database = props.database;- if (isDefaultProject(database.project)) {- if (- !hasProjectPermissionV2(defaultProject(database.project), "bb.sql.select")- ) {- // For unassigned databases, only high-privileged users- // are accessible via SQL Editor.- emit("failed", database);- return;- }- }-- const { instance, databaseName } = extractDatabaseResourceName(database.name);- const route = router.resolve({- name: SQL_EDITOR_DATABASE_MODULE,- params: {- project: extractProjectResourceName(database.project),- instance: extractInstanceResourceName(instance),- database: databaseName,- },- query: {- table: props.table ? props.table : undefined,- schema: props.schema ? props.schema : undefined,- },- });- if (isSQLEditorRoute(router)) {- router.push(route);- } else {- window.open(route.fullPath);- }-};-</script>diff --git a/frontend/src/components/DatabaseDetail/SchemaDiagramButton.vue b/frontend/src/components/DatabaseDetail/SchemaDiagramButton.vuedeleted file mode 100644index 2576625acd..0000000000--- a/frontend/src/components/DatabaseDetail/SchemaDiagramButton.vue+++ /dev/null@@ -1,49 +0,0 @@-<template>- <div- class="flex items-center text-sm textlabel cursor-pointer hover:text-accent"- v-bind="$attrs"- @click.stop.prevent="openModal"- >- <span class="mr-1">{{ $t("schema-diagram.self") }}</span>- <SchemaDiagramIcon />- </div>-- <BBModal- v-if="open"- :title="$t('schema-diagram.self')"- class="h-[calc(100vh-40px)] max-h-[calc(100vh-40px)]!"- header-class="border-0!"- container-class="flex-1 pt-0!"- @close="open = false"- >- <div class="w-[80vw] h-full">- <SchemaDiagram- :database="database"- :database-metadata="dbSchemaStore.getDatabaseMetadata(database.name)"- />- </div>- </BBModal>-</template>--<script setup lang="ts">-import { ref } from "vue";-import { BBModal } from "@/bbkit";-import { SchemaDiagram, SchemaDiagramIcon } from "@/components/SchemaDiagram";-import { useDBSchemaV1Store } from "@/store";-import type { Database } from "@/types/proto-es/v1/database_service_pb";--const props = defineProps<{- database: Database;-}>();--const open = ref<boolean>(false);-const dbSchemaStore = useDBSchemaV1Store();--const openModal = async () => {- await dbSchemaStore.getOrFetchDatabaseMetadata({- database: props.database.name,- skipCache: false,- });- open.value = true;-};-</script>diff --git a/frontend/src/components/DatabaseDetail/Settings/DatabaseSettingsPanel.vue b/frontend/src/components/DatabaseDetail/Settings/DatabaseSettingsPanel.vuedeleted file mode 100644index 09767ec162..0000000000--- a/frontend/src/components/DatabaseDetail/Settings/DatabaseSettingsPanel.vue+++ /dev/null@@ -1,86 +0,0 @@-<template>- <div class="divide-y">- <div class="flex flex-col gap-y-4 pb-7">- <div>- <p class="text-lg font-medium leading-7 text-main">- {{ $t("common.environment") }}- </p>- <EnvironmentSelect- class="mt-1 max-w-md"- :value="environmentSelectValue"- :disabled="!allowUpdateDatabase"- :clearable="!getInstanceResource(database).environment"- :render-suffix="- (env: Environment) =>- getInstanceResource(database).environment === env.name- ? `(${$t('common.default')})`- : ''- "- @update:value="handleSelectEnvironment($event as (string | undefined))"- />- </div>- </div>- <Labels- :database="database"- :allow-edit="allowUpdateDatabase"- class="pt-7"- />- </div>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";-import { cloneDeep } from "lodash-es";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import { EnvironmentSelect } from "@/components/v2";-import { pushNotification, useDatabaseV1Store } from "@/store";-import type { Database } from "@/types/proto-es/v1/database_service_pb";-import { UpdateDatabaseRequestSchema } from "@/types/proto-es/v1/database_service_pb";-import type { Environment } from "@/types/v1/environment";-import {- getDatabaseProject,- getInstanceResource,- hasProjectPermissionV2,-} from "@/utils";-import Labels from "./components/Labels.vue";--const props = defineProps<{- database: Database;-}>();--const databaseStore = useDatabaseV1Store();-const { t } = useI18n();--const environmentSelectValue = computed(- () => props.database.effectiveEnvironment || undefined-);--const allowUpdateDatabase = computed(() =>- hasProjectPermissionV2(- getDatabaseProject(props.database),- "bb.databases.update"- )-);--const handleSelectEnvironment = async (name: string | undefined) => {- if (name === props.database.effectiveEnvironment) {- return;- }- const databasePatch = cloneDeep(props.database);- databasePatch.environment = name ?? "";-- await databaseStore.updateDatabase(- create(UpdateDatabaseRequestSchema, {- database: databasePatch,- updateMask: create(FieldMaskSchema, { paths: ["environment"] }),- })- );- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });-};-</script>diff --git a/frontend/src/components/DatabaseDetail/Settings/components/Labels.vue b/frontend/src/components/DatabaseDetail/Settings/components/Labels.vuedeleted file mode 100644index 301c2eb1b5..0000000000--- a/frontend/src/components/DatabaseDetail/Settings/components/Labels.vue+++ /dev/null@@ -1,123 +0,0 @@-<template>- <div class="flex flex-col gap-y-4">- <div class="flex items-center">- <div class="flex-1">- <div class="flex items-center">- <p class="text-lg font-medium leading-7 text-main flex">- {{ $t("database.labels") }}- </p>- </div>- </div>- </div>- <div>- <LabelListEditor- ref="labelListEditorRef"- v-model:kv-list="state.kvList"- :readonly="!allowEdit"- :show-errors="dirty"- class="max-w-120"- />- </div>- <div v-if="dirty" class="flex flex-row justify-end items-center gap-x-3">- <NButton @click="handleCancel">- {{ $t("common.revert") }}- </NButton>- <NButton- :disabled="!allowSave || state.isUpdating"- :loading="state.isUpdating"- type="primary"- @click="handleSave"- >- {{ $t("common.save") }}- </NButton>- </div>- </div>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { isEqual } from "lodash-es";-import { NButton } from "naive-ui";-import { computed, reactive, ref, watch } from "vue";-import { useI18n } from "vue-i18n";-import { LabelListEditor } from "@/components/Label/";-import { pushNotification, useDatabaseV1Store } from "@/store";-import type { Database } from "@/types/proto-es/v1/database_service_pb";-import { UpdateDatabaseRequestSchema } from "@/types/proto-es/v1/database_service_pb";-import { convertKVListToLabels, convertLabelsToKVList } from "@/utils";--type LocalState = {- kvList: { key: string; value: string }[];- isUpdating: boolean;-};--const props = defineProps<{- database: Database;- allowEdit: boolean;-}>();--const { t } = useI18n();-const labelListEditorRef = ref<InstanceType<typeof LabelListEditor>>();-const state = reactive<LocalState>({- kvList: [],- isUpdating: false,-});--const convert = () => {- return convertLabelsToKVList(props.database.labels, true /* sort */);-};--const dirty = computed(() => {- const original = convert();- const local = state.kvList;- return !isEqual(original, local);-});--const allowSave = computed(() => {- if (!dirty.value) return false;- const errors = labelListEditorRef.value?.flattenErrors ?? [];- return errors.length === 0;-});--const handleCancel = () => {- state.kvList = convert();-};--const handleSave = async () => {- if (!allowSave.value) return;- state.isUpdating = true;- try {- // Won't omit empty `tenant` value.- // Otherwise the server API won't update the labels field correctly.- const labels = convertKVListToLabels(state.kvList, false /* !omitEmpty */);-- await useDatabaseV1Store().updateDatabase(- create(UpdateDatabaseRequestSchema, {- database: {- ...props.database,- labels,- },- updateMask: { paths: ["labels"] },- })- );- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });- } finally {- state.isUpdating = false;- }-};--watch(- () => props.database.labels,- () => {- state.kvList = convert();- },- {- immediate: true,- deep: true,- }-);-</script>diff --git a/frontend/src/components/DatabaseDetail/Settings/index.ts b/frontend/src/components/DatabaseDetail/Settings/index.tsdeleted file mode 100644index 69179cd43d..0000000000--- a/frontend/src/components/DatabaseDetail/Settings/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import DatabaseSettingsPanel from "./DatabaseSettingsPanel.vue";--export { DatabaseSettingsPanel };diff --git a/frontend/src/components/DatabaseDetail/index.ts b/frontend/src/components/DatabaseDetail/index.tsdeleted file mode 100644index f19b99e7ca..0000000000--- a/frontend/src/components/DatabaseDetail/index.ts+++ /dev/null@@ -1,5 +0,0 @@-import SQLEditorButtonV1 from "./SQLEditorButtonV1.vue";-import SchemaDiagramButton from "./SchemaDiagramButton.vue";-import { DatabaseSettingsPanel } from "./Settings";--export { SQLEditorButtonV1, DatabaseSettingsPanel, SchemaDiagramButton };diff --git a/frontend/src/components/DatabaseDetail/sqlEditor.ts b/frontend/src/components/DatabaseDetail/sqlEditor.tsnew file mode 100644index 0000000000..9c51416e13--- /dev/null+++ b/frontend/src/components/DatabaseDetail/sqlEditor.ts@@ -0,0 +1,53 @@+import type { Router } from "vue-router";+import { SQL_EDITOR_DATABASE_MODULE } from "@/router/sqlEditor";+import { defaultProject, isDefaultProject } from "@/types";+import type { Database } from "@/types/proto-es/v1/database_service_pb";+import {+ extractDatabaseResourceName,+ extractInstanceResourceName,+ extractProjectResourceName,+ hasProjectPermissionV2,+ isSQLEditorRoute,+} from "@/utils";++export const openSQLEditorForDatabase = ({+ router,+ database,+ schema,+ table,+ onPermissionDenied,+}: {+ router: Router;+ database: Database;+ schema?: string;+ table?: string;+ onPermissionDenied?: (database: Database) => void;+}) => {+ if (isDefaultProject(database.project)) {+ if (+ !hasProjectPermissionV2(defaultProject(database.project), "bb.sql.select")+ ) {+ onPermissionDenied?.(database);+ return;+ }+ }++ const { instance, databaseName } = extractDatabaseResourceName(database.name);+ const route = router.resolve({+ name: SQL_EDITOR_DATABASE_MODULE,+ params: {+ project: extractProjectResourceName(database.project),+ instance: extractInstanceResourceName(instance),+ database: databaseName,+ },+ query: {+ schema: schema || undefined,+ table: table || undefined,+ },+ });+ if (isSQLEditorRoute(router)) {+ router.push(route);+ } else {+ window.open(route.fullPath);+ }+};diff --git a/frontend/src/components/ExternalTableDetailDrawer.vue b/frontend/src/components/ExternalTableDetailDrawer.vueindex 195f6fad4e..2260d66354 100644--- a/frontend/src/components/ExternalTableDetailDrawer.vue+++ b/frontend/src/components/ExternalTableDetailDrawer.vue@@ -61,12 +61,15 @@><DatabaseV1Name :database="database" /></dd>- <SQLEditorButtonV1+ <buttonv-if="allowQuery"- class="text-sm md:mr-4"- :database="database"- :label="true"- />+ type="button"+ class="flex items-center text-sm textlabel cursor-pointer hover:text-accent md:mr-4 border-0 bg-transparent p-0"+ @click.stop.prevent="gotoSQLEditor"+ >+ <span class="mr-1">{{ $t("sql-editor.self") }}</span>+ <heroicons-solid:terminal class="w-5 h-5" />+ </button></dl></div></div>@@ -129,6 +132,7 @@import { create } from "@bufbuild/protobuf";import { computedAsync } from "@vueuse/core";import { computed, reactive, ref } from "vue";+import { useRouter } from "vue-router";import {DatabaseV1Name,Drawer,@@ -150,7 +154,7 @@ import {isDatabaseV1Queryable,} from "@/utils";import ColumnDataTable from "./ColumnDataTable/index.vue";-import { SQLEditorButtonV1 } from "./DatabaseDetail";+import { openSQLEditorForDatabase } from "./DatabaseDetail/sqlEditor";interface LocalState {columnNameSearchKeyword: string;@@ -169,6 +173,7 @@ defineEmits(["dismiss"]);const dbSchemaStore = useDBSchemaV1Store();const databaseV1Store = useDatabaseV1Store();+const router = useRouter();const state = reactive<LocalState>({columnNameSearchKeyword: "",partitionTableNameSearchKeyword: "",@@ -223,6 +228,13 @@ const allowQuery = computed(() => {return isDatabaseV1Queryable(database.value);});+const gotoSQLEditor = () => {+ openSQLEditorForDatabase({+ router,+ database: database.value,+ });+};+const getTableName = (tableName: string) => {if (hasSchemaProperty(instanceEngine.value)) {return `"${props.schemaName}"."${tableName}"`;diff --git a/frontend/src/components/FeatureGuard/FeatureAttention.vue b/frontend/src/components/FeatureGuard/FeatureAttention.vueindex 90877d5ecf..89ae475983 100644--- a/frontend/src/components/FeatureGuard/FeatureAttention.vue+++ b/frontend/src/components/FeatureGuard/FeatureAttention.vue@@ -9,17 +9,14 @@@click="onClick"/>- <InstanceAssignment- :show="state.showInstanceAssignmentDrawer"- @dismiss="state.showInstanceAssignmentDrawer = false"- /></template><script lang="ts" setup>-import { computed, reactive } from "vue";+import { computed } from "vue";import { useI18n } from "vue-i18n";import { useRouter } from "vue-router";import { BBAttention } from "@/bbkit";+import { INSTANCE_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";import { useActuatorV1Store, useSubscriptionV1Store } from "@/store";import { ENTERPRISE_INQUIRE_LINK, instanceLimitFeature } from "@/types";import type {@@ -31,11 +28,6 @@ import {PlanType,} from "@/types/proto-es/v1/subscription_service_pb";import { autoSubscriptionRoute, hasWorkspacePermissionV2 } from "@/utils";-import InstanceAssignment from "../InstanceAssignment.vue";--interface LocalState {- showInstanceAssignmentDrawer: boolean;-}const props = withDefaults(defineProps<{@@ -56,10 +48,6 @@ const { t } = useI18n();const actuatorStore = useActuatorV1Store();const subscriptionStore = useSubscriptionV1Store();-const state = reactive<LocalState>({- showInstanceAssignmentDrawer: false,-});-const hasPermission = computed(() =>hasWorkspacePermissionV2("bb.settings.set"));@@ -165,7 +153,13 @@ const onClick = () => {return;}if (instanceMissingLicense.value || existInstanceWithoutLicense.value) {- state.showInstanceAssignmentDrawer = true;+ router.push({+ name: INSTANCE_ROUTE_DASHBOARD,+ query: {+ assignLicense: "1",+ instances: props.instance?.name,+ },+ });return;}router.push(autoSubscriptionRoute());diff --git a/frontend/src/components/FeatureGuard/FeatureBadge.vue b/frontend/src/components/FeatureGuard/FeatureBadge.vueindex 0655207968..3a4a22ebcf 100644--- a/frontend/src/components/FeatureGuard/FeatureBadge.vue+++ b/frontend/src/components/FeatureGuard/FeatureBadge.vue@@ -9,7 +9,7 @@(e: MouseEvent) => {e.stopPropagation();e.preventDefault();- state.showInstanceAssignmentDrawer = true;+ gotoInstanceAssignment();}">@@ -49,17 +49,14 @@</span></NTooltip></div>- <InstanceAssignment- v-if="instanceMissingLicense && canManageSubscription"- :show="state.showInstanceAssignmentDrawer"- @dismiss="state.showInstanceAssignmentDrawer = false"- /></template><script lang="ts" setup>import { SparklesIcon } from "lucide-vue-next";import { NTooltip } from "naive-ui";-import { computed, reactive } from "vue";+import { computed } from "vue";+import { useRouter } from "vue-router";+import { INSTANCE_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";import { useSubscriptionV1Store } from "@/store";import type {Instance,@@ -70,11 +67,6 @@ import {PlanType,} from "@/types/proto-es/v1/subscription_service_pb";import { autoSubscriptionRoute, hasWorkspacePermissionV2 } from "@/utils";-import InstanceAssignment from "../InstanceAssignment.vue";--interface LocalState {- showInstanceAssignmentDrawer: boolean;-}const props = withDefaults(defineProps<{@@ -90,10 +82,7 @@ const props = withDefaults(});-const state = reactive<LocalState>({- showInstanceAssignmentDrawer: false,-});-+const router = useRouter();const subscriptionStore = useSubscriptionV1Store();const hasFeature = computed(() => {@@ -110,4 +99,17 @@ const instanceMissingLicense = computed(() => {const canManageSubscription = computed((): boolean => {return hasWorkspacePermissionV2("bb.instances.update");});++const gotoInstanceAssignment = () => {+ if (!canManageSubscription.value) {+ return;+ }+ router.push({+ name: INSTANCE_ROUTE_DASHBOARD,+ query: {+ assignLicense: "1",+ instances: props.instance?.name,+ },+ });+};</script>diff --git a/frontend/src/components/FeatureGuard/FeatureModal.vue b/frontend/src/components/FeatureGuard/FeatureModal.vueindex 0f23b6504d..cae79995e1 100644--- a/frontend/src/components/FeatureGuard/FeatureModal.vue+++ b/frontend/src/components/FeatureGuard/FeatureModal.vue@@ -85,19 +85,16 @@</div></div></BBModal>- <InstanceAssignment- :show="state.showInstanceAssignmentDrawer"- @dismiss="state.showInstanceAssignmentDrawer = false"- /></template><script lang="ts" setup>import { SparklesIcon } from "lucide-vue-next";import { NButton } from "naive-ui";-import { computed, reactive } from "vue";+import { computed } from "vue";import { useI18n } from "vue-i18n";import { useRouter } from "vue-router";import { BBModal } from "@/bbkit";+import { INSTANCE_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";import { useSubscriptionV1Store } from "@/store";import { ENTERPRISE_INQUIRE_LINK } from "@/types";import type {@@ -109,11 +106,6 @@ import {PlanType,} from "@/types/proto-es/v1/subscription_service_pb";import { autoSubscriptionRoute, hasWorkspacePermissionV2 } from "@/utils";-import InstanceAssignment from "../InstanceAssignment.vue";--interface LocalState {- showInstanceAssignmentDrawer: boolean;-}const props = withDefaults(defineProps<{@@ -127,10 +119,6 @@ const props = withDefaults(});-const state = reactive<LocalState>({- showInstanceAssignmentDrawer: false,-});-const emit = defineEmits(["cancel"]);const { t } = useI18n();const router = useRouter();@@ -154,7 +142,13 @@ const title = computed(() => {const ok = () => {if (instanceMissingLicense.value) {- state.showInstanceAssignmentDrawer = true;+ router.push({+ name: INSTANCE_ROUTE_DASHBOARD,+ query: {+ assignLicense: "1",+ instances: props.instance?.name,+ },+ });} else {router.push(autoSubscriptionRoute());}diff --git a/frontend/src/components/InstanceAssignment.vue b/frontend/src/components/InstanceAssignment.vuedeleted file mode 100644index 2efe070b9b..0000000000--- a/frontend/src/components/InstanceAssignment.vue+++ /dev/null@@ -1,225 +0,0 @@-<template>- <Drawer :show="show" @close="$emit('dismiss')">- <DrawerContent- :title="$t('subscription.instance-assignment.manage-license')"- class="max-w-[100vw]"- >- <div class="flex flex-col gap-y-5 w-[40rem] h-full">- <div>- <div class="flex gap-x-2">- <div class="text-gray-400">- {{- $t("subscription.instance-assignment.used-and-total-license")- }}- </div>- <LearnMoreLink- url="https://docs.bytebase.com/administration/license?source=console"- class="ml-1 text-sm"- />- </div>- <div class="mt-1 text-4xl flex items-center gap-x-2">- <span>- {{ actuatorStore.activatedInstanceCount }}- </span>- <span class="text-xl">/</span>- <span>{{ totalLicenseCount }}</span>- </div>- </div>-- <PagedInstanceTable- ref="pagedInstanceTableRef"- session-key="bb.instance-table"- :bordered="true"- :show-address="false"- :show-external-link="false"- :show-selection="canManageSubscription"- :selected-instance-names="Array.from(state.selectedInstance)"- @update:selected-instance-names="- (list: string[]) => (state.selectedInstance = new Set(list))- "- />- </div>-- <template #footer>- <div class="w-full flex justify-between items-center">- <div class="w-full flex justify-end items-center gap-x-2">- <NButton @click.prevent="cancel">- {{ $t("common.cancel") }}- </NButton>- <NButton- :disabled="- !canManageSubscription ||- state.processing ||- state.selectedInstance.size > instanceLicenseCount- "- type="primary"- @click.prevent="updateAssignment"- >- {{ $t("common.confirm") }}- </NButton>- </div>- </div>- </template>- </DrawerContent>- </Drawer>-</template>--<script lang="ts" setup>-import { create } from "@bufbuild/protobuf";-import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";-import { NButton } from "naive-ui";-import { storeToRefs } from "pinia";-import { computed, reactive, ref, watch } from "vue";-import { useI18n } from "vue-i18n";-import { Drawer, DrawerContent, PagedInstanceTable } from "@/components/v2";-import {- pushNotification,- useActuatorV1Store,- useDatabaseV1Store,- useInstanceV1Store,- useSubscriptionV1Store,-} from "@/store";-import type {- Instance,- UpdateInstanceRequest,-} from "@/types/proto-es/v1/instance_service_pb";-import { UpdateInstanceRequestSchema } from "@/types/proto-es/v1/instance_service_pb";-import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";-import { hasWorkspacePermissionV2 } from "@/utils";-import LearnMoreLink from "./LearnMoreLink.vue";--const props = withDefaults(- defineProps<{- show: boolean;- selectedInstanceList?: string[];- }>(),- {- show: false,- selectedInstanceList: () => [],- }-);--interface LocalState {- selectedInstance: Set<string>;- processing: boolean;-}--const emit = defineEmits(["dismiss"]);--const state = reactive<LocalState>({- selectedInstance: new Set(),- processing: false,-});--const instanceV1Store = useInstanceV1Store();-const databaseV1Store = useDatabaseV1Store();-const subscriptionStore = useSubscriptionV1Store();-const actuatorStore = useActuatorV1Store();-const { t } = useI18n();-const pagedInstanceTableRef = ref<InstanceType<typeof PagedInstanceTable>>();-const { instanceLicenseCount } = storeToRefs(subscriptionStore);--const canManageSubscription = computed((): boolean => {- return (- hasWorkspacePermissionV2("bb.instances.update") &&- subscriptionStore.currentPlan !== PlanType.FREE- );-});--const selectActivationInstances = (instances: Instance[]) => {- for (const instance of instances) {- if (instance.activation) {- state.selectedInstance.add(instance.name);- }- }-};--watch(- [() => props.show, () => props.selectedInstanceList],- async ([show, selectedInstanceList]) => {- if (!show) {- state.selectedInstance = new Set();- return;- }-- for (const instanceName of selectedInstanceList) {- state.selectedInstance.add(instanceName);- }- },- { immediate: true }-);--watch(- () => pagedInstanceTableRef.value?.dataList ?? [],- (dataList) => {- selectActivationInstances(dataList);- },- { deep: true, immediate: true }-);--const totalLicenseCount = computed((): string => {- if (instanceLicenseCount.value === Number.MAX_VALUE) {- return t("common.unlimited");- }- return `${instanceLicenseCount.value}`;-});--const cancel = () => {- emit("dismiss");-};--const updateAssignment = async () => {- if (state.processing) {- return;- }- state.processing = true;-- const batchUpdate: UpdateInstanceRequest[] = [];- for (const instanceName of state.selectedInstance) {- const instance = instanceV1Store.getInstanceByName(instanceName);- if (instance.activation) {- continue;- }- // activate instance- batchUpdate.push(- create(UpdateInstanceRequestSchema, {- instance: {- ...instance,- activation: true,- },- updateMask: create(FieldMaskSchema, { paths: ["activation"] }),- })- );- }-- for (const instance of pagedInstanceTableRef.value?.dataList ?? []) {- if (instance.activation && !state.selectedInstance.has(instance.name)) {- batchUpdate.push(- create(UpdateInstanceRequestSchema, {- instance: {- ...instance,- activation: false,- },- updateMask: create(FieldMaskSchema, { paths: ["activation"] }),- })- );- }- }-- const updated = await instanceV1Store.batchUpdateInstances(batchUpdate);- for (const instance of updated) {- databaseV1Store.updateDatabaseInstance(instance);- }-- // refresh activatedInstanceCount- await actuatorStore.fetchServerInfo(actuatorStore.workspaceResourceName);-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("subscription.instance-assignment.success-notification"),- });- state.processing = false;- emit("dismiss");-};-</script>diff --git a/frontend/src/components/InstanceDatabaseRedirect.vue b/frontend/src/components/InstanceDatabaseRedirect.vuedeleted file mode 100644index 2bf0b59c65..0000000000--- a/frontend/src/components/InstanceDatabaseRedirect.vue+++ /dev/null@@ -1,78 +0,0 @@-<script setup lang="ts">-import { onMounted } from "vue";-import { useRoute, useRouter } from "vue-router";-import { INSTANCE_ROUTE_DETAIL } from "@/router/dashboard/instance";-import { PROJECT_V1_ROUTE_DATABASE_DETAIL } from "@/router/dashboard/projectV1";-import {- databaseNamePrefix,- instanceNamePrefix,- pushNotification,- useDatabaseV1Store,-} from "@/store";-import { isValidProjectName } from "@/types";-import { extractProjectResourceName } from "@/utils/v1";--const route = useRoute();-const router = useRouter();-const databaseStore = useDatabaseV1Store();--onMounted(async () => {- const instanceId = route.params.instanceId as string;- const databaseName = route.params.databaseName as string;-- try {- // Fetch the database to get its project information- const database = await databaseStore.getOrFetchDatabaseByName(- `${instanceNamePrefix}${instanceId}/${databaseNamePrefix}${databaseName}`- );-- if (database && isValidProjectName(database.project)) {- // Extract project ID from the database's project field- const projectId = extractProjectResourceName(database.project);-- // Redirect to the project database detail page- router.replace({- name: PROJECT_V1_ROUTE_DATABASE_DETAIL,- params: {- projectId: projectId,- instanceId: instanceId,- databaseName: databaseName,- },- });- } else {- // If database not found, show error and redirect to instance detail- pushNotification({- module: "bytebase",- style: "WARN",- title: "Database not found",- description: `Database: ${databaseName}`,- });-- router.replace({- name: INSTANCE_ROUTE_DETAIL,- params: {- instanceId: instanceId,- },- });- }- } catch (error) {- console.error("Failed to fetch database:", error);-- // Show error notification- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: "Error",- description: `Failed to load database: ${databaseName}`,- });-- // On error, redirect to instance detail- router.replace({- name: INSTANCE_ROUTE_DETAIL,- params: {- instanceId: instanceId,- },- });- }-});-</script>diff --git a/frontend/src/components/IssueV1/components/RoleGrant/DatabaseResourceTable.vue b/frontend/src/components/IssueV1/components/RoleGrant/DatabaseResourceTable.vuedeleted file mode 100644index 867ff465d7..0000000000--- a/frontend/src/components/IssueV1/components/RoleGrant/DatabaseResourceTable.vue+++ /dev/null@@ -1,109 +0,0 @@-<template>- <NDataTable- size="small"- :columns="columns"- :data="databaseResourceList"- :striped="true"- :bordered="true"- />-</template>--<script lang="tsx" setup>-import type { DataTableColumn } from "naive-ui";-import { NDataTable } from "naive-ui";-import { computed, watch } from "vue";-import { useI18n } from "vue-i18n";-import { EnvironmentV1Name, InstanceV1Name } from "@/components/v2";-import { useDatabaseV1Store } from "@/store";-import type { DatabaseResource } from "@/types";-import type { DatabaseGroup } from "@/types/proto-es/v1/database_group_service_pb";-import {- extractDatabaseResourceName,- getDatabaseEnvironment,- getInstanceResource,-} from "@/utils";--const props = defineProps<{- databaseResourceList: DatabaseResource[];-}>();--defineEmits<{- (event: "edit", databaseGroup: DatabaseGroup): void;-}>();--const { t } = useI18n();-const databaseStore = useDatabaseV1Store();--const getDatabaseName = (databaseResource: DatabaseResource) => {- const database = databaseStore.getDatabaseByName(- databaseResource.databaseFullName- );- return extractDatabaseResourceName(database.name).databaseName;-};--const extractTableName = (databaseResource: DatabaseResource) => {- if (!databaseResource.schema && !databaseResource.table) {- return "*";- }- const names = [];- if (databaseResource.schema) {- names.push(databaseResource.schema);- }- names.push(databaseResource.table || "*");- return names.join(".");-};--const getDatabase = (databaseResource: DatabaseResource) => {- const database = databaseStore.getDatabaseByName(- databaseResource.databaseFullName- );- return database;-};--watch(- () => props.databaseResourceList,- async () => {- await databaseStore.batchGetOrFetchDatabases(- props.databaseResourceList.map(- (databaseResource) => databaseResource.databaseFullName- )- );- },- {- immediate: true,- }-);--const columns = computed((): DataTableColumn<DatabaseResource>[] => {- return [- {- title: t("common.database"),- key: "database",- render: (row) => getDatabaseName(row),- },- {- title: t("common.table"),- key: "table",- render: (row) => (- <span class="line-clamp-1">{extractTableName(row)}</span>- ),- },- {- title: t("common.environment"),- key: "environment",- render: (row) => (- <EnvironmentV1Name- environment={getDatabaseEnvironment(getDatabase(row))}- />- ),- },- {- title: t("common.instance"),- key: "instance",- render: (row) => (- <InstanceV1Name instance={getInstanceResource(getDatabase(row))} />- ),- },- ];-});-</script>diff --git a/frontend/src/components/IssueV1/components/RoleGrant/index.ts b/frontend/src/components/IssueV1/components/RoleGrant/index.tsdeleted file mode 100644index 217f1a350a..0000000000--- a/frontend/src/components/IssueV1/components/RoleGrant/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import DatabaseResourceTable from "./DatabaseResourceTable.vue";--export { DatabaseResourceTable };diff --git a/frontend/src/components/IssueV1/components/index.ts b/frontend/src/components/IssueV1/components/index.tsindex 9f5840b847..1ed226ad59 100644--- a/frontend/src/components/IssueV1/components/index.ts+++ b/frontend/src/components/IssueV1/components/index.ts@@ -1 +1,2 @@-export * from "./RoleGrant";+export { default as IssueLabelSelector } from "./IssueLabelSelector.vue";+export { default as IssueStatusIcon } from "./IssueStatusIcon.vue";diff --git a/frontend/src/components/Plan/PollerProvider.vue b/frontend/src/components/Plan/PollerProvider.vuedeleted file mode 100644index 962e7ad164..0000000000--- a/frontend/src/components/Plan/PollerProvider.vue+++ /dev/null@@ -1,9 +0,0 @@-<template>- <slot />-</template>--<script lang="ts" setup>-import { provideResourcePoller } from "./logic/poller";--provideResourcePoller();-</script>diff --git a/frontend/src/components/Plan/components/AddSpecDrawer.vue b/frontend/src/components/Plan/components/AddSpecDrawer.vuedeleted file mode 100644index cc1bb6044c..0000000000--- a/frontend/src/components/Plan/components/AddSpecDrawer.vue+++ /dev/null@@ -1,183 +0,0 @@-<template>- <Drawer- placement="right"- v-model:show="show"- :mask-closable="true"- :resizable="true"- >- <DrawerContent- :title="title ?? $t('plan.add-spec')"- closable- class="max-w-[100vw]"- >- <div class="flex flex-col gap-y-4">- <!-- Select Targets -->- <div class="w-full md:w-[80vw] lg:w-[60vw]">- <DatabaseAndGroupSelector- :project="project"- :value="databaseSelectState"- @update:value="handleUpdateSelection"- />- </div>-- </div>- <template #footer>- <div class="w-full flex items-center justify-end">- <div class="flex items-center gap-x-2">- <NButton quaternary @click="handleCancel">- {{ $t("common.close") }}- </NButton>- <NButton- type="primary"- :disabled="!canSubmit"- :loading="isCreating"- @click="handleConfirm"- >- {{ $t("common.confirm") }}- </NButton>- </div>- </div>- </template>- </DrawerContent>- </Drawer>-</template>--<script setup lang="ts">-import { create as createProto } from "@bufbuild/protobuf";-import { NButton } from "naive-ui";-import { v4 as uuidv4 } from "uuid";-import { computed, reactive, ref, watch } from "vue";-import { useI18n } from "vue-i18n";-import type { DatabaseSelectState } from "@/components/DatabaseAndGroupSelector";-import DatabaseAndGroupSelector from "@/components/DatabaseAndGroupSelector";-import { getLocalSheetByName, getNextLocalSheetUID } from "@/components/Plan";-import { Drawer, DrawerContent } from "@/components/v2";-import {- pushNotification,- useCurrentProjectV1,- useDatabaseV1Store,-} from "@/store";-import type { Database } from "@/types/proto-es/v1/database_service_pb";-import {- Plan_ChangeDatabaseConfigSchema,- type Plan_Spec,- Plan_SpecSchema,-} from "@/types/proto-es/v1/plan_service_pb";--const props = defineProps<{- title?: string;- preSelectedDatabases?: Database[];- preSelectedDatabaseGroup?: string;-}>();--const emit = defineEmits<{- (event: "created", spec: Plan_Spec): void;-}>();--const { project } = useCurrentProjectV1();-const { t } = useI18n();-const dbStore = useDatabaseV1Store();-const show = defineModel<boolean>("show", { default: false });--const isCreating = ref(false);--const databaseSelectState = reactive<DatabaseSelectState>({- changeSource: "DATABASE",- selectedDatabaseNameList: [],-});--const hasSelection = computed(() => {- if (databaseSelectState.changeSource === "DATABASE") {- return databaseSelectState.selectedDatabaseNameList.length > 0;- } else {- return !!databaseSelectState.selectedDatabaseGroup;- }-});--const canSubmit = computed(() => {- return hasSelection.value;-});--// Reset state when drawer opens-watch(show, (newVal) => {- if (newVal) {- // Initialize with pre-selected database group if provided- if (props.preSelectedDatabaseGroup) {- databaseSelectState.changeSource = "GROUP";- databaseSelectState.selectedDatabaseNameList = [];- databaseSelectState.selectedDatabaseGroup =- props.preSelectedDatabaseGroup;- } else {- databaseSelectState.changeSource = "DATABASE";- databaseSelectState.selectedDatabaseNameList = (- props.preSelectedDatabases ?? []- ).map((db) => db.name);- databaseSelectState.selectedDatabaseGroup = undefined;- }-- isCreating.value = false;- }-});--const handleUpdateSelection = async (newState: DatabaseSelectState) => {- Object.assign(databaseSelectState, newState);-- // Preload database information if databases are selected- if (- newState.changeSource === "DATABASE" &&- newState.selectedDatabaseNameList?.length > 0- ) {- await dbStore.batchGetOrFetchDatabases(newState.selectedDatabaseNameList);- }-};--const handleCancel = () => {- show.value = false;-};--const handleConfirm = async () => {- if (!canSubmit.value) return;-- isCreating.value = true;- try {- // Get targets- const targets: string[] = [];- if (databaseSelectState.changeSource === "DATABASE") {- targets.push(...databaseSelectState.selectedDatabaseNameList);- } else if (databaseSelectState.selectedDatabaseGroup) {- targets.push(databaseSelectState.selectedDatabaseGroup);- }-- // Otherwise, create spec for plan flow- const sheetUID = getNextLocalSheetUID();- const localSheet = getLocalSheetByName(- `${project.value.name}/sheets/${sheetUID}`- );-- // Create spec- const spec = createProto(Plan_SpecSchema, {- id: uuidv4(),- config: {- case: "changeDatabaseConfig",- value: createProto(Plan_ChangeDatabaseConfigSchema, {- targets,-- sheet: localSheet.name,- }),- },- });-- emit("created", spec);- show.value = false;- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.error"),- description: error instanceof Error ? error.message : String(error),- });- } finally {- isCreating.value = false;- }-};-</script>diff --git a/frontend/src/components/Plan/components/BannerSection/BannerSection.vue b/frontend/src/components/Plan/components/BannerSection/BannerSection.vuedeleted file mode 100644index 39c913367a..0000000000--- a/frontend/src/components/Plan/components/BannerSection/BannerSection.vue+++ /dev/null@@ -1,36 +0,0 @@-<template>- <div>- <div- v-show="showClosedBanner"- class="h-8 w-full text-base font-medium bg-gray-400 text-white flex justify-center items-center shrink-0"- >- {{ $t("common.closed") }}- </div>- <div- v-show="showSuccessBanner"- class="h-8 w-full text-base font-medium bg-success text-white flex justify-center items-center shrink-0"- >- {{ $t("common.approved") }}- </div>- </div>-</template>--<script lang="ts" setup>-import { computed } from "vue";-import { usePlanContext } from "@/components/Plan";-import { State } from "@/types/proto-es/v1/common_pb";-import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";--const { plan, issue } = usePlanContext();--const showClosedBanner = computed(() => {- return (- plan.value.state === State.DELETED ||- (issue.value && issue.value.status === IssueStatus.CANCELED)- );-});--const showSuccessBanner = computed(() => {- return issue.value && issue.value.status === IssueStatus.DONE;-});-</script>diff --git a/frontend/src/components/Plan/components/BannerSection/index.ts b/frontend/src/components/Plan/components/BannerSection/index.tsdeleted file mode 100644index 120e113f66..0000000000--- a/frontend/src/components/Plan/components/BannerSection/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import BannerSection from "./BannerSection.vue";--export default BannerSection;diff --git a/frontend/src/components/Plan/components/ChecksView/ChecksDrawer.vue b/frontend/src/components/Plan/components/ChecksView/ChecksDrawer.vuedeleted file mode 100644index 29163677ba..0000000000--- a/frontend/src/components/Plan/components/ChecksView/ChecksDrawer.vue+++ /dev/null@@ -1,48 +0,0 @@-<template>- <Drawer v-bind="$attrs">- <DrawerContent- :title="$t('plan.navigator.checks')"- class="w-[40rem] max-w-[100vw] relative"- >- <ChecksView- :default-status="status"- :plan-check-runs="resolvedPlanCheckRuns"- :is-loading="isLoading"- />- </DrawerContent>- </Drawer>-</template>--<script setup lang="ts">-import { computed, ref } from "vue";-import { Drawer, DrawerContent } from "@/components/v2";-import type { PlanCheckRun } from "@/types/proto-es/v1/plan_service_pb";-import type { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";-import { usePlanContext } from "../../logic";-import { useResourcePoller } from "../../logic/poller";-import ChecksView from "./ChecksView.vue";--const props = defineProps<{- status: Advice_Level;- planCheckRuns?: PlanCheckRun[];-}>();--const { planCheckRuns: contextPlanCheckRuns } = usePlanContext();--const resolvedPlanCheckRuns = computed(() => {- return props.planCheckRuns ?? contextPlanCheckRuns.value;-});-const { refreshResources } = useResourcePoller();--const isLoading = ref(true);--// Load plan check runs on component mount-const loadCheckRuns = async () => {- isLoading.value = true;- await refreshResources(["planCheckRuns"], true);- isLoading.value = false;-};--// Load once when component mounts-loadCheckRuns();-</script>diff --git a/frontend/src/components/Plan/components/ChecksView/ChecksView.vue b/frontend/src/components/Plan/components/ChecksView/ChecksView.vuedeleted file mode 100644index b94ae56254..0000000000--- a/frontend/src/components/Plan/components/ChecksView/ChecksView.vue+++ /dev/null@@ -1,361 +0,0 @@-<template>- <div class="flex-1 flex flex-col">- <!-- Header with status counts -->- <div class="flex items-center justify-between">- <div class="flex items-center gap-4">- <div class="flex items-center gap-3" v-if="hasAnyStatus">- <div- v-if="statusSummary.error > 0"- class="flex items-center gap-1 text-error cursor-pointer"- :class="getItemClass(Advice_Level.ERROR)"- @click="toggleSelectedStatus(Advice_Level.ERROR)"- >- <XCircleIcon class="w-5 h-5" />- <span>{{ $t("common.error") }}</span>- <span>{{ statusSummary.error }}</span>- </div>- <div- v-if="statusSummary.warning > 0"- class="flex items-center gap-1 text-warning cursor-pointer"- :class="getItemClass(Advice_Level.WARNING)"- @click="toggleSelectedStatus(Advice_Level.WARNING)"- >- <AlertCircleIcon class="w-5 h-5" />- <span>{{ $t("common.warning") }}</span>- <span>{{ statusSummary.warning }}</span>- </div>- <div- v-if="statusSummary.success > 0"- class="flex items-center gap-1 text-success cursor-pointer"- :class="getItemClass(Advice_Level.SUCCESS)"- @click="toggleSelectedStatus(Advice_Level.SUCCESS)"- >- <CheckCircleIcon class="w-5 h-5" />- <span>{{ $t("common.success") }}</span>- <span>{{ statusSummary.success }}</span>- </div>- </div>- </div>- </div>-- <!-- Results List -->- <div class="flex-1 overflow-y-auto">- <div- v-if="isLoading"- class="flex flex-col items-center justify-center py-12"- >- <BBSpin />- </div>- <!-- Empty state -->- <div- v-else-if="filteredResultGroups.length === 0"- class="flex flex-col items-center justify-center py-12"- >- <CheckCircleIcon class="w-12 h-12 text-control-light opacity-50 mb-4" />- <div class="text-lg text-control-light">- {{- hasFilters- ? $t("plan.checks.no-results-match-filters")- : $t("plan.checks.no-check-results")- }}- </div>- </div>- <div v-else>- <div class="divide-y">- <!-- Group by result type/target -->- <div- v-for="group in displayedResultGroups"- :key="group.key"- class="px-2 py-4"- >- <!-- Check Run Header -->- <div class="flex flex-wrap items-start justify-between gap-2 mb-2">- <div class="flex items-center gap-3 shrink-0">- <component- :is="getCheckTypeIcon(group.type)"- class="w-5 h-5 text-control-light"- />- <div class="flex flex-row items-center gap-2">- <span class="text-sm font-medium">- {{ getCheckTypeLabel(group.type) }}- </span>- <NTooltip- v-if="getCheckTypeDescription(group.type)"- style="max-width: 20rem"- >- <template #trigger>- <CircleQuestionMarkIcon- class="w-4 h-4 text-control-light"- />- </template>- {{ getCheckTypeDescription(group.type) }}- </NTooltip>- <Timestamp- v-if="group.createTime"- :timestamp="group.createTime"- custom-class="text-sm"- />- </div>- </div>-- <div class="flex items-center gap-2 min-w-0 max-w-[50%]">- <DatabaseDisplay :database="group.target" />- </div>- </div>-- <!-- Results for this group -->- <div class="flex flex-col gap-y-2 pl-8">- <CheckResultItem- v-for="(result, idx) in group.results"- :key="idx"- :status="getCheckResultStatus(result.status)"- :title="result.title"- :content="result.content"- :code="result.code"- :report-type="result.report?.case"- :position="- result.report?.case === 'sqlReviewReport' &&- result.report.value.startPosition- ? result.report.value.startPosition- : undefined- "- :affected-rows="- result.report?.case === 'sqlSummaryReport'- ? result.report.value.affectedRows- : undefined- "- />- </div>- </div>- </div>- <!-- Load more button -->- <div v-if="hasMore" class="flex justify-center py-4">- <button- class="text-sm text-accent hover:underline"- @click="loadMore"- >- {{ $t("common.load-more") }} ({{ remainingCount }})- </button>- </div>- </div>- </div>- </div>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import type { Timestamp as TimestampPb } from "@bufbuild/protobuf/wkt";-import {- AlertCircleIcon,- CheckCircleIcon,- CircleQuestionMarkIcon,- FileCodeIcon,- SearchCodeIcon,- ShieldIcon,- XCircleIcon,-} from "lucide-vue-next";-import { NTooltip } from "naive-ui";-import { computed, ref } from "vue";-import { useI18n } from "vue-i18n";-import { BBSpin } from "@/bbkit";-import Timestamp from "@/components/misc/Timestamp.vue";-import {- type PlanCheckRun,- type PlanCheckRun_Result,- PlanCheckRun_Result_Type,- PlanCheckRun_ResultSchema,- PlanCheckRun_Status,-} from "@/types/proto-es/v1/plan_service_pb";-import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";-import { computePlanCheckStatusSummary } from "../../logic/plan-check-status";-import CheckResultItem from "../common/CheckResultItem.vue";-import DatabaseDisplay from "../common/DatabaseDisplay.vue";--interface ResultGroup {- key: string;- type: PlanCheckRun_Result_Type;- target: string;- createTime?: TimestampPb;- results: PlanCheckRun_Result[];-}--const props = defineProps<{- defaultStatus?: Advice_Level;- planCheckRuns: PlanCheckRun[];- isLoading?: boolean;-}>();--const { t } = useI18n();--const selectedStatus = ref<Advice_Level | undefined>(props.defaultStatus);--// Pagination - load more-const PAGE_SIZE = 10;-const displayCount = ref(PAGE_SIZE);--const loadMore = () => {- displayCount.value += PAGE_SIZE;-};--const hasFilters = computed(() => {- return selectedStatus.value !== undefined;-});--// Summary depends only on `planCheckRuns` (not status filter) so toggling the filter does not rescan for counts.-const planCheckSummary = computed(() =>- computePlanCheckStatusSummary(props.planCheckRuns)-);--const statusSummary = computed(() => ({- error: planCheckSummary.value.error,- warning: planCheckSummary.value.warning,- success: planCheckSummary.value.success,-}));--const hasAnyStatus = computed(() => {- const s = planCheckSummary.value;- return s.error > 0 || s.warning > 0 || s.success > 0;-});--const toggleSelectedStatus = (status: Advice_Level) => {- if (selectedStatus.value === status) {- selectedStatus.value = undefined; // Deselect if already selected- } else {- selectedStatus.value = status; // Select the new status- }- // Reset pagination when filter changes- displayCount.value = PAGE_SIZE;-};--const getItemClass = (status: Advice_Level) => {- return selectedStatus.value === status- ? "bg-gray-100 rounded-lg px-2 py-1"- : "px-2 py-1";-};--// O(total results); pagination only slices `groups` — very large `results` may need future virtualization.-const filteredResultGroups = computed(() => {- const groups: ResultGroup[] = [];- const groupMap = new Map<string, ResultGroup>();-- for (const checkRun of props.planCheckRuns) {- // Handle failed check runs- if (checkRun.status === PlanCheckRun_Status.FAILED) {- if (- selectedStatus.value === undefined ||- selectedStatus.value === Advice_Level.ERROR- ) {- // Create a synthetic error result for the failed run- const syntheticResult = create(PlanCheckRun_ResultSchema, {- status: Advice_Level.ERROR,- title: "Check Failed",- content: checkRun.error || "Plan check run failed",- code: 0,- });- const key = `failed-${checkRun.name}`;- groups.push({- key,- type: PlanCheckRun_Result_Type.TYPE_UNSPECIFIED,- target: "",- createTime: checkRun.createTime,- results: [syntheticResult],- });- }- }-- // Process results- for (const result of checkRun.results) {- // Filter by status- if (- selectedStatus.value !== undefined &&- result.status !== selectedStatus.value- ) {- continue;- }-- const key = `${result.type}-${result.target}`;- let group = groupMap.get(key);- if (!group) {- group = {- key,- type: result.type,- target: result.target,- createTime: checkRun.createTime,- results: [],- };- groupMap.set(key, group);- groups.push(group);- }- group.results.push(result);- }- }-- return groups;-});--// Paginated groups-const displayedResultGroups = computed(() => {- return filteredResultGroups.value.slice(0, displayCount.value);-});--const hasMore = computed(() => {- return filteredResultGroups.value.length > displayCount.value;-});--const remainingCount = computed(() => {- return filteredResultGroups.value.length - displayCount.value;-});--// Check type configuration lookup-const checkTypeConfig: Partial<- Record<- PlanCheckRun_Result_Type,- { icon: typeof FileCodeIcon; labelKey: string }- >-> = {- [PlanCheckRun_Result_Type.STATEMENT_ADVISE]: {- icon: SearchCodeIcon,- labelKey: "task.check-type.sql-review.self",- },- [PlanCheckRun_Result_Type.STATEMENT_SUMMARY_REPORT]: {- icon: FileCodeIcon,- labelKey: "task.check-type.summary-report",- },- [PlanCheckRun_Result_Type.GHOST_SYNC]: {- icon: ShieldIcon,- labelKey: "task.check-type.ghost-sync",- },-};--const getCheckTypeIcon = (type: PlanCheckRun_Result_Type) => {- return checkTypeConfig[type]?.icon ?? FileCodeIcon;-};--const getCheckTypeLabel = (type: PlanCheckRun_Result_Type) => {- const key = checkTypeConfig[type]?.labelKey;- return key ? t(key) : type.toString();-};--const getCheckTypeDescription = (type: PlanCheckRun_Result_Type) => {- switch (type) {- case PlanCheckRun_Result_Type.STATEMENT_ADVISE:- return t("task.check-type.sql-review.description");- default:- return undefined;- }-};--const adviceLevelToStatus: Partial<- Record<Advice_Level, "SUCCESS" | "WARNING" | "ERROR">-> = {- [Advice_Level.ERROR]: "ERROR",- [Advice_Level.WARNING]: "WARNING",- [Advice_Level.SUCCESS]: "SUCCESS",-};--const getCheckResultStatus = (- status: Advice_Level-): "SUCCESS" | "WARNING" | "ERROR" => {- return adviceLevelToStatus[status] ?? "SUCCESS";-};-</script>diff --git a/frontend/src/components/Plan/components/ChecksView/index.ts b/frontend/src/components/Plan/components/ChecksView/index.tsdeleted file mode 100644index 9ce0fe3c54..0000000000--- a/frontend/src/components/Plan/components/ChecksView/index.ts+++ /dev/null@@ -1 +0,0 @@-export { default as ChecksView } from "./ChecksView.vue";diff --git a/frontend/src/components/Plan/components/Configuration/Configuration.vue b/frontend/src/components/Plan/components/Configuration/Configuration.vuedeleted file mode 100644index 1cd492dda2..0000000000--- a/frontend/src/components/Plan/components/Configuration/Configuration.vue+++ /dev/null@@ -1,94 +0,0 @@-<template>- <div class="flex flex-col gap-y-2">- <h3 class="textlabel uppercase">{{ $t("plan.options.self") }}</h3>- <div v-if="shouldShow" class="flex flex-wrap gap-x-6 gap-y-2">- <TransactionModeSection v-if="shouldShowTransactionModeSection" />- <PreBackupSection v-if="shouldShowPreBackupSection" />- <GhostSection v-if="shouldShowGhostSection" />- <IsolationLevelSection v-if="shouldShowIsolationLevelSection" />- <InstanceRoleSection v-if="shouldShowInstanceRoleSection" />- </div>- <div v-else class="text-sm text-control-light">- {{ $t("plan.options.no-options-available") }}- </div>- </div>-</template>--<script lang="ts" setup>-import { computed } from "vue";-import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";-import { usePlanContext } from "../../logic";-import { useSelectedSpec } from "../SpecDetailView/context";-import GhostSection from "./GhostSection";-import { provideGhostSettingContext } from "./GhostSection/context";-import InstanceRoleSection from "./InstanceRoleSection";-import { provideInstanceRoleSettingContext } from "./InstanceRoleSection/context";-import IsolationLevelSection from "./IsolationLevelSection";-import { provideIsolationLevelSettingContext } from "./IsolationLevelSection/context";-import PreBackupSection from "./PreBackupSection";-import { providePreBackupSettingContext } from "./PreBackupSection/context";-import TransactionModeSection from "./TransactionModeSection";-import { provideTransactionModeSettingContext } from "./TransactionModeSection/context";--const { isCreating, plan, events, issue, readonly, allowEdit, project } =- usePlanContext();-const { selectedSpec } = useSelectedSpec();--const allowChange = computed(() => {- // If readonly mode, disallow changes- if (readonly?.value) {- return false;- }-- // Allow changes when creating- if (isCreating.value) {- return true;- }-- // Disallow changes if the plan has started rollout.- if (plan.value.hasRollout) {- return false;- }-- // If issue is not open, disallow- if (issue?.value && issue.value.status !== IssueStatus.OPEN) {- return false;- }-- return allowEdit.value;-});--const providerArgs = {- project,- plan,- selectedSpec,- isCreating,- allowChange,-};--const { shouldShow: shouldShowTransactionModeSection, events: txEvents } =- provideTransactionModeSettingContext(providerArgs);-const { shouldShow: shouldShowInstanceRoleSection, events: roleEvents } =- provideInstanceRoleSettingContext(providerArgs);-const { shouldShow: shouldShowIsolationLevelSection, events: isoEvents } =- provideIsolationLevelSettingContext(providerArgs);-const { shouldShow: shouldShowGhostSection, events: ghostEvents } =- provideGhostSettingContext(providerArgs);-const { shouldShow: shouldShowPreBackupSection, events: backupEvents } =- providePreBackupSettingContext(providerArgs);--const shouldShow = computed(- () =>- shouldShowTransactionModeSection.value ||- shouldShowIsolationLevelSection.value ||- shouldShowInstanceRoleSection.value ||- shouldShowGhostSection.value ||- shouldShowPreBackupSection.value-);--// Forward all setting updates to plan context-const emitStatusChanged = () => events.emit("status-changed", { eager: true });-[txEvents, roleEvents, isoEvents, ghostEvents, backupEvents].forEach((e) =>- e.on("update", emitStatusChanged)-);-</script>diff --git a/frontend/src/components/Plan/components/Configuration/GhostSection/FlagsForm/BoolFlag.vue b/frontend/src/components/Plan/components/Configuration/GhostSection/FlagsForm/BoolFlag.vuedeleted file mode 100644index b11dd3f819..0000000000--- a/frontend/src/components/Plan/components/Configuration/GhostSection/FlagsForm/BoolFlag.vue+++ /dev/null@@ -1,34 +0,0 @@-<template>- <NRadioGroup- :value="value"- @update:value="$emit('update:value', $event as boolean)"- >- <NRadio :value="false">{{ getLabel(false) }}</NRadio>- <NRadio :value="true">{{ getLabel(true) }}</NRadio>- </NRadioGroup>-</template>--<script setup lang="ts">-import { NRadio, NRadioGroup } from "naive-ui";-import { useI18n } from "vue-i18n";--const props = defineProps<{- value: boolean;- defaults: boolean;- readonly: boolean;-}>();--defineEmits<{- (event: "update:value", on: boolean): void;-}>();--const { t } = useI18n();--const getLabel = (value: boolean) => {- const label = value ? "true" : "false";- if (value === props.defaults) {- return `(${t("common.default")}) ${label}`;- }- return label;-};-</script>diff --git a/frontend/src/components/Plan/components/Configuration/GhostSection/FlagsForm/FlagsForm.vue b/frontend/src/components/Plan/components/Configuration/GhostSection/FlagsForm/FlagsForm.vuedeleted file mode 100644index a928da2f86..0000000000--- a/frontend/src/components/Plan/components/Configuration/GhostSection/FlagsForm/FlagsForm.vue+++ /dev/null@@ -1,124 +0,0 @@-<template>- <div- class="grid gap-y-4 gap-x-4 items-center text-sm"- style="grid-template-columns: auto 1fr"- >- <div- v-for="param in SupportedGhostParameters"- :key="param.key"- class="contents"- >- <div class="font-medium text-control">{{ param.key }}</div>- <div class="textinfolabel break-all">- <NInput- v-if="param.type === 'int'"- size="small"- :value="getIntValue(param)"- :allow-input="onlyAllowNumber"- :disabled="readonly"- :placeholder="param.defaults"- @update:value="setIntValue(param, parseInt($event, 10))"- />- <NInput- v-if="param.type === 'float'"- size="small"- :value="getFloatValue(param)"- :disabled="readonly"- :placeholder="param.defaults"- @update:value="setFloatValue(param, $event)"- />- <BoolFlag- v-if="param.type === 'bool'"- :value="getBoolValue(param)"- :defaults="param.defaults === 'true'"- :readonly="readonly"- @update:value="setBoolValue(param, $event)"- />- <NInput- v-if="param.type === 'string'"- size="small"- :value="getStringValue(param)"- :disabled="readonly"- :placeholder="param.defaults"- @update:value="setStringValue(param, $event)"- />- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import { NInput } from "naive-ui";-import { onlyAllowNumber } from "@/utils";-import BoolFlag from "./BoolFlag.vue";-import type { GhostParameter } from "./constants";-import { SupportedGhostParameters } from "./constants";--const props = defineProps<{- flags: Record<string, string>;- readonly: boolean;-}>();-const emit = defineEmits<{- (event: "update:flags", flags: Record<string, string>): void;-}>();--const getBoolValue = (param: GhostParameter) => {- const { key, defaults: value } = param;- if (props.flags[key] === "true") return true;- if (props.flags[key] === "false") return false;- return value === "true";-};-const getStringValue = (param: GhostParameter) => {- return props.flags[param.key] ?? "";-};-const getIntValue = (param: GhostParameter) => {- const intVal = parseInt(props.flags[param.key], 10);- if (Number.isNaN(intVal)) return undefined;- return String(intVal);-};-const getFloatValue = (param: GhostParameter) => {- return props.flags[param.key];-};--const setBoolValue = (param: GhostParameter, value: boolean) => {- const { key } = param;- const updated = { ...props.flags };- updated[key] = value ? "true" : "false";- if (updated[key] === param.defaults) {- delete updated[key];- }- emit("update:flags", updated);-};-const setStringValue = (param: GhostParameter, value: string) => {- const updated = { ...props.flags };- const { key } = param;- value = value.trim();- if (value) {- updated[key] = value;- } else {- delete updated[key];- }- emit("update:flags", updated);-};-const setIntValue = (param: GhostParameter, value: number) => {- const updated = { ...props.flags };- const { key } = param;- if (!Number.isNaN(value)) {- updated[key] = value.toString();- } else {- delete updated[key];- }- emit("update:flags", updated);-};-const setFloatValue = (param: GhostParameter, value: string) => {- const updated = { ...props.flags };- const { key } = param;- value = value.trim();- if (value !== "") {- updated[key] = value;- } else {- delete updated[key];- }- emit("update:flags", updated);-};-</script>diff --git a/frontend/src/components/Plan/components/Configuration/GhostSection/FlagsForm/constants.ts b/frontend/src/components/Plan/components/Configuration/GhostSection/FlagsForm/constants.tsdeleted file mode 100644index 040fcb4165..0000000000--- a/frontend/src/components/Plan/components/Configuration/GhostSection/FlagsForm/constants.ts+++ /dev/null@@ -1,64 +0,0 @@-export type GhostParameterType = "bool" | "int" | "float" | "string";--export type GhostParameter<T extends GhostParameterType = GhostParameterType> =- {- key: string;- type: T;- defaults: string;- };--export const SupportedGhostParameters: GhostParameter[] = [- { key: "attempt-instant-ddl", type: "bool", defaults: "true" },- { key: "allow-on-master", type: "bool", defaults: "true" },- { key: "assume-rbr", type: "bool", defaults: "false" },- { key: "assume-master-host", type: "bool", defaults: "false" },- { key: "chunk-size", type: "int", defaults: "1000" },- { key: "cut-over-lock-timeout-seconds", type: "int", defaults: "10" },- { key: "default-retries", type: "int", defaults: "60" },- { key: "dml-batch-size", type: "int", defaults: "10" },- { key: "exponential-backoff-max-interval", type: "int", defaults: "64" },- { key: "heart-beat-interval-millis", type: "int", defaults: "100" },- { key: "max-load", type: "string", defaults: "" },- { key: "max-lag-millis", type: "int", defaults: "1500" },- { key: "nice-ratio", type: "float", defaults: "0" },- { key: "switch-to-rbr", type: "bool", defaults: "false" },- { key: "throttle-control-replicas", type: "string", defaults: "" },-];--export const isBoolParameter = (- param: GhostParameter-): param is GhostParameter<"bool"> => {- return param.type === "bool";-};--export const isIntParameter = (- param: GhostParameter-): param is GhostParameter<"int"> => {- return param.type === "int";-};--export const isStringParameter = (- param: GhostParameter-): param is GhostParameter<"string"> => {- return param.type === "string";-};--export const isFloatParameter = (- param: GhostParameter-): param is GhostParameter<"float"> => {- return param.type === "float";-};--/**- * Returns the default ghost configuration from SupportedGhostParameters.- * Only includes parameters with non-empty defaults.- */-export const getDefaultGhostFlags = (): Record<string, string> => {- const defaults: Record<string, string> = {};- for (const param of SupportedGhostParameters) {- if (param.defaults !== "") {- defaults[param.key] = param.defaults;- }- }- return defaults;-};diff --git a/frontend/src/components/Plan/components/Configuration/GhostSection/FlagsForm/index.ts b/frontend/src/components/Plan/components/Configuration/GhostSection/FlagsForm/index.tsdeleted file mode 100644index 4347eddcde..0000000000--- a/frontend/src/components/Plan/components/Configuration/GhostSection/FlagsForm/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import FlagsForm from "./FlagsForm.vue";--export default FlagsForm;diff --git a/frontend/src/components/Plan/components/Configuration/GhostSection/GhostFlagsPanel.vue b/frontend/src/components/Plan/components/Configuration/GhostSection/GhostFlagsPanel.vuedeleted file mode 100644index d5ea4cc3e2..0000000000--- a/frontend/src/components/Plan/components/Configuration/GhostSection/GhostFlagsPanel.vue+++ /dev/null@@ -1,147 +0,0 @@-<template>- <Drawer :show="show" @close="close">- <DrawerContent- :title="title"- class="w-screen md:max-w-[calc(100vw-8rem)] md:w-[40vw]"- >- <template #default>- <div class="flex flex-col gap-y-4">- <p class="font-medium text-control">- {{ $t("task.online-migration.ghost-parameters") }}- <LearnMoreLink- class="text-sm ml-1"- url="https://github.com/github/gh-ost/blob/master/doc/command-line-flags.md"- />- </p>- <FlagsForm v-model:flags="flags" :readonly="readonly" />- </div>- </template>- <template #footer>- <div class="flex flex-row justify-end gap-x-2">- <NButton @click="close">{{ $t("common.cancel") }}</NButton>- <NTooltip :disabled="errors.length === 0">- <template #trigger>- <NButton type="primary" :disabled="!isDirty" @click="trySave">- {{ $t("common.save") }}- </NButton>- </template>- <template #default>- <ErrorList :errors="errors" />- </template>- </NTooltip>- </div>- </template>- </DrawerContent>- </Drawer>-</template>--<script setup lang="ts">-import { cloneDeep, isEqual } from "lodash-es";-import { NButton, NTooltip } from "naive-ui";-import { computed, ref, watch } from "vue";-import { useI18n } from "vue-i18n";-import LearnMoreLink from "@/components/LearnMoreLink.vue";-import ErrorList from "@/components/misc/ErrorList.vue";-import { updateSpecSheetWithStatement } from "@/components/Plan/logic";-import { Drawer, DrawerContent } from "@/components/v2";-import { pushNotification } from "@/store";-import { setSheetStatement } from "@/utils";-import { useSelectedSpec } from "../../SpecDetailView/context";-import {- getGhostConfig,- updateGhostConfig,-} from "../../StatementSection/directiveUtils";-import { useSpecSheet } from "../../StatementSection/useSpecSheet";-import { useGhostSettingContext } from "./context";-import FlagsForm from "./FlagsForm";--defineProps<{- show: boolean;-}>();--const emits = defineEmits<{- (e: "update:show", value: boolean): void;-}>();--const { t } = useI18n();-const { isCreating, allowChange, plan, events } = useGhostSettingContext();-const { selectedSpec } = useSelectedSpec();-const { sheet, sheetStatement, sheetReady, isSheetOversize } =- useSpecSheet(selectedSpec);--const title = computed(() => {- return t("task.online-migration.configure-ghost-parameters");-});--const flags = ref<Record<string, string>>({});--// Get current flags from sheet directive-const currentFlags = computed(() => {- if (!sheetReady.value) return {};- return getGhostConfig(sheetStatement.value) ?? {};-});--const isDirty = computed(() => {- return !isEqual(currentFlags.value, flags.value);-});--const errors = computed(() => {- const errors: string[] = [];- if (!isDirty.value) {- errors.push(t("task.online-migration.error.nothing-changed"));- }- return errors;-});--const readonly = computed(() => {- if (isCreating.value) return false;- return !allowChange.value || isSheetOversize.value;-});--const close = () => {- flags.value = cloneDeep(currentFlags.value);- emits("update:show", false);-};--const trySave = async () => {- if (errors.value.length > 0) {- return;- }-- const updatedStatement = updateGhostConfig(- sheetStatement.value,- cloneDeep(flags.value)- );-- if (isCreating.value) {- // When creating a plan, update the local sheet directly.- if (!sheet.value) return;- setSheetStatement(sheet.value, updatedStatement);- } else {- // For created plans, create new sheet and update plan/spec- await updateSpecSheetWithStatement(- plan.value,- selectedSpec.value,- updatedStatement- );- events.emit("update");- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });- }- close();-};--watch(- currentFlags,- (newFlags, oldFlags) => {- if (isEqual(newFlags, oldFlags)) {- return;- }- flags.value = cloneDeep(newFlags);- },- { immediate: true, deep: true }-);-</script>diff --git a/frontend/src/components/Plan/components/Configuration/GhostSection/GhostSection.vue b/frontend/src/components/Plan/components/Configuration/GhostSection/GhostSection.vuedeleted file mode 100644index acd1b86fa2..0000000000--- a/frontend/src/components/Plan/components/Configuration/GhostSection/GhostSection.vue+++ /dev/null@@ -1,68 +0,0 @@-<template>- <div class="flex flex-col gap-1">- <OptionRow>- <template #label>- {{ $t("task.online-migration.self") }}- </template>- <template #tooltip>- <i18n-t- tag="p"- keypath="issue.migration-mode.online.description"- class="whitespace-pre-line"- >- <template #link>- <LearnMoreLink- url="https://docs.bytebase.com/change-database/online-schema-migration-for-mysql?source=console"- color="light"- />- </template>- </i18n-t>- </template>- <template #suffix>- <NButton- v-if="enabled && allowChange"- tag="div"- size="tiny"- style="--n-padding: 0 5px"- @click="showFlagsPanel = true"- >- <template #icon>- <WrenchIcon class="w-4 h-4" />- </template>- {{ $t("task.online-migration.configure") }}- </NButton>- </template>- <GhostSwitch />- </OptionRow>-- <GhostFlagsPanel- :show="showFlagsPanel"- @update:show="(show) => (showFlagsPanel = show)"- />- </div>-</template>--<script lang="ts" setup>-import { WrenchIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { computed, ref } from "vue";-import LearnMoreLink from "@/components/LearnMoreLink.vue";-import { useSelectedSpec } from "../../SpecDetailView/context";-import { isGhostEnabled } from "../../StatementSection/directiveUtils";-import { useSpecSheet } from "../../StatementSection/useSpecSheet";-import OptionRow from "../OptionRow.vue";-import { useGhostSettingContext } from "./context";-import GhostFlagsPanel from "./GhostFlagsPanel.vue";-import GhostSwitch from "./GhostSwitch.vue";--const showFlagsPanel = ref(false);--const { allowChange } = useGhostSettingContext();-const { selectedSpec } = useSelectedSpec();-const { sheetStatement, sheetReady } = useSpecSheet(selectedSpec);--const enabled = computed(() => {- if (!sheetReady.value) return false;- return isGhostEnabled(sheetStatement.value);-});-</script>diff --git a/frontend/src/components/Plan/components/Configuration/GhostSection/GhostSwitch.vue b/frontend/src/components/Plan/components/Configuration/GhostSection/GhostSwitch.vuedeleted file mode 100644index ed72dddfb1..0000000000--- a/frontend/src/components/Plan/components/Configuration/GhostSection/GhostSwitch.vue+++ /dev/null@@ -1,203 +0,0 @@-<template>- <NTooltip :disabled="!tooltipMessage" :showArrow="false">- <template #trigger>- <NSwitch- size="small"- :value="enabled"- :disabled="!allowChange || isSheetOversize"- @update:value="toggleChecked"- />- </template>- <div class="max-w-sm">- <p class="opacity-80">{{ tooltipMessage }}</p>- <ErrorList v-if="errors.length > 0" :errors="errors" class="mt-2" />- <LearnMoreLink- v-if="databasesNotMeetingRequirements.length > 0"- :url="'https://docs.bytebase.com/change-database/online-schema-migration-for-mysql?source=console'"- color="light"- class="mt-1 text-sm"- />- </div>- </NTooltip>-</template>--<script setup lang="tsx">-import { NSwitch, NTooltip } from "naive-ui";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import LearnMoreLink from "@/components/LearnMoreLink.vue";-import type { ErrorItem } from "@/components/misc/ErrorList.vue";-import { default as ErrorList } from "@/components/misc/ErrorList.vue";-import {- targetsForSpec,- updateSpecSheetWithStatement,-} from "@/components/Plan/logic";-import { pushNotification } from "@/store";-import {- extractDatabaseResourceName,- getInstanceResource,- setSheetStatement,-} from "@/utils";-import { useSelectedSpec } from "../../SpecDetailView/context";-import {- getDefaultGhostConfig,- getGhostConfig,- isGhostEnabled,- updateGhostConfig,-} from "../../StatementSection/directiveUtils";-import { useSpecSheet } from "../../StatementSection/useSpecSheet";-import { allowGhostForDatabase } from "./common";-import { useGhostSettingContext } from "./context";--const { t } = useI18n();-const { isCreating, plan, allowChange, events, databases } =- useGhostSettingContext();-const { selectedSpec } = useSelectedSpec();-const { sheet, sheetStatement, sheetReady, isSheetOversize } =- useSpecSheet(selectedSpec);--const enabled = computed(() => {- if (!sheetReady.value) return false;- return isGhostEnabled(sheetStatement.value);-});--const errors = computed(() => {- const errors: ErrorItem[] = [];- const unsupportedDatabases = databases.value.filter(- (db) => !allowGhostForDatabase(db)- );- if (unsupportedDatabases.length > 0) {- errors.push(- t(- "task.online-migration.error.not-applicable.database-doesnt-meet-ghost-requirement",- {- database: unsupportedDatabases- .map((db) => extractDatabaseResourceName(db.name).databaseName)- .join(", "),- }- )- );- }-- // Check for databases with supported engine/version but missing backup location (bbdataarchive)- const missingBackupDatabases = databases.value.filter(- (db) => allowGhostForDatabase(db) && !db.backupAvailable- );- if (missingBackupDatabases.length > 0) {- // Ghost only supports MySQL/MariaDB, group by instance to avoid duplicates- const instanceMap = new Map<string, string>();- for (const db of missingBackupDatabases) {- const instanceResource = getInstanceResource(db);- if (!instanceMap.has(instanceResource.name)) {- instanceMap.set(instanceResource.name, instanceResource.title);- }- }- for (const [, instanceTitle] of instanceMap) {- errors.push(- t("plan.ghost.missing-backup-database", {- instance: instanceTitle,- })- );- }- }-- return errors;-});--// Computed properties for tooltip functionality-const specTargets = computed(() => {- if (!selectedSpec.value) return [];- return targetsForSpec(selectedSpec.value);-});--const checkedDatabasesCount = computed(() => {- return databases.value.length;-});--const totalDatabasesCount = computed(() => {- return specTargets.value.length;-});--const databasesNotMeetingRequirements = computed(() => {- return databases.value.filter((db) => {- // Check if database doesn't have backup available or doesn't allow ghost- if (!db.backupAvailable || !allowGhostForDatabase(db)) return true;- return false;- });-});--const tooltipMessage = computed(() => {- // Check if sheet is oversized- if (isSheetOversize.value) {- return t("issue.options-disabled-due-to-oversize");- }-- // Check if only some databases are checked- if (- checkedDatabasesCount.value < totalDatabasesCount.value &&- checkedDatabasesCount.value > 0- ) {- return t("plan.ghost.only-some-databases-checked");- }-- // Check if some databases don't meet requirements (show summary)- if (databasesNotMeetingRequirements.value.length > 0) {- // If there are specific errors, show a general summary- if (errors.value.length > 0) {- return t("plan.ghost.some-databases-have-issues", {- count: databasesNotMeetingRequirements.value.length,- });- }- // Otherwise show the databases that don't meet requirements- const dbNames = databasesNotMeetingRequirements.value- .map((db) => extractDatabaseResourceName(db.name).databaseName)- .join(", ");- return t("plan.ghost.some-databases-not-meeting-requirements", {- databases: dbNames,- });- }-- // If there are errors but all databases are selected, show a general error summary- if (errors.value.length > 0) {- return t("plan.ghost.configuration-has-issues", {- count: errors.value.length,- });- }-- return undefined;-});--const toggleChecked = async (on: boolean) => {- if (errors.value.length > 0) {- return;- }-- // Get current ghost config from sheet (to preserve flags when enabling)- const currentConfig = on- ? (getGhostConfig(sheetStatement.value) ?? getDefaultGhostConfig())- : undefined;- const updatedStatement = updateGhostConfig(- sheetStatement.value,- currentConfig- );-- if (isCreating.value) {- // When creating a plan, update the local sheet directly.- if (!sheet.value) return;- setSheetStatement(sheet.value, updatedStatement);- } else {- // For created plans, create new sheet and update plan/spec- await updateSpecSheetWithStatement(- plan.value,- selectedSpec.value,- updatedStatement- );- events.emit("update");- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });- }-};-</script>diff --git a/frontend/src/components/Plan/components/Configuration/GhostSection/common.ts b/frontend/src/components/Plan/components/Configuration/GhostSection/common.tsdeleted file mode 100644index 95c4b7d797..0000000000--- a/frontend/src/components/Plan/components/Configuration/GhostSection/common.ts+++ /dev/null@@ -1,28 +0,0 @@-import { Engine } from "@/types/proto-es/v1/common_pb";-import type { Database } from "@/types/proto-es/v1/database_service_pb";-import { getInstanceResource, semverCompare } from "@/utils";--export const GHOST_AVAILABLE_ENGINES = [Engine.MYSQL, Engine.MARIADB];--export const MIN_GHOST_SUPPORT_MYSQL_VERSION = "5.6.0";--export const MIN_GHOST_SUPPORT_MARIADB_VERSION = "10.6.0";--export const allowGhostForDatabase = (database: Database) => {- const instanceResource = getInstanceResource(database);- const engine = instanceResource.engine;- return (- (engine === Engine.MYSQL &&- semverCompare(- instanceResource.engineVersion,- MIN_GHOST_SUPPORT_MYSQL_VERSION,- "gte"- )) ||- (engine === Engine.MARIADB &&- semverCompare(- instanceResource.engineVersion,- MIN_GHOST_SUPPORT_MARIADB_VERSION,- "gte"- ))- );-};diff --git a/frontend/src/components/Plan/components/Configuration/GhostSection/context.ts b/frontend/src/components/Plan/components/Configuration/GhostSection/context.tsdeleted file mode 100644index ab6b35cd00..0000000000--- a/frontend/src/components/Plan/components/Configuration/GhostSection/context.ts+++ /dev/null@@ -1,76 +0,0 @@-import Emittery from "emittery";-import type { ComputedRef, InjectionKey, Ref } from "vue";-import { computed, inject, provide } from "vue";-import { targetsForSpec } from "@/components/Plan/logic";-import { useDatabaseV1Store } from "@/store";-import { isValidDatabaseName } from "@/types";-import type { Plan, Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";-import { getInstanceResource } from "@/utils";-import { GHOST_AVAILABLE_ENGINES } from "./common";--export const KEY = Symbol(- "bb.plan.setting.gh-ost"-) as InjectionKey<GhostSettingContext>;--export const useGhostSettingContext = () => {- return inject(KEY)!;-};--export const provideGhostSettingContext = (refs: {- isCreating: Ref<boolean>;- plan: Ref<Plan>;- selectedSpec: Ref<Plan_Spec | undefined>;- allowChange: ComputedRef<boolean>;-}) => {- const databaseStore = useDatabaseV1Store();-- const { isCreating, plan, selectedSpec, allowChange } = refs;-- const events = new Emittery<{- update: never;- }>();-- const databases = computed(() => {- const targets = selectedSpec.value- ? targetsForSpec(selectedSpec.value)- : [];- return targets- .map((target) => databaseStore.getDatabaseByName(target))- .filter((db) => isValidDatabaseName(db.name));- });-- const shouldShow = computed(() => {- if (!selectedSpec.value) return false;-- // Check if all databases support ghost (engine check)- const allDatabasesSupportGhost = databases.value.every((db) =>- GHOST_AVAILABLE_ENGINES.includes(getInstanceResource(db).engine)- );- if (!allDatabasesSupportGhost) return false;-- // Check if this is a change database config- if (selectedSpec.value.config?.case !== "changeDatabaseConfig") {- return false;- }- const config = selectedSpec.value.config.value;- // Show for sheet-based migrations only (not release-based).- // Release-based migrations don't support ghost configuration.- return !config.release;- });-- const context = {- isCreating,- selectedSpec,- plan,- shouldShow,- allowChange,- databases,- events,- };-- provide(KEY, context);-- return context;-};--type GhostSettingContext = ReturnType<typeof provideGhostSettingContext>;diff --git a/frontend/src/components/Plan/components/Configuration/GhostSection/index.ts b/frontend/src/components/Plan/components/Configuration/GhostSection/index.tsdeleted file mode 100644index e8bc849440..0000000000--- a/frontend/src/components/Plan/components/Configuration/GhostSection/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import GhostSection from "./GhostSection.vue";--export default GhostSection;diff --git a/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/InstanceRoleSection.vue b/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/InstanceRoleSection.vuedeleted file mode 100644index c8eadbcbc7..0000000000--- a/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/InstanceRoleSection.vue+++ /dev/null@@ -1,26 +0,0 @@-<template>- <OptionRow>- <template #label>- {{ $t("common.role.self") }}- </template>- <template #tooltip>- <div class="flex flex-col gap-y-1">- <p class="font-medium">- {{ $t("plan.spec.role-selection.title") }}- </p>- <p class="text-sm">- {{ $t("plan.spec.role-selection.description") }}- </p>- <p class="text-xs text-gray-400">- {{ $t("plan.spec.role-selection.technical-note") }}- </p>- </div>- </template>- <InstanceRoleSelect />- </OptionRow>-</template>--<script lang="ts" setup>-import OptionRow from "../OptionRow.vue";-import InstanceRoleSelect from "./InstanceRoleSelect.vue";-</script>diff --git a/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/InstanceRoleSelect.vue b/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/InstanceRoleSelect.vuedeleted file mode 100644index 1b86e39428..0000000000--- a/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/InstanceRoleSelect.vue+++ /dev/null@@ -1,178 +0,0 @@-<template>- <NTooltip :disabled="!isSheetOversize">- <template #trigger>- <NSelect- v-model:value="selectedRole"- class="w-36!"- size="small"- :options="options"- :placeholder="$t('instance.select-database-user')"- :filterable="true"- :virtual-scroll="true"- :fallback-option="false"- :consistent-menu-width="false"- :clearable="true"- :disabled="!allowChange || isSheetOversize"- :loading="loading"- />- </template>- {{ $t("issue.options-disabled-due-to-oversize") }}- </NTooltip>-</template>--<script setup lang="tsx">-import { create } from "@bufbuild/protobuf";-import { NSelect, NTooltip, type SelectOption } from "naive-ui";-import { computed, nextTick, ref, watch } from "vue";-import {- updateSpecSheetWithStatement,- usePlanContext,-} from "@/components/Plan/logic";-import { instanceRoleServiceClientConnect } from "@/connect";-import type { InstanceRole } from "@/types/proto-es/v1/instance_role_service_pb";-import { ListInstanceRolesRequestSchema } from "@/types/proto-es/v1/instance_role_service_pb";-import { extractDatabaseResourceName, setSheetStatement } from "@/utils";-import { useSelectedSpec } from "../../SpecDetailView/context";-import {- parseStatement,- updateRoleSetter,-} from "../../StatementSection/directiveUtils";-import { useSpecSheet } from "../../StatementSection/useSpecSheet";-import { useInstanceRoleSettingContext } from "./context";--const {- allowChange,- selectedRole: contextSelectedRole,- databases,- events,-} = useInstanceRoleSettingContext();-const { selectedSpec } = useSelectedSpec();-const { sheetStatement, sheet, sheetReady, isSheetOversize } =- useSpecSheet(selectedSpec);-const { plan, isCreating } = usePlanContext();--// Flag to prevent circular updates-const isUpdatingFromUI = ref(false);--const instanceRoles = ref<InstanceRole[]>([]);-const loading = ref(false);--const selectedRole = computed({- get: () => contextSelectedRole.value,- set: (value: string | undefined) => {- isUpdatingFromUI.value = true;- contextSelectedRole.value = value;- setRoleInStatement(value);- // Reset the flag after Vue's next tick to allow statement updates to propagate- nextTick(() => {- isUpdatingFromUI.value = false;- });- },-});--const database = computed(() => {- // For instance roles, we just need to get from the first database- // since all databases in a spec share the same instance- return databases.value[0];-});--const instanceName = computed(() => {- if (!database.value) return undefined;- return extractDatabaseResourceName(database.value.name).instance;-});--watch(- instanceName,- async () => {- if (!database.value || !instanceName.value) return;-- loading.value = true;- try {- const request = create(ListInstanceRolesRequestSchema, {- parent: instanceName.value,- });- const response =- await instanceRoleServiceClientConnect.listInstanceRoles(request);- instanceRoles.value = response.roles;- } finally {- loading.value = false;- }- },- {- immediate: true,- }-);--const options = computed(() => {- return instanceRoles.value.map<SelectOption>((instanceRole) => {- return {- value: instanceRole.roleName,- label: instanceRole.roleName,- };- });-});--// Initialize selected role from statement-const initializeFromStatement = () => {- if (!sheetReady.value || !sheetStatement.value) {- // If sheet is not ready or statement is empty, reset to undefined- contextSelectedRole.value = undefined;- return;- }-- const parsed = parseStatement(sheetStatement.value);- if (parsed.roleSetterBlock) {- // Extract role name from the role setter block- const match = parsed.roleSetterBlock.match(- /SET ROLE ([a-zA-Z_][a-zA-Z0-9_]{0,62});/- );- if (match) {- contextSelectedRole.value = match[1];- } else {- contextSelectedRole.value = undefined;- }- } else {- contextSelectedRole.value = undefined;- }-};--watch(- () => selectedSpec.value?.id,- () => {- initializeFromStatement();- },- {- immediate: true,- }-);--// Watch for sheet statement changes to update role-// Only update when statement changes externally, not when we change it ourselves-watch(- [sheetStatement, sheetReady],- () => {- if (!isUpdatingFromUI.value) {- initializeFromStatement();- }- },- { immediate: true }-);--const setRoleInStatement = async (roleName: string | undefined) => {- const updatedStatement = updateRoleSetter(sheetStatement.value, roleName);-- if (isCreating.value) {- // When creating a plan, update the local sheet directly.- if (!sheet.value) return;- setSheetStatement(sheet.value, updatedStatement);- } else {- // For created plans, create new sheet and update plan/spec- await updateSpecSheetWithStatement(- plan.value,- selectedSpec.value,- updatedStatement- );- }- events.emit("update");-};-</script>diff --git a/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/context.ts b/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/context.tsdeleted file mode 100644index 17cf6c84e9..0000000000--- a/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/context.ts+++ /dev/null@@ -1,82 +0,0 @@-import Emittery from "emittery";-import type { ComputedRef, InjectionKey, Ref } from "vue";-import { computed, inject, provide, ref } from "vue";-import { targetsForSpec } from "@/components/Plan/logic";-import { useDatabaseV1Store } from "@/store";-import { isValidDatabaseName } from "@/types";-import { Engine } from "@/types/proto-es/v1/common_pb";-import { type Plan, type Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";-import type { Project } from "@/types/proto-es/v1/project_service_pb";-import { getInstanceResource } from "@/utils";--export const KEY = Symbol(- "bb.plan.setting.instance-role"-) as InjectionKey<InstanceRoleSettingContext>;--export const useInstanceRoleSettingContext = () => {- return inject(KEY)!;-};--export const provideInstanceRoleSettingContext = (refs: {- isCreating: Ref<boolean>;- project: Ref<Project>;- plan: Ref<Plan>;- selectedSpec: Ref<Plan_Spec | undefined>;- allowChange: ComputedRef<boolean>;-}) => {- const databaseStore = useDatabaseV1Store();-- const { isCreating, plan, selectedSpec, allowChange } = refs;-- const events = new Emittery<{- update: never;- }>();-- const selectedRole = ref<string | undefined>(undefined);-- const databases = computed(() => {- const targets = selectedSpec.value- ? targetsForSpec(selectedSpec.value)- : [];- return targets- .map((target) => databaseStore.getDatabaseByName(target))- .filter((db) => isValidDatabaseName(db.name));- });-- const shouldShow = computed(() => {- if (!selectedSpec.value) return false;-- // Only show for PostgreSQL databases- const allDatabasesArePostgres = databases.value.every(- (db) => getInstanceResource(db).engine === Engine.POSTGRES- );- if (!allDatabasesArePostgres) return false;-- // Check if this is a database change spec.- if (selectedSpec.value.config?.case !== "changeDatabaseConfig") {- return false;- }- const config = selectedSpec.value.config.value;- // Show for MIGRATE type, but not SDL.- return !config.release;- });-- const context = {- isCreating,- selectedSpec,- plan,- shouldShow,- allowChange,- selectedRole,- databases,- events,- };-- provide(KEY, context);-- return context;-};--type InstanceRoleSettingContext = ReturnType<- typeof provideInstanceRoleSettingContext->;diff --git a/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/index.ts b/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/index.tsdeleted file mode 100644index dd0186438f..0000000000--- a/frontend/src/components/Plan/components/Configuration/InstanceRoleSection/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import InstanceRoleSection from "./InstanceRoleSection.vue";--export default InstanceRoleSection;diff --git a/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/IsolationLevelSection.vue b/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/IsolationLevelSection.vuedeleted file mode 100644index 08b2b85877..0000000000--- a/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/IsolationLevelSection.vue+++ /dev/null@@ -1,29 +0,0 @@-<template>- <OptionRow v-if="shouldShowCombined">- <template #label>- {{ $t("plan.isolation-level.self") }}- </template>- <template #tooltip>- {{ $t("plan.isolation-level.description") }}- </template>- <IsolationLevelSelect />- </OptionRow>-</template>--<script lang="ts" setup>-import { computed } from "vue";-import OptionRow from "../OptionRow.vue";-import { useTransactionModeSettingContext } from "../TransactionModeSection/context";-import { useIsolationLevelSettingContext } from "./context";-import IsolationLevelSelect from "./IsolationLevelSelect.vue";--// Check if isolation level section should be shown based on context-const { shouldShow } = useIsolationLevelSettingContext();--// Only show isolation level when transaction mode is ON and context allows it-const { transactionMode } = useTransactionModeSettingContext();--const shouldShowCombined = computed(() => {- return shouldShow.value && transactionMode.value === "on";-});-</script>diff --git a/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/IsolationLevelSelect.vue b/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/IsolationLevelSelect.vuedeleted file mode 100644index 9017febfdf..0000000000--- a/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/IsolationLevelSelect.vue+++ /dev/null@@ -1,144 +0,0 @@-<template>- <NTooltip :disabled="!isSheetOversize">- <template #trigger>- <NSelect- v-model:value="selectedIsolation"- class="w-36!"- size="small"- :options="options"- :placeholder="$t('plan.select-isolation-level')"- :filterable="true"- :virtual-scroll="true"- :fallback-option="false"- :consistent-menu-width="false"- :clearable="true"- :disabled="!allowChange || isSheetOversize"- />- </template>- {{ $t("issue.options-disabled-due-to-oversize") }}- </NTooltip>-</template>--<script setup lang="tsx">-import { NSelect, NTooltip, type SelectOption } from "naive-ui";-import { computed, nextTick, ref, watch } from "vue";-import {- updateSpecSheetWithStatement,- usePlanContext,-} from "@/components/Plan/logic";-import { setSheetStatement } from "@/utils";-import { useSelectedSpec } from "../../SpecDetailView/context";-import {- type IsolationLevel,- parseStatement,- updateIsolationLevel,-} from "../../StatementSection/directiveUtils";-import { useSpecSheet } from "../../StatementSection/useSpecSheet";-import { useIsolationLevelSettingContext } from "./context";--const {- allowChange,- isolationLevel: contextIsolationLevel,- events,-} = useIsolationLevelSettingContext();--const { selectedSpec } = useSelectedSpec();-const { sheetStatement, sheet, sheetReady, isSheetOversize } =- useSpecSheet(selectedSpec);-const { plan, isCreating } = usePlanContext();--// Flag to prevent circular updates-const isUpdatingFromUI = ref(false);--const selectedIsolation = computed({- get: () => contextIsolationLevel.value,- set: (value: IsolationLevel | null) => {- isUpdatingFromUI.value = true;- contextIsolationLevel.value = value || undefined;- setIsolationInStatement(value || undefined);- // Reset the flag after Vue's next tick to allow statement updates to propagate- nextTick(() => {- isUpdatingFromUI.value = false;- });- },-});--const options = computed(() => {- const opts: SelectOption[] = [- {- value: "READ_UNCOMMITTED",- label: "Read Uncommitted",- },- {- value: "READ_COMMITTED",- label: "Read Committed",- },- {- value: "REPEATABLE_READ",- label: "Repeatable Read",- },- {- value: "SERIALIZABLE",- label: "Serializable",- },- ];- return opts;-});--// Initialize isolation level from statement-const initializeFromStatement = () => {- if (!sheetReady.value || !sheetStatement.value) {- // If sheet is not ready or statement is empty, reset to undefined- contextIsolationLevel.value = undefined;- return;- }-- const parsed = parseStatement(sheetStatement.value);- contextIsolationLevel.value = parsed.isolationLevel;-};--watch(- () => selectedSpec.value?.id,- () => {- initializeFromStatement();- },- {- immediate: true,- }-);--// Watch for sheet statement changes to update isolation level-// Only update when statement changes externally, not when we change it ourselves-watch(- [sheetStatement, sheetReady],- () => {- if (!isUpdatingFromUI.value) {- initializeFromStatement();- }- },- { immediate: true }-);--const setIsolationInStatement = async (- isolationLevel: IsolationLevel | undefined-) => {- const updatedStatement = updateIsolationLevel(- sheetStatement.value,- isolationLevel- );-- if (isCreating.value) {- // When creating a plan, update the local sheet directly.- if (!sheet.value) return;- setSheetStatement(sheet.value, updatedStatement);- } else {- // For created plans, create new sheet and update plan/spec- await updateSpecSheetWithStatement(- plan.value,- selectedSpec.value,- updatedStatement- );- }- events.emit("update");-};-</script>diff --git a/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/context.ts b/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/context.tsdeleted file mode 100644index 98ecd87452..0000000000--- a/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/context.ts+++ /dev/null@@ -1,84 +0,0 @@-import Emittery from "emittery";-import type { ComputedRef, InjectionKey, Ref } from "vue";-import { computed, inject, provide, ref } from "vue";-import { targetsForSpec } from "@/components/Plan/logic";-import { useDatabaseV1Store } from "@/store";-import { isValidDatabaseName } from "@/types";-import { Engine } from "@/types/proto-es/v1/common_pb";-import { type Plan, type Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";-import type { Project } from "@/types/proto-es/v1/project_service_pb";-import { getInstanceResource } from "@/utils";-import type { IsolationLevel } from "../../StatementSection/directiveUtils";--export const KEY = Symbol(- "bb.plan.setting.isolation-level"-) as InjectionKey<IsolationLevelSettingContext>;--type IsolationLevelSettingContext = ReturnType<- typeof provideIsolationLevelSettingContext->;--export const useIsolationLevelSettingContext = () => {- return inject(KEY)!;-};--export const provideIsolationLevelSettingContext = (refs: {- isCreating: Ref<boolean>;- project: Ref<Project>;- plan: Ref<Plan>;- selectedSpec: Ref<Plan_Spec | undefined>;- allowChange: ComputedRef<boolean>;-}) => {- const databaseStore = useDatabaseV1Store();-- const { isCreating, plan, selectedSpec, allowChange } = refs;-- const events = new Emittery<{- update: never;- }>();-- const isolationLevel = ref<IsolationLevel | undefined>(undefined);-- const databases = computed(() => {- const targets = selectedSpec.value- ? targetsForSpec(selectedSpec.value)- : [];- return targets- .map((target) => databaseStore.getDatabaseByName(target))- .filter((db) => isValidDatabaseName(db.name));- });-- const shouldShow = computed(() => {- if (!selectedSpec.value) return false;-- // Only show for MySQL/MariaDB/TiDB for now- const supportedEngines = [Engine.MYSQL, Engine.MARIADB, Engine.TIDB];- const allDatabasesSupported = databases.value.every((db) =>- supportedEngines.includes(getInstanceResource(db).engine)- );- if (!allDatabasesSupported) return false;-- // Check if this is a DDL or DML change- if (selectedSpec.value.config?.case !== "changeDatabaseConfig") {- return false;- }- const config = selectedSpec.value.config.value;- // Show for all MIGRATE types (DDL, DML, Ghost), but not SDL- return !config.release;- });-- const context = {- isCreating,- selectedSpec,- plan,- shouldShow,- allowChange,- isolationLevel,- databases,- events,- };-- provide(KEY, context);-- return context;-};diff --git a/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/index.ts b/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/index.tsdeleted file mode 100644index b95acd8cd3..0000000000--- a/frontend/src/components/Plan/components/Configuration/IsolationLevelSection/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import IsolationLevelSection from "./IsolationLevelSection.vue";--export default IsolationLevelSection;diff --git a/frontend/src/components/Plan/components/Configuration/OptionRow.vue b/frontend/src/components/Plan/components/Configuration/OptionRow.vuedeleted file mode 100644index 0114be0792..0000000000--- a/frontend/src/components/Plan/components/Configuration/OptionRow.vue+++ /dev/null@@ -1,29 +0,0 @@-<template>- <div class="flex items-center gap-2">- <!-- Label + Tooltip -->- <div class="flex items-center gap-1">- <label class="text-sm text-control-placeholder whitespace-nowrap">- <slot name="label" />- </label>- <NTooltip v-if="$slots.tooltip">- <template #trigger>- <heroicons:information-circle- class="w-3.5 h-3.5 text-control-light cursor-help"- />- </template>- <template #default>- <div class="max-w-xs">- <slot name="tooltip" />- </div>- </template>- </NTooltip>- <slot name="suffix" />- </div>- <!-- Value -->- <slot />- </div>-</template>--<script lang="ts" setup>-import { NTooltip } from "naive-ui";-</script>diff --git a/frontend/src/components/Plan/components/Configuration/PreBackupSection/PreBackupSection.vue b/frontend/src/components/Plan/components/Configuration/PreBackupSection/PreBackupSection.vuedeleted file mode 100644index 4ee9f76028..0000000000--- a/frontend/src/components/Plan/components/Configuration/PreBackupSection/PreBackupSection.vue+++ /dev/null@@ -1,16 +0,0 @@-<template>- <OptionRow>- <template #label>- {{ $t("task.prior-backup") }}- </template>- <template #tooltip>- {{ $t("task.prior-backup-tips") }}- </template>- <PreBackupSwitch />- </OptionRow>-</template>--<script lang="ts" setup>-import OptionRow from "../OptionRow.vue";-import PreBackupSwitch from "./PreBackupSwitch.vue";-</script>diff --git a/frontend/src/components/Plan/components/Configuration/PreBackupSection/PreBackupSwitch.vue b/frontend/src/components/Plan/components/Configuration/PreBackupSection/PreBackupSwitch.vuedeleted file mode 100644index 8488c8ad8a..0000000000--- a/frontend/src/components/Plan/components/Configuration/PreBackupSection/PreBackupSwitch.vue+++ /dev/null@@ -1,208 +0,0 @@-<template>- <NTooltip :disabled="!tooltipMessage" :showArrow="false">- <template #trigger>- <NSwitch- size="small"- :value="enabled"- :disabled="- !allowChange ||- (!enabled &&- (databasesNotMeetingRequirements.length > 0 || errors.length > 0))- "- @update:value="(on) => handleToggle(on)"- />- </template>- <div class="max-w-sm">- <p class="opacity-80">{{ tooltipMessage }}</p>- <ErrorList v-if="errors.length > 0" :errors="errors" class="mt-2" />- <LearnMoreLink- v-if="databasesNotMeetingRequirements.length > 0"- :url="'https://docs.bytebase.com/change-database/rollback-data-changes?source=console'"- color="light"- class="mt-1 text-sm"- />- </div>- </NTooltip>-</template>--<script lang="ts" setup>-import { NSwitch, NTooltip } from "naive-ui";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import LearnMoreLink from "@/components/LearnMoreLink.vue";-import type { ErrorItem } from "@/components/misc/ErrorList.vue";-import ErrorList from "@/components/misc/ErrorList.vue";-import { targetsForSpec } from "@/components/Plan/logic";-import { pushNotification } from "@/store";-import { Engine } from "@/types/proto-es/v1/common_pb";-import { extractDatabaseResourceName, getInstanceResource } from "@/utils";-import { BACKUP_AVAILABLE_ENGINES } from "./common";-import { usePreBackupSettingContext } from "./context";--const { t } = useI18n();-const { enabled, allowChange, databases, toggle, selectedSpec } =- usePreBackupSettingContext();--// Compute detailed errors for ErrorList-const errors = computed(() => {- const errors: ErrorItem[] = [];-- // Check for unsupported database engines- const unsupportedEngineDatabases = databases.value.filter(- (db) => !BACKUP_AVAILABLE_ENGINES.includes(getInstanceResource(db).engine)- );- if (unsupportedEngineDatabases.length > 0) {- errors.push(- t("database.engine-not-supported-for-backup", {- databases: unsupportedEngineDatabases- .map(- (db) =>- `${extractDatabaseResourceName(db.name).databaseName} (${getInstanceResource(db).engine})`- )- .join(", "),- })- );- }-- // Check for databases with supported engines but missing backup location- const missingBackupLocationDatabases = databases.value.filter(- (db) =>- BACKUP_AVAILABLE_ENGINES.includes(getInstanceResource(db).engine) &&- !db.backupAvailable- );-- if (missingBackupLocationDatabases.length > 0) {- // Group by engine type for clearer messages- const postgresDBs = missingBackupLocationDatabases.filter(- (db) => getInstanceResource(db).engine === Engine.POSTGRES- );- const mysqlLikeDBs = missingBackupLocationDatabases.filter((db) => {- const engine = getInstanceResource(db).engine;- return (- engine === Engine.MYSQL ||- engine === Engine.TIDB ||- engine === Engine.MSSQL- );- });- const oracleDBs = missingBackupLocationDatabases.filter(- (db) => getInstanceResource(db).engine === Engine.ORACLE- );-- // PostgreSQL: requires schema 'bbdataarchive' within the database- for (const db of postgresDBs) {- errors.push(- t("plan.pre-backup.missing-backup-schema-postgres", {- database: extractDatabaseResourceName(db.name).databaseName,- })- );- }-- // MySQL/TiDB/MSSQL: requires database 'bbdataarchive' on the instance- // Group by instance to avoid duplicate messages- const mysqlInstanceMap = new Map<string, string>();- for (const db of mysqlLikeDBs) {- const instanceResource = getInstanceResource(db);- if (!mysqlInstanceMap.has(instanceResource.name)) {- mysqlInstanceMap.set(instanceResource.name, instanceResource.title);- }- }- for (const [, instanceTitle] of mysqlInstanceMap) {- errors.push(- t("plan.pre-backup.missing-backup-database", {- instance: instanceTitle,- })- );- }-- // Oracle: requires database 'BBDATAARCHIVE' on the instance- // Group by instance to avoid duplicate messages- const oracleInstanceMap = new Map<string, string>();- for (const db of oracleDBs) {- const instanceResource = getInstanceResource(db);- if (!oracleInstanceMap.has(instanceResource.name)) {- oracleInstanceMap.set(instanceResource.name, instanceResource.title);- }- }- for (const [, instanceTitle] of oracleInstanceMap) {- errors.push(- t("plan.pre-backup.missing-backup-database-oracle", {- instance: instanceTitle,- })- );- }- }-- return errors;-});--// Computed properties for new tooltip functionality-const specTargets = computed(() => {- if (!selectedSpec.value) return [];- return targetsForSpec(selectedSpec.value);-});--const checkedDatabasesCount = computed(() => {- return databases.value.length;-});--const totalDatabasesCount = computed(() => {- return specTargets.value.length;-});--const databasesNotMeetingRequirements = computed(() => {- return databases.value.filter((db) => {- // Check if database doesn't have backup available- if (!db.backupAvailable) return true;- // Check if database engine is not supported- if (!BACKUP_AVAILABLE_ENGINES.includes(getInstanceResource(db).engine)) {- return true;- }- return false;- });-});--const tooltipMessage = computed(() => {- // Check if only some databases are checked- if (- checkedDatabasesCount.value < totalDatabasesCount.value &&- checkedDatabasesCount.value > 0- ) {- return t("plan.pre-backup.only-some-databases-checked");- }-- // Check if some databases don't meet requirements (show summary)- if (databasesNotMeetingRequirements.value.length > 0) {- // If there are specific errors, show a general summary- if (errors.value.length > 0) {- return t("plan.pre-backup.some-databases-have-issues", {- count: databasesNotMeetingRequirements.value.length,- });- }- // Otherwise show the databases that don't meet requirements- const dbNames = databasesNotMeetingRequirements.value- .map((db) => extractDatabaseResourceName(db.name).databaseName)- .join(", ");- return t("plan.pre-backup.some-databases-not-meeting-requirements", {- databases: dbNames,- });- }-- // If there are errors but all databases are selected, show a general error summary- if (errors.value.length > 0) {- return t("plan.pre-backup.configuration-has-issues", {- count: errors.value.length,- });- }-- return undefined;-});--const handleToggle = async (on: boolean) => {- await toggle(on);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });-};-</script>diff --git a/frontend/src/components/Plan/components/Configuration/PreBackupSection/common.ts b/frontend/src/components/Plan/components/Configuration/PreBackupSection/common.tsdeleted file mode 100644index fb67e272f3..0000000000--- a/frontend/src/components/Plan/components/Configuration/PreBackupSection/common.ts+++ /dev/null@@ -1,9 +0,0 @@-import { Engine } from "@/types/proto-es/v1/common_pb";--export const BACKUP_AVAILABLE_ENGINES = [- Engine.MYSQL,- Engine.TIDB,- Engine.MSSQL,- Engine.ORACLE,- Engine.POSTGRES,-];diff --git a/frontend/src/components/Plan/components/Configuration/PreBackupSection/context.ts b/frontend/src/components/Plan/components/Configuration/PreBackupSection/context.tsdeleted file mode 100644index 945fa69ef4..0000000000--- a/frontend/src/components/Plan/components/Configuration/PreBackupSection/context.ts+++ /dev/null@@ -1,138 +0,0 @@-import { create } from "@bufbuild/protobuf";-import Emittery from "emittery";-import { cloneDeep } from "lodash-es";-import {- type ComputedRef,- computed,- type InjectionKey,- inject,- provide,- type Ref,- unref,-} from "vue";-import { isDatabaseChangeSpec, targetsForSpec } from "@/components/Plan/logic";-import { planServiceClientConnect } from "@/connect";-import { useDatabaseV1Store } from "@/store";-import { isValidDatabaseName } from "@/types";-import {- type Plan,- type Plan_Spec,- UpdatePlanRequestSchema,-} from "@/types/proto-es/v1/plan_service_pb";-import type { Project } from "@/types/proto-es/v1/project_service_pb";-import { getInstanceResource } from "@/utils";-import { BACKUP_AVAILABLE_ENGINES } from "./common";--const KEY = Symbol(- "bb.plan.setting.pre-backup"-) as InjectionKey<PreBackupSettingContext>;--export const usePreBackupSettingContext = () => {- return inject(KEY)!;-};--export const providePreBackupSettingContext = (refs: {- isCreating: Ref<boolean>;- project: Ref<Project>;- plan: Ref<Plan>;- selectedSpec: Ref<Plan_Spec | undefined>;- allowChange: ComputedRef<boolean>;-}) => {- const databaseStore = useDatabaseV1Store();- const { isCreating, plan, selectedSpec, allowChange } = refs;-- const events = new Emittery<{- update: never;- }>();-- const databases = computed(() => {- const targets = selectedSpec.value- ? targetsForSpec(selectedSpec.value)- : [];- return targets- .map((target) => databaseStore.getDatabaseByName(target))- .filter((db) => isValidDatabaseName(db.name));- });-- const shouldShow = computed((): boolean => {- if (- !selectedSpec.value ||- selectedSpec.value.config?.case !== "changeDatabaseConfig"- ) {- return false;- }- if (isDatabaseChangeSpec(selectedSpec.value)) {- // If any of the databases in the spec is not supported, do not show.- if (- !databases.value.every((db) =>- BACKUP_AVAILABLE_ENGINES.includes(getInstanceResource(db).engine)- )- ) {- return false;- }- }- return true;- });-- const enabled = computed((): boolean => {- if (selectedSpec.value?.config?.case === "changeDatabaseConfig") {- return Boolean(selectedSpec.value.config.value.enablePriorBackup);- }- return false;- });-- const toggle = async (on: boolean) => {- if (isCreating.value) {- if (selectedSpec.value?.config?.case === "changeDatabaseConfig") {- if (on) {- selectedSpec.value.config.value.enablePriorBackup = true;- } else {- selectedSpec.value.config.value.enablePriorBackup = false;- }- }- } else {- const planPatch = cloneDeep(unref(plan));- const spec = planPatch.specs.find((s) => {- return s.id === selectedSpec.value?.id;- });- if (!planPatch || !spec || spec.config.case !== "changeDatabaseConfig") {- // Should not reach here.- throw new Error(- "Plan or spec is not defined. Cannot update pre-backup setting."- );- }- if (on) {- spec.config.value.enablePriorBackup = true;- } else {- spec.config.value.enablePriorBackup = false;- }-- const request = create(UpdatePlanRequestSchema, {- plan: planPatch,- updateMask: { paths: ["specs"] },- });- await planServiceClientConnect.updatePlan(request);- }-- // Emit the update event.- events.emit("update");- };-- const context = {- shouldShow,- enabled,- allowChange,- databases,- events,- toggle,- selectedSpec,- };-- provide(KEY, context);-- return context;-};--type PreBackupSettingContext = ReturnType<- typeof providePreBackupSettingContext->;diff --git a/frontend/src/components/Plan/components/Configuration/PreBackupSection/index.ts b/frontend/src/components/Plan/components/Configuration/PreBackupSection/index.tsdeleted file mode 100644index 9ded4d6044..0000000000--- a/frontend/src/components/Plan/components/Configuration/PreBackupSection/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import PreBackupSection from "./PreBackupSection.vue";--export default PreBackupSection;diff --git a/frontend/src/components/Plan/components/Configuration/TransactionModeSection/TransactionModeSection.vue b/frontend/src/components/Plan/components/Configuration/TransactionModeSection/TransactionModeSection.vuedeleted file mode 100644index 754ed16ddf..0000000000--- a/frontend/src/components/Plan/components/Configuration/TransactionModeSection/TransactionModeSection.vue+++ /dev/null@@ -1,29 +0,0 @@-<template>- <OptionRow>- <template #label>- {{ $t("issue.transaction-mode.label") }}- </template>- <template #tooltip>- <div class="flex flex-col gap-y-1">- <div v-if="transactionMode === 'on'">- {{ $t("issue.transaction-mode.on-tooltip") }}- </div>- <div v-else>- {{ $t("issue.transaction-mode.off-tooltip") }}- </div>- <div class="text-sm text-gray-400">- {{ $t("issue.transaction-mode.execution-order-note") }}- </div>- </div>- </template>- <TransactionModeSwitch />- </OptionRow>-</template>--<script lang="ts" setup>-import OptionRow from "../OptionRow.vue";-import { useTransactionModeSettingContext } from "./context";-import TransactionModeSwitch from "./TransactionModeSwitch.vue";--const { transactionMode } = useTransactionModeSettingContext();-</script>diff --git a/frontend/src/components/Plan/components/Configuration/TransactionModeSection/TransactionModeSwitch.vue b/frontend/src/components/Plan/components/Configuration/TransactionModeSection/TransactionModeSwitch.vuedeleted file mode 100644index 86c126c957..0000000000--- a/frontend/src/components/Plan/components/Configuration/TransactionModeSection/TransactionModeSwitch.vue+++ /dev/null@@ -1,109 +0,0 @@-<template>- <NTooltip :disabled="!isSheetOversize">- <template #trigger>- <NSwitch- v-model:value="isTransactionOn"- size="small"- :disabled="!allowChange || isSheetOversize"- />- </template>- {{ $t("issue.options-disabled-due-to-oversize") }}- </NTooltip>-</template>--<script setup lang="tsx">-import { NSwitch, NTooltip } from "naive-ui";-import { computed, nextTick, ref, watch } from "vue";-import {- updateSpecSheetWithStatement,- usePlanContext,-} from "@/components/Plan/logic";-import { getDefaultTransactionMode, setSheetStatement } from "@/utils";-import { useSelectedSpec } from "../../SpecDetailView/context";-import {- parseStatement,- updateTransactionMode,-} from "../../StatementSection/directiveUtils";-import { useSpecSheet } from "../../StatementSection/useSpecSheet";-import { useTransactionModeSettingContext } from "./context";--const { allowChange, transactionMode, events } =- useTransactionModeSettingContext();-const { selectedSpec } = useSelectedSpec();-const { sheetStatement, sheet, sheetReady, isSheetOversize } =- useSpecSheet(selectedSpec);-const { plan, isCreating } = usePlanContext();--// Flag to prevent circular updates-const isUpdatingFromUI = ref(false);--const isTransactionOn = computed({- get: () => transactionMode.value === "on",- set: (value: boolean) => {- isUpdatingFromUI.value = true;- transactionMode.value = value ? "on" : "off";- updateStatementWithTransactionMode();- // Reset the flag after Vue's next tick to allow statement updates to propagate- nextTick(() => {- isUpdatingFromUI.value = false;- });- },-});--// Initialize transaction mode from statement-const initializeFromStatement = () => {- if (!sheetReady.value || !sheetStatement.value) {- // If sheet is not ready or statement is empty, use default- transactionMode.value = getDefaultTransactionMode() ? "on" : "off";- return;- }-- const parsed = parseStatement(sheetStatement.value);- if (parsed.transactionMode !== undefined) {- transactionMode.value = parsed.transactionMode;- } else {- transactionMode.value = getDefaultTransactionMode() ? "on" : "off";- }-};--// Watch for spec changes to reset defaults-watch(- () => selectedSpec.value?.id,- () => {- initializeFromStatement();- },- { immediate: true }-);--// Watch for sheet statement changes to update transaction mode-// Only update when statement changes externally, not when we change it ourselves-watch(- [sheetStatement, sheetReady],- () => {- if (!isUpdatingFromUI.value) {- initializeFromStatement();- }- },- { immediate: true }-);--// Update statement when transaction mode changes-const updateStatementWithTransactionMode = async () => {- const mode = transactionMode.value;- const updatedStatement = updateTransactionMode(sheetStatement.value, mode);-- if (isCreating.value) {- // When creating a plan, update the local sheet directly.- if (!sheet.value) return;- setSheetStatement(sheet.value, updatedStatement);- } else {- // For created plans, create new sheet and update plan/spec- await updateSpecSheetWithStatement(- plan.value,- selectedSpec.value,- updatedStatement- );- }- events.emit("update");-};-</script>diff --git a/frontend/src/components/Plan/components/Configuration/TransactionModeSection/context.ts b/frontend/src/components/Plan/components/Configuration/TransactionModeSection/context.tsdeleted file mode 100644index 5d4523c835..0000000000--- a/frontend/src/components/Plan/components/Configuration/TransactionModeSection/context.ts+++ /dev/null@@ -1,85 +0,0 @@-import Emittery from "emittery";-import type { ComputedRef, InjectionKey, Ref } from "vue";-import { computed, inject, provide, ref } from "vue";-import { targetsForSpec } from "@/components/Plan/logic";-import { useDatabaseV1Store } from "@/store";-import { isValidDatabaseName } from "@/types";-import { type Plan, type Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";-import type { Project } from "@/types/proto-es/v1/project_service_pb";-import {- getInstanceResource,- instanceV1SupportsTransactionMode,-} from "@/utils";--export const KEY = Symbol(- "bb.plan.setting.transaction-mode"-) as InjectionKey<TransactionModeSettingContext>;--export const useTransactionModeSettingContext = () => {- return inject(KEY)!;-};--export const provideTransactionModeSettingContext = (refs: {- isCreating: Ref<boolean>;- project: Ref<Project>;- plan: Ref<Plan>;- selectedSpec: Ref<Plan_Spec | undefined>;- allowChange: ComputedRef<boolean>;-}) => {- const databaseStore = useDatabaseV1Store();-- const { isCreating, plan, selectedSpec, allowChange } = refs;-- const events = new Emittery<{- update: never;- }>();-- const transactionMode = ref<"on" | "off">("on");-- const databases = computed(() => {- const targets = selectedSpec.value- ? targetsForSpec(selectedSpec.value)- : [];- return targets- .map((target) => databaseStore.getDatabaseByName(target))- .filter((db) => isValidDatabaseName(db.name));- });-- const shouldShow = computed(() => {- if (!selectedSpec.value) return false;-- // Check if all databases support transaction mode- const allDatabasesSupportTransactionMode = databases.value.every((db) =>- instanceV1SupportsTransactionMode(getInstanceResource(db).engine)- );- if (!allDatabasesSupportTransactionMode) return false;-- // Check if this is a DDL or DML change- if (selectedSpec.value.config?.case !== "changeDatabaseConfig") {- return false;- }- const config = selectedSpec.value.config.value;- // Show for sheet-based migrations only (not release-based).- // Release-based migrations don't support transaction mode configuration.- return !config.release;- });-- const context = {- isCreating,- selectedSpec,- plan,- shouldShow,- allowChange,- transactionMode,- databases,- events,- };-- provide(KEY, context);-- return context;-};--type TransactionModeSettingContext = ReturnType<- typeof provideTransactionModeSettingContext->;diff --git a/frontend/src/components/Plan/components/Configuration/TransactionModeSection/index.ts b/frontend/src/components/Plan/components/Configuration/TransactionModeSection/index.tsdeleted file mode 100644index f87274efbe..0000000000--- a/frontend/src/components/Plan/components/Configuration/TransactionModeSection/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import TransactionModeSection from "./TransactionModeSection.vue";--export default TransactionModeSection;diff --git a/frontend/src/components/Plan/components/Configuration/index.ts b/frontend/src/components/Plan/components/Configuration/index.tsdeleted file mode 100644index 51ecbcb2bb..0000000000--- a/frontend/src/components/Plan/components/Configuration/index.ts+++ /dev/null@@ -1,7 +0,0 @@-import Configuration from "./Configuration.vue";-import GhostSection from "./GhostSection";-import PreBackupSection from "./PreBackupSection";--export default Configuration;--export { PreBackupSection, GhostSection };diff --git a/frontend/src/components/Plan/components/ExportOption/ExportFormatSelector.vue b/frontend/src/components/Plan/components/ExportOption/ExportFormatSelector.vuedeleted file mode 100644index a85f1bdb46..0000000000--- a/frontend/src/components/Plan/components/ExportOption/ExportFormatSelector.vue+++ /dev/null@@ -1,47 +0,0 @@-<template>- <NRadioGroup v-if="editable" :value="format" @update:value="handleUpdate">- <NRadio- v-for="formatItem in availableExportFormats"- :key="formatItem"- :value="formatItem"- :label="ExportFormat[formatItem]"- />- </NRadioGroup>- <template v-else>- <span class="text-sm font-medium leading-6">{{- ExportFormat[format]- }}</span>- </template>-</template>--<script setup lang="ts">-import { NRadio, NRadioGroup } from "naive-ui";-import { computed, onMounted } from "vue";-import { ExportFormat } from "@/types/proto-es/v1/common_pb";--const props = defineProps<{- format: ExportFormat;- editable?: boolean;-}>();--const emit = defineEmits<{- (event: "update:format", value: ExportFormat): void;-}>();--const availableExportFormats = computed(() => [- ExportFormat.JSON,- ExportFormat.CSV,- ExportFormat.SQL,- ExportFormat.XLSX,-]);--const handleUpdate = (value: ExportFormat) => {- emit("update:format", value);-};--onMounted(() => {- if (!availableExportFormats.value.includes(props.format)) {- handleUpdate(availableExportFormats.value[0]);- }-});-</script>diff --git a/frontend/src/components/Plan/components/ExportOption/ExportPasswordInputer.vue b/frontend/src/components/Plan/components/ExportOption/ExportPasswordInputer.vuedeleted file mode 100644index e20883ab5a..0000000000--- a/frontend/src/components/Plan/components/ExportOption/ExportPasswordInputer.vue+++ /dev/null@@ -1,55 +0,0 @@-<template>- <div class="flex items-start md:items-center flex-col md:flex-row gap-4">- <div class="flex items-center gap-4">- <span class="text-sm">- {{ $t("export-data.password-optional") }}- </span>- <NSwitch- v-model:value="encryptEnabled"- :disabled="!editable"- size="small"- />- </div>- <div v-if="editable && encryptEnabled" class="flex items-center gap-4">- <span class="text-sm">- {{ $t("common.password") }}- <RequiredStar />- </span>- <NInput- :value="password"- class="w-auto!"- size="small"- type="password"- :input-props="{ autocomplete: 'new-password' }"- :placeholder="$t('common.password')"- @update:value="(val) => $emit('update:password', val)"- />- </div>- </div>-</template>--<script setup lang="ts">-import { NInput, NSwitch } from "naive-ui";-import { ref, watch } from "vue";-import RequiredStar from "@/components/RequiredStar.vue";--const props = defineProps<{- password?: string;- editable?: boolean;-}>();--const emit = defineEmits<{- (event: "update:password", value: string): void;-}>();--const encryptEnabled = ref(Boolean(props.password));--watch(- () => encryptEnabled.value,- (encryptEnabled) => {- if (!encryptEnabled) {- emit("update:password", "");- }- }-);-</script>diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/ACTIONS.md b/frontend/src/components/Plan/components/HeaderSection/Actions/ACTIONS.mddeleted file mode 100644index d5397155d5..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/ACTIONS.md+++ /dev/null@@ -1,330 +0,0 @@-# Plan Header Actions Documentation--This document describes all available actions in the Plan Header section, including visibility rules, permissions, and disabled states.--## Architecture--The action system uses a **Registry Pattern** for maintainability and type safety.--### Core Components--```-Actions/-├── registry/ # Action Registry (source of truth)-│ ├── types.ts # ActionContext, ActionDefinition interfaces-│ ├── context.ts # buildActionContext() - context builder-│ ├── useActionRegistry.ts # Main composable-│ ├── actions/-│ │ ├── plan.ts # PLAN_CLOSE, PLAN_REOPEN-│ │ ├── issue.ts # ISSUE_CREATE, ISSUE_REVIEW, ISSUE_STATUS_*-│ │ └── rollout.ts # ROLLOUT_CREATE, ROLLOUT_START, ROLLOUT_CANCEL, EXPORT_DOWNLOAD-│ └── components/-│ ├── ActionButton.vue # Single action button-│ ├── ActionDropdown.vue # Secondary actions dropdown-│ └── IssueReviewButton.vue # Review popover with approve/reject/comment-└── Actions.vue # Main orchestrator-```--### Key Concepts--**ActionContext**: Single reactive object containing all state needed for action decisions:-- Entities: plan, issue, rollout, project-- Derived flags: isIssueOnly, isExportPlan, hasDeferredRollout, isCreator-- Permissions: updatePlan, createIssue, updateIssue, createRollout, runTasks-- Validation: hasEmptySpec, planChecksRunning, planChecksFailed--**hasDeferredRollout**: Plans where rollout is created on-demand (export, create database). For these plans:-- ROLLOUT_CREATE is hidden; ROLLOUT_START creates rollout and runs tasks in one step-- Issues auto-resolve when task completes--**ActionDefinition**: Declarative action with pure functions:-```typescript-interface ActionDefinition {- id: UnifiedActionType;- label: (ctx: ActionContext) => string;- buttonType: "primary" | "success" | "default";- category: ActionCategory | ((ctx: ActionContext) => ActionCategory); // Can be dynamic- priority: number; // Lower = higher priority- isVisible: (ctx: ActionContext) => boolean;- isDisabled: (ctx: ActionContext) => boolean;- disabledReason: (ctx: ActionContext) => string | undefined;- executeType: ExecuteType;-}-```-------## Action Types--### Plan Actions--#### `ISSUE_CREATE` (Primary, Priority: 5)-**Label**: "Ready for review"--**Description**: Creates an issue from the plan and initiates the approval workflow.--**Visibility**:-- Plan has no issue attached (`plan.issue === ""`)-- Plan has no rollout attached (`plan.rollout === ""`)-- Plan is in ACTIVE state-- User has `bb.issues.create` permission--**Disabled When**:-- Any spec has an empty statement-- Plan checks are currently running-- Plan checks failed and SQL review is enforced (`project.enforceSqlReview`)-------#### `PLAN_CLOSE` (Secondary, Priority: 100)-**Label**: "Close"--**Description**: Closes (archives) the plan.--**Visibility**:-- Plan has no issue attached-- Plan has no rollout attached-- Plan is in ACTIVE state-- User is the plan creator OR has `bb.plans.update` permission-------#### `PLAN_REOPEN` (Primary, Priority: 10)-**Label**: "Reopen"--**Description**: Reopens a closed (archived) plan.--**Visibility**:-- Plan has no issue attached-- Plan has no rollout attached-- Plan is in DELETED state-- User is the plan creator OR has `bb.plans.update` permission-------### Issue Review Action--#### `ISSUE_REVIEW` (Primary, Priority: 30)-**Label**: "Review"--**Description**: Opens the unified review popover for approve/reject/comment.--**Visibility**:-- Issue exists and is OPEN-- Issue approval status is not APPROVED or SKIPPED-- User is a candidate for the current approval step (canApprove or canReject)-------### Issue Status Actions--#### `ISSUE_STATUS_CLOSE` (Secondary, Priority: 90)-**Label**: "Close"--**Description**: Closes the issue without resolving it (CANCELED).--**Visibility**:-- Issue exists and is OPEN-- No rollout exists (can't close after rollout starts)-- User has `bb.issues.update` permission-------#### `ISSUE_STATUS_REOPEN` (Primary, Priority: 20)-**Label**: "Reopen"--**Description**: Reopens a canceled issue.--**Visibility**:-- Issue exists and is CANCELED (not DONE - resolved issues cannot be reopened)-- User has `bb.issues.update` permission-------### Rollout Actions--#### `ROLLOUT_CREATE` (Primary/Secondary, Priority: 55)-**Label**: "Create Rollout"--**Description**: Creates a rollout from the issue. Shows as primary action when ready, moves to dropdown when conditions aren't met.--**Visibility**:-- Not a deferred rollout plan (export/create database plans use ROLLOUT_START instead)-- Not an issue-only plan-- Plan has no rollout attached-- Issue exists-- User has `bb.rollouts.create` permission-- If `requireIssueApproval=true` AND issue not APPROVED/SKIPPED → hidden-- If `requirePlanCheckNoError=true` AND plan checks failed → hidden--**Category Logic**:-- **Primary** (main button): When all conditions are met (no warnings)-- **Secondary** (dropdown): When warnings exist (require_*=false but conditions not met)--**Warning Panel** (shown when clicking from dropdown):-- `requireIssueApproval=false` AND approval not APPROVED/SKIPPED → shows approval flow section-- Plan checks are running → shows running message-- `requirePlanCheckNoError=false` AND plan checks failed → shows plan check status--When warnings exist, user must check "Bypass stage requirements" checkbox to proceed.-------#### `ROLLOUT_START` (Primary, Priority: 60)-**Label**:-- "Export" (for export data issues)-- "Rollout" (for other issues)--**Description**: Starts or retries tasks in the rollout. For deferred rollout plans (export/create database), this action creates the rollout and runs all tasks in one step.--**Visibility**:-For deferred rollout plans (export/create database):-- Issue exists and is APPROVED or SKIPPED-- No rollout yet (will create it) OR has startable tasks-- User has `bb.taskRuns.create` permission--For regular plans:-- Rollout exists-- Issue approval status is APPROVED or SKIPPED-- Has DATABASE_CREATE or DATABASE_EXPORT tasks-- At least one task is startable (NOT_STARTED, FAILED, or CANCELED)-- **Permission**: User has `bb.taskRuns.create` permission OR is creator (for exports)-------#### `ROLLOUT_CANCEL` (Secondary, Priority: 80)-**Label**: "Cancel"--**Description**: Cancels running or pending tasks.--**Visibility**:-- Rollout exists-- Issue approval status is APPROVED or SKIPPED-- At least one task is in PENDING or RUNNING status-- **Permission**: Same as ROLLOUT_START-------#### `EXPORT_DOWNLOAD` (Primary, Priority: 0)-**Label**: "Download"--**Description**: Downloads completed export archive.--**Visibility**:-- Plan is an export plan-- Export archive is ready-- User is the issue creator-------## Warning Behavior--### Rollout Creation Category and Warnings--The ROLLOUT_CREATE button visibility and category depend on project settings and current state:--| Condition | Result |-|-----------|--------|-| `requireIssueApproval=true` + not approved | **Hidden** |-| `requirePlanCheckNoError=true` + checks failed | **Hidden** |-| `requireIssueApproval=false` + not approved | Secondary (dropdown) with warning |-| `requirePlanCheckNoError=false` + checks failed | Secondary (dropdown) with warning |-| Plan checks running | Secondary (dropdown) with warning |-| All conditions met | Primary (main button) |--### Task Execution Warnings--Task execution (RUN/SKIP/CANCEL) always shows **warnings** for approval and plan check issues, never errors. Users can bypass these warnings to proceed.-------## Global Disabled States--All actions are disabled when:-- Editor is in editing mode (`editorState.isEditing === true`)-- **Tooltip**: "Save changes before continuing"-------## Action Priority Order--Actions are sorted by priority (lower number = higher priority). The first visible primary action is shown as the main button.--| Priority | Action | Category |-|----------|--------|----------|-| 0 | EXPORT_DOWNLOAD | primary |-| 5 | ISSUE_CREATE | primary |-| 10 | PLAN_REOPEN | primary |-| 20 | ISSUE_STATUS_REOPEN | primary |-| 30 | ISSUE_REVIEW | primary |-| 55 | ROLLOUT_CREATE | primary |-| 60 | ROLLOUT_START | primary |-| 80 | ROLLOUT_CANCEL | secondary |-| 90 | ISSUE_STATUS_CLOSE | secondary |-| 100 | PLAN_CLOSE | secondary |-------## Permission Summary--### Plan Permissions-- `bb.plans.update`: Close or reopen plans-- `bb.issues.create`: Create issues from plans--### Issue Permissions-- `bb.issues.update`: Close or reopen issues--### Rollout Permissions-- `bb.rollouts.create`: Create rollouts-- `bb.taskRuns.create`: Run rollout tasks-- **Issue creator**: Run export tasks (for DATABASE_EXPORT issues)--### Approval Permissions-- **Approval template roles**: Approve or reject based on current approval step-------## Usage--### Using the Action Registry--```typescript-import { useActionRegistry } from "./registry";--const {- context, // Reactive ActionContext- primaryAction, // First visible primary action- secondaryActions, // All visible secondary actions- isActionDisabled, // Check if action is disabled- getDisabledReason, // Get disabled tooltip- executeAction, // Execute action by ID-} = useActionRegistry();-```--### Adding a New Action--1. Define the action in the appropriate file (`registry/actions/*.ts`):-```typescript-export const MY_NEW_ACTION: ActionDefinition = {- id: "MY_NEW_ACTION",- label: () => t("my-action.label"),- buttonType: "primary",- category: "primary",- priority: 45,- isVisible: (ctx) => /* visibility logic */,- isDisabled: (ctx) => /* disabled logic */,- disabledReason: (ctx) => /* reason or undefined */,- executeType: "immediate",-};-```--2. Add to the actions array in the same file-3. Add the type to `registry/types.ts`-4. Handle execution in `Actions.vue` if needed-------## Implementation Files--- **registry/**: Action registry (source of truth for all actions and components)-- **Actions.vue**: Main orchestratordiff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/Actions.vue b/frontend/src/components/Plan/components/HeaderSection/Actions/Actions.vuedeleted file mode 100644index a657bd65bc..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/Actions.vue+++ /dev/null@@ -1,286 +0,0 @@-<template>- <CreateButton v-if="isCreating" />- <div v-else class="flex items-center gap-x-2">- <!-- Plan link for database change issues -->- <PlanLink v-if="shouldShowPlanLink" />-- <!-- Primary action: special components for specific actions -->- <CreateIssueButton- v-if="primaryAction?.id === 'ISSUE_CREATE'"- :disabled="isActionDisabled(primaryAction)"- :disabled-reason="getDisabledReason(primaryAction)"- />- <IssueReviewButton- v-else-if="primaryAction?.id === 'ISSUE_REVIEW'"- :can-approve="context.permissions.isApprovalCandidate"- :can-reject="context.permissions.isApprovalCandidate"- :disabled="isActionDisabled(primaryAction)"- :disabled-reason="getDisabledReason(primaryAction)"- />- <ExportArchiveDownloadAction- v-else-if="primaryAction?.id === 'EXPORT_DOWNLOAD'"- />- <ActionButton- v-else-if="primaryAction"- :action="primaryAction"- :context="context"- :disabled="isActionDisabled(primaryAction)"- :disabled-reason="getDisabledReason(primaryAction)"- @execute="handlePerformAction"- />-- <!-- Secondary actions dropdown -->- <ActionDropdown- v-if="secondaryActions.length > 0"- :actions="secondaryActions"- :context="context"- :global-disabled="globalDisabled"- :global-disabled-reason="globalDisabledReason"- :is-action-disabled="isActionDisabled"- :get-disabled-reason="getDisabledReason"- @execute="handlePerformAction"- />-- <!-- Rollout Action Panel (only when rollout exists) -->- <TaskRolloutActionPanel- v-if="pendingRolloutAction && rolloutStage"- :show="true"- :action="pendingRolloutAction === 'ROLLOUT_CANCEL' ? 'CANCEL' : 'RUN'"- :target="{ type: 'tasks', stage: rolloutStage }"- @close="pendingRolloutAction = undefined"- @confirm="handleRolloutActionConfirm"- />-- </div>-</template>--<script setup lang="ts">-import { clone, create } from "@bufbuild/protobuf";-import { useDialog } from "naive-ui";-import { computed, ref } from "vue";-import { useI18n } from "vue-i18n";-import { useRouter } from "vue-router";-import { usePlanContext, usePlanLink } from "@/components/Plan/logic";-import { useResourcePoller } from "@/components/Plan/logic/poller";-import TaskRolloutActionPanel from "@/components/RolloutV1/components/Task/TaskRolloutActionPanel.vue";-import {- issueServiceClientConnect,- rolloutServiceClientConnect,-} from "@/connect";-import { buildPlanDeployRouteFromRolloutName } from "@/router/dashboard/projectV1RouteHelpers";-import { pushNotification, useCurrentProjectV1 } from "@/store";-import { usePlanStore } from "@/store/modules/v1/plan";-import { State } from "@/types/proto-es/v1/common_pb";-import {- BatchUpdateIssuesStatusRequestSchema,- IssueStatus,-} from "@/types/proto-es/v1/issue_service_pb";-import { PlanSchema } from "@/types/proto-es/v1/plan_service_pb";-import {- BatchRunTasksRequestSchema,- CreateRolloutRequestSchema,-} from "@/types/proto-es/v1/rollout_service_pb";-import { CreateButton, CreateIssueButton } from "./create";-import { ExportArchiveDownloadAction } from "./export";-import PlanLink from "./PlanLink.vue";-import {- ActionButton,- ActionDropdown,- IssueReviewButton,- useActionRegistry,-} from "./registry";-import type {- IssueStatusAction,- RolloutAction,- UnifiedAction,-} from "./registry/types";--const { t } = useI18n();-const router = useRouter();-const dialog = useDialog();-const resourcePoller = useResourcePoller();-const { project } = useCurrentProjectV1();-const { isCreating, plan, issue, rollout, events } = usePlanContext();-const planStore = usePlanStore();-const creatingRollout = ref(false);-const { shouldShow: shouldShowPlanLink } = usePlanLink();--// Use the action registry-const {- context,- primaryAction,- secondaryActions,- isActionDisabled,- getDisabledReason,-} = useActionRegistry();--// Global disabled state (for dropdown)-const globalDisabled = computed(() => {- if (!primaryAction.value) return false;- return isActionDisabled(primaryAction.value);-});--const globalDisabledReason = computed(() => {- if (!primaryAction.value) return undefined;- return getDisabledReason(primaryAction.value);-});--// Panel visibility state-const pendingRolloutAction = ref<RolloutAction | undefined>(undefined);-// Get the first stage for database creation/export rollouts-// (the panel handles all stages internally for these task types)-const rolloutStage = computed(() => rollout.value?.stages[0]);--const handlePerformAction = async (action: UnifiedAction) => {- switch (action) {- case "ISSUE_STATUS_CLOSE":- case "ISSUE_STATUS_REOPEN":- await handleIssueStatusChange(action as IssueStatusAction);- break;- case "PLAN_CLOSE":- await handlePlanStateChange("PLAN_CLOSE");- break;- case "PLAN_REOPEN":- await handlePlanStateChange("PLAN_REOPEN");- break;- case "ROLLOUT_START":- // For deferred rollout plans without rollout, create and run all tasks- if (context.value.hasDeferredRollout && !rollout.value) {- await handleCreateRollout({ runAllTasks: true });- return;- }- pendingRolloutAction.value = action as RolloutAction;- break;- case "ROLLOUT_CANCEL":- pendingRolloutAction.value = action as RolloutAction;- break;- }-};--const handleIssueStatusChange = async (action: IssueStatusAction) => {- const issueValue = issue?.value;- if (!issueValue) return;-- const actionConfig = {- ISSUE_STATUS_CLOSE: {- title: t("common.close"),- content: t("issue.status-transition.modal.close"),- status: IssueStatus.CANCELED,- },- ISSUE_STATUS_REOPEN: {- title: t("common.reopen"),- content: t("issue.status-transition.modal.reopen"),- status: IssueStatus.OPEN,- },- }[action];-- const d = dialog.warning({- title: actionConfig.title,- content: actionConfig.content,- positiveText: actionConfig.title,- negativeText: t("common.cancel"),- onPositiveClick: async () => {- d.loading = true;- try {- const request = create(BatchUpdateIssuesStatusRequestSchema, {- parent: project.value.name,- issues: [issueValue.name],- status: actionConfig.status,- });- await issueServiceClientConnect.batchUpdateIssuesStatus(request);- events.emit("perform-issue-status-action", { action });- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.failed"),- description: String(error),- });- }- },- });-};--const handlePlanStateChange = async (action: "PLAN_CLOSE" | "PLAN_REOPEN") => {- if (!plan?.value) return;-- const isClosing = action === "PLAN_CLOSE";- const title = isClosing ? t("common.close") : t("common.reopen");- const content = isClosing- ? t("plan.state.close-confirm")- : t("plan.state.reopen-confirm");- const newState = isClosing ? State.DELETED : State.ACTIVE;-- const d = dialog.warning({- title,- content,- positiveText: title,- negativeText: t("common.cancel"),- onPositiveClick: async () => {- d.loading = true;- try {- const planPatch = clone(PlanSchema, plan.value);- planPatch.state = newState;- await planStore.updatePlan(planPatch, ["state"]);- await resourcePoller.refreshResources();- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.failed"),- description: String(error),- });- }- },- });-};--// Create rollout and optionally run all tasks (for export plans)-const handleCreateRollout = async (options?: { runAllTasks?: boolean }) => {- if (creatingRollout.value) return;-- creatingRollout.value = true;- try {- const request = create(CreateRolloutRequestSchema, {- parent: plan.value.name,- });- const createdRollout =- await rolloutServiceClientConnect.createRollout(request);-- if (options?.runAllTasks) {- // Run all tasks in each stage (for export/create plans)- for (const stage of createdRollout.stages) {- const runRequest = create(BatchRunTasksRequestSchema, {- parent: stage.name,- tasks: stage.tasks.map((task) => task.name),- });- await rolloutServiceClientConnect.batchRunTasks(runRequest);- }- await resourcePoller.refreshResources();- events.emit("status-changed", { eager: true });- } else {- // Navigate to rollout page- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.created"),- });- router.push(buildPlanDeployRouteFromRolloutName(createdRollout.name));- }- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.failed"),- description: String(error),- });- } finally {- creatingRollout.value = false;- }-};--const handleRolloutActionConfirm = () => {- events.emit("status-changed", { eager: true });- pendingRolloutAction.value = undefined;-};-</script>diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/PlanLink.vue b/frontend/src/components/Plan/components/HeaderSection/Actions/PlanLink.vuedeleted file mode 100644index 4f7472cc6d..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/PlanLink.vue+++ /dev/null@@ -1,39 +0,0 @@-<template>- <RouterLink :to="planRoute">- <NButton icon-placement="right" secondary strong>- <span class="mr-1">#{{ planID }}</span>- <span>{{ $t("common.plan") }}</span>- <template #icon>- <ArrowUpRightIcon class="opacity-60" />- </template>- </NButton>- </RouterLink>-</template>--<script lang="ts" setup>-import { ArrowUpRightIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { computed } from "vue";-import { usePlanContext } from "@/components/Plan/logic";-import { PROJECT_V1_ROUTE_PLAN_DETAIL } from "@/router/dashboard/projectV1";-import { buildPlanDeployRouteFromPlanName } from "@/router/dashboard/projectV1RouteHelpers";-import { extractPlanUID, extractProjectResourceName } from "@/utils";--const { plan } = usePlanContext();--const planID = computed(() => extractPlanUID(plan.value.name));--const planRoute = computed(() => {- if (plan.value.hasRollout) {- return buildPlanDeployRouteFromPlanName(plan.value.name);- }-- return {- name: PROJECT_V1_ROUTE_PLAN_DETAIL,- params: {- projectId: extractProjectResourceName(plan.value.name),- planId: planID.value,- },- };-});-</script>diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/create/CreateButton.vue b/frontend/src/components/Plan/components/HeaderSection/Actions/create/CreateButton.vuedeleted file mode 100644index 3b9fbca18f..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/create/CreateButton.vue+++ /dev/null@@ -1,291 +0,0 @@-<template>- <NPopover- trigger="manual"- placement="bottom"- :show="showPopover"- @update:show="showPopover = $event"- >- <template #trigger>- <NTooltip :disabled="planCreateErrorList.length === 0" placement="top">- <template #trigger>- <NButton- type="primary"- size="medium"- tag="div"- :disabled="planCreateErrorList.length > 0 || loading"- :loading="loading"- @click="handleButtonClick"- >- {{ loading ? $t("common.creating") : $t("common.create") }}- </NButton>- </template>- <template #default>- <ErrorList :errors="planCreateErrorList" />- </template>- </NTooltip>- </template>-- <template #default>- <div class="w-72 flex flex-col gap-y-3 p-1">- <div class="flex flex-col gap-y-1">- <div class="font-medium text-control flex items-center gap-x-1">- {{ $t("issue.labels") }}- <RequiredStar v-if="project.forceIssueLabels" />- </div>- <IssueLabelSelector- :disabled="loading"- :selected="selectedLabels"- :project="project"- :size="'medium'"- :render-menu-inside-parent="true"- @update:selected="selectedLabels = $event"- />- </div>- <div class="flex justify-end gap-x-2">- <NButton size="small" quaternary @click="handleCancel">- {{ $t("common.cancel") }}- </NButton>- <NTooltip :disabled="confirmErrors.length === 0" placement="top">- <template #trigger>- <NButton- type="primary"- size="small"- :disabled="confirmErrors.length > 0 || loading"- :loading="loading"- @click="doCreatePlan"- >- {{ $t("common.confirm") }}- </NButton>- </template>- <template #default>- <ErrorList :errors="confirmErrors" />- </template>- </NTooltip>- </div>- </div>- </template>- </NPopover>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { NButton, NPopover, NTooltip } from "naive-ui";-import { computed, nextTick, ref } from "vue";-import { useI18n } from "vue-i18n";-import { useRouter } from "vue-router";-import IssueLabelSelector from "@/components/IssueV1/components/IssueLabelSelector.vue";-import {- ErrorList,- useSpecsValidation,-} from "@/components/Plan/components/common";-import { getLocalSheetByName, usePlanContext } from "@/components/Plan/logic";-import RequiredStar from "@/components/RequiredStar.vue";-import { planServiceClientConnect } from "@/connect";-import {- PROJECT_V1_ROUTE_ISSUE_DETAIL,- PROJECT_V1_ROUTE_PLAN_DETAIL,-} from "@/router/dashboard/projectV1";-import {- experimentalCreateIssueByPlan,- pushNotification,- useCurrentProjectV1,- useCurrentUserV1,- useSheetV1Store,-} from "@/store";-import { Issue_Type, IssueSchema } from "@/types/proto-es/v1/issue_service_pb";-import {- CreatePlanRequestSchema,- type Plan_ChangeDatabaseConfig,- type Plan_ExportDataConfig,-} from "@/types/proto-es/v1/plan_service_pb";-import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";-import {- extractIssueUID,- extractPlanUID,- extractProjectResourceName,- extractSheetUID,- hasProjectPermissionV2,- normalizeTitle,-} from "@/utils";--const { t } = useI18n();-const router = useRouter();-const { project } = useCurrentProjectV1();-const { plan } = usePlanContext();-const sheetStore = useSheetV1Store();-const currentUser = useCurrentUserV1();-const loading = ref(false);-const showPopover = ref(false);-const selectedLabels = ref<string[]>([]);--const resetDraft = () => {- selectedLabels.value = [];-};--const handleCancel = () => {- resetDraft();- showPopover.value = false;-};--// Use the validation hook for all specs-const { isSpecEmpty } = useSpecsValidation(computed(() => plan.value.specs));--const isDataExportPlan = computed(() => {- return (- plan.value.specs.length > 0 &&- plan.value.specs.every((spec) => spec.config?.case === "exportDataConfig")- );-});--const planCreateErrorList = computed(() => {- const errorList: string[] = [];- if (!hasProjectPermissionV2(project.value, "bb.plans.create")) {- errorList.push(t("common.missing-required-permission"));- }- if (!normalizeTitle(plan.value.title)) {- errorList.push("Missing plan title");- }- if (plan.value.specs.some((spec) => isSpecEmpty(spec))) {- errorList.push("Missing statement");- }- return errorList;-});--// Errors that disable the confirm button in popover (for data export plans)-const confirmErrors = computed(() => {- const list: string[] = [];-- if (project.value.forceIssueLabels && selectedLabels.value.length === 0) {- list.push(t("plan.labels-required-for-review"));- }-- return list;-});--const handleButtonClick = () => {- if (isDataExportPlan.value) {- showPopover.value = true;- } else {- doCreatePlan();- }-};--const doCreatePlan = async () => {- // Prevent race condition: check if already creating- if (loading.value) {- return;- }-- // For data export plans, check confirmErrors before proceeding- if (isDataExportPlan.value && confirmErrors.value.length > 0) {- return;- }-- loading.value = true;- showPopover.value = false;-- try {- // For data export plans, create plan + issue and redirect to issue- if (isDataExportPlan.value) {- await doCreateDataExportIssue();- } else {- // For regular plans, just create the plan- await createSheets();- const request = create(CreatePlanRequestSchema, {- parent: project.value.name,- plan: plan.value,- });- const createdPlan = await planServiceClientConnect.createPlan(request);- if (!createdPlan) {- loading.value = false;- return;- }-- nextTick(() => {- router.replace({- name: PROJECT_V1_ROUTE_PLAN_DETAIL,- params: {- projectId: extractProjectResourceName(createdPlan.name),- planId: extractPlanUID(createdPlan.name),- },- });- });- }- } catch (error) {- console.error("Failed to create plan:", error);- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: "Failed to create",- description: String(error),- });- loading.value = false;- }-};--// Create data export issue (plan + issue, rollout is created later via EXPORT action)-const doCreateDataExportIssue = async () => {- // Create sheets first- await createSheets();-- const issueCreate = create(IssueSchema, {- title: plan.value.title,- description: plan.value.description,- creator: `users/${currentUser.value.email}`,- labels: selectedLabels.value,- type: Issue_Type.DATABASE_EXPORT,- });- const { createdIssue } = await experimentalCreateIssueByPlan(- project.value,- issueCreate,- plan.value,- { skipRollout: true }- );-- resetDraft();-- // Redirect to issue detail page- nextTick(() => {- router.replace({- name: PROJECT_V1_ROUTE_ISSUE_DETAIL,- params: {- projectId: extractProjectResourceName(createdIssue.name),- issueId: extractIssueUID(createdIssue.name),- },- });- });-};--// Create sheets for spec configs and update their resource names.-const createSheets = async () => {- const specs = plan.value.specs || [];- const configWithSheetList: (- | Plan_ChangeDatabaseConfig- | Plan_ExportDataConfig- )[] = [];- const pendingCreateSheetMap = new Map<string, Sheet>();-- for (const spec of specs) {- let config = null;- if (spec.config?.case === "changeDatabaseConfig") {- config = spec.config.value;- } else if (spec.config?.case === "exportDataConfig") {- config = spec.config.value;- }-- if (!config) continue;- configWithSheetList.push(config);- if (pendingCreateSheetMap.has(config.sheet)) continue;- const uid = extractSheetUID(config.sheet);- if (uid.startsWith("-")) {- // The sheet is pending create.- const sheetToCreate = getLocalSheetByName(config.sheet);- const createdSheet = await sheetStore.createSheet(- project.value.name,- sheetToCreate- );- config.sheet = createdSheet.name;- }- }-};-</script>diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/create/CreateIssueButton.vue b/frontend/src/components/Plan/components/HeaderSection/Actions/create/CreateIssueButton.vuedeleted file mode 100644index 9031025705..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/create/CreateIssueButton.vue+++ /dev/null@@ -1,297 +0,0 @@-<template>- <NPopover- trigger="click"- placement="bottom-end"- :show="showPopover"- @update:show="showPopover = $event"- >- <template #trigger>- <NTooltip :disabled="errors.length === 0" placement="top">- <template #trigger>- <NButton- type="primary"- size="medium"- tag="div"- :disabled="disabled || errors.length > 0 || loading"- :loading="loading"- >- {{ $t("plan.ready-for-review") }}- </NButton>- </template>- <template #default>- <ErrorList :errors="errors" />- </template>- </NTooltip>- </template>-- <template #default>- <div class="w-80 flex flex-col gap-y-3 p-1">- <NAlert v-if="showChecksWarning" type="warning">- {{ $t("issue.checks-warning-hint") }}- </NAlert>- <div class="flex flex-col gap-y-1">- <div class="font-medium text-control flex items-center gap-x-1">- {{ $t("issue.labels") }}- <RequiredStar v-if="project.forceIssueLabels" />- </div>- <IssueLabelSelector- :disabled="loading"- :selected="selectedLabels"- :project="project"- :size="'medium'"- :render-menu-inside-parent="true"- @update:selected="selectedLabels = $event"- />- </div>- <div class="flex items-center gap-x-2">- <NCheckbox- v-if="showChecksWarning"- v-model:checked="checksWarningAcknowledged"- size="small"- >- {{- $t("issue.action-anyway", {- action: $t("common.confirm"),- })- }}- </NCheckbox>- <div class="grow" />- <NButton size="small" quaternary @click="handleCancel">- {{ $t("common.cancel") }}- </NButton>- <NTooltip :disabled="confirmErrors.length === 0" placement="top">- <template #trigger>- <NButton- type="primary"- size="small"- :disabled="confirmErrors.length > 0 || loading"- :loading="loading"- @click="doCreateIssue"- >- {{ $t("common.confirm") }}- </NButton>- </template>- <template #default>- <ErrorList :errors="confirmErrors" />- </template>- </NTooltip>- </div>- </div>- </template>- </NPopover>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { NAlert, NButton, NCheckbox, NPopover, NTooltip } from "naive-ui";-import { computed, nextTick, ref } from "vue";-import { useI18n } from "vue-i18n";-import { useRouter } from "vue-router";-import IssueLabelSelector from "@/components/IssueV1/components/IssueLabelSelector.vue";-import {- ErrorList,- useSpecsValidation,-} from "@/components/Plan/components/common";-import { usePlanCheckStatus, usePlanContext } from "@/components/Plan/logic";-import RequiredStar from "@/components/RequiredStar.vue";-import { issueServiceClientConnect } from "@/connect";-import {- PROJECT_V1_ROUTE_ISSUE_DETAIL,- PROJECT_V1_ROUTE_PLAN_DETAIL,-} from "@/router/dashboard/projectV1";-import {- pushNotification,- useCurrentProjectV1,- useCurrentUserV1,-} from "@/store";-import {- CreateIssueRequestSchema,- Issue_Type,- IssueSchema,- IssueStatus,-} from "@/types/proto-es/v1/issue_service_pb";-import type { Plan, Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";-import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";-import { extractIssueUID, extractProjectResourceName } from "@/utils";--const props = defineProps<{- disabled: boolean;- disabledReason?: string;-}>();--const { t } = useI18n();-const router = useRouter();-const { project } = useCurrentProjectV1();-const { plan, events } = usePlanContext();-const currentUser = useCurrentUserV1();--const loading = ref(false);-const showPopover = ref(false);-const selectedLabels = ref<string[]>([]);--// Use the validation hook for all specs-const { isSpecEmpty } = useSpecsValidation(computed(() => plan.value.specs));--// Use plan check status for issue creation validation-const {- getOverallStatus: planCheckSummaryStatus,- hasRunning: hasRunningPlanChecks,-} = usePlanCheckStatus(plan);--const checksWarningAcknowledged = ref(false);--const resetDraft = () => {- selectedLabels.value = [];- checksWarningAcknowledged.value = false;-};--const handleCancel = () => {- resetDraft();- showPopover.value = false;-};--// Errors that disable the main button-const errors = computed(() => {- const list: string[] = [];-- if (props.disabledReason) {- list.push(props.disabledReason);- }-- // Check if all specs have valid statements- if (plan.value.specs.some((spec) => isSpecEmpty(spec))) {- list.push(t("plan.navigator.statement-empty"));- }-- // Check if plan checks are running- if (hasRunningPlanChecks.value) {- list.push(- t(- "custom-approval.issue-review.disallow-approve-reason.some-task-checks-are-still-running"- )- );- }-- // Check if plan checks failed and policy restricts- const planChecksFailed = planCheckSummaryStatus.value === Advice_Level.ERROR;- if (planChecksFailed && project.value.enforceSqlReview) {- list.push(- t(- "custom-approval.issue-review.disallow-approve-reason.some-task-checks-didnt-pass"- )- );- }-- return list;-});--// Show warning when checks have errors for database change plans.-// Backend always skips auto-rollout creation when checks have errors.-// Only relevant for change-database plans (auto-rollout doesn't apply to exports).-// When enforceSqlReview is on, the button is already disabled so this won't be visible.-const showChecksWarning = computed(() => {- return (- planCheckSummaryStatus.value === Advice_Level.ERROR &&- plan.value.specs.length > 0 &&- plan.value.specs.every(- (spec) => spec.config?.case === "changeDatabaseConfig"- )- );-});--// Errors that disable the confirm button in popover-const confirmErrors = computed(() => {- const list: string[] = [];-- if (project.value.forceIssueLabels && selectedLabels.value.length === 0) {- list.push(t("plan.labels-required-for-review"));- }-- if (showChecksWarning.value && !checksWarningAcknowledged.value) {- list.push(t("issue.checks-warning-hint"));- }-- return list;-});--// Helper function to determine issue type from plan specs-const getIssueTypeFromPlan = (planValue: Plan): Issue_Type => {- const hasExportDataSpec = planValue.specs.some(- (spec: Plan_Spec) => spec.config?.case === "exportDataConfig"- );-- if (hasExportDataSpec) {- return Issue_Type.DATABASE_EXPORT;- }-- return Issue_Type.DATABASE_CHANGE;-};--const shouldStayOnPlanDetailPage = (planValue: Plan) => {- if (planValue.specs.length === 0) {- return true;- }-- return !planValue.specs.every((spec: Plan_Spec) => {- return (- spec.config?.case === "createDatabaseConfig" ||- spec.config?.case === "exportDataConfig"- );- });-};--const doCreateIssue = async () => {- if (loading.value) return;- if (confirmErrors.value.length > 0) return;-- loading.value = true;-- try {- const createIssueRequest = create(CreateIssueRequestSchema, {- parent: project.value.name,- issue: create(IssueSchema, {- creator: `users/${currentUser.value.email}`,- labels: selectedLabels.value,- plan: plan.value.name,- status: IssueStatus.OPEN,- type: getIssueTypeFromPlan(plan.value),- }),- });-- const createdIssue =- await issueServiceClientConnect.createIssue(createIssueRequest);-- events.emit("status-changed", { eager: true });-- resetDraft();- showPopover.value = false;-- // Only plan-scoped flows should remain on the dedicated Plan Detail page.- // Issue-scoped flows must continue on the issue page.- const currentRoute = router.currentRoute.value;- const isPlanDetailPage =- typeof currentRoute.name === "string" &&- currentRoute.name.startsWith(PROJECT_V1_ROUTE_PLAN_DETAIL);- if (!(isPlanDetailPage && shouldStayOnPlanDetailPage(plan.value))) {- nextTick(() => {- router.push({- name: PROJECT_V1_ROUTE_ISSUE_DETAIL,- params: {- projectId: extractProjectResourceName(plan.value.name),- issueId: extractIssueUID(createdIssue.name),- },- });- });- }- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.failed"),- description: String(error),- });- } finally {- loading.value = false;- }-};-</script>diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/create/RolloutCreatePanel.vue b/frontend/src/components/Plan/components/HeaderSection/Actions/create/RolloutCreatePanel.vuedeleted file mode 100644index c38edd4f5d..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/create/RolloutCreatePanel.vue+++ /dev/null@@ -1,195 +0,0 @@-<template>- <CommonDrawer- :show="show"- :title="$t('issue.create-rollout')"- :loading="loading"- @show="bypassWarnings = false"- @close="$emit('close')"- >- <template #default>- <div class="flex flex-col gap-y-4 h-full px-1">- <!-- Error alert (blocking) -->- <NAlert v-if="errorMessages.length > 0" type="error" :title="$t('common.error')">- <ul class="list-disc list-inside text-sm">- <li v-for="msg in errorMessages" :key="msg">{{ msg }}</li>- </ul>- </NAlert>-- <!-- Warning alert (bypassable) -->- <NAlert- v-else-if="warningMessages.length > 0"- type="warning"- :title="$t('common.notices')"- >- <ul class="list-disc list-inside text-sm">- <li v-for="msg in warningMessages" :key="msg">{{ msg }}</li>- </ul>- </NAlert>-- <ApprovalFlowSection v-if="issue" :issue="issue" />-- <div class="w-full flex flex-col gap-2">- <span class="font-medium text-control">{{- $t("plan.navigator.checks")- }}</span>- <PlanCheckStatusCount :plan="plan" />- <span v-if="!hasAnyChecks" class="text-sm text-control-placeholder">- {{ $t("plan.overview.no-checks") }}- </span>- </div>- </div>- </template>- <template #footer>- <div class="w-full flex justify-between items-center gap-x-2">- <NCheckbox- v-if="warningMessages.length > 0 && errorMessages.length === 0"- v-model:checked="bypassWarnings"- :disabled="loading"- >- {{ $t("rollout.bypass-stage-requirements") }}- </NCheckbox>- <div v-else />-- <div class="flex gap-x-2">- <NButton quaternary @click="$emit('close')">- {{ $t("common.cancel") }}- </NButton>- <NButton- type="primary"- :disabled="errorMessages.length > 0 || (warningMessages.length > 0 && !bypassWarnings)"- :loading="loading"- @click="handleConfirm"- >- {{ $t("common.confirm") }}- </NButton>- </div>- </div>- </template>- </CommonDrawer>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { NAlert, NButton, NCheckbox } from "naive-ui";-import { computed, ref } from "vue";-import { useI18n } from "vue-i18n";-import { useRouter } from "vue-router";-import { ApprovalFlowSection } from "@/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection";-import PlanCheckStatusCount from "@/components/Plan/components/PlanCheckStatusCount.vue";-import { usePlanCheckStatus, usePlanContext } from "@/components/Plan/logic";-import CommonDrawer from "@/components/RolloutV1/components/Rollout/CommonDrawer.vue";-import { rolloutServiceClientConnect } from "@/connect";-import { buildPlanDeployRouteFromRolloutName } from "@/router/dashboard/projectV1RouteHelpers";-import { pushNotification } from "@/store";-import { CreateRolloutRequestSchema } from "@/types/proto-es/v1/rollout_service_pb";-import type { ActionContext } from "../registry/types";--const props = defineProps<{- show: boolean;- context: ActionContext;-}>();--const emit = defineEmits<{- (event: "close"): void;- (event: "confirm"): void;-}>();--const { t } = useI18n();-const router = useRouter();-const { events } = usePlanContext();--const plan = computed(() => props.context.plan);-const issue = computed(() => props.context.issue);-const project = computed(() => props.context.project);-const { hasAnyStatus: hasAnyChecks } = usePlanCheckStatus(plan);--const loading = ref(false);-const bypassWarnings = ref(false);--// Errors: require_*=true and condition not met (blocking)-const errorMessages = computed(() => {- const msgs: string[] = [];- if (!props.context.permissions.createRollout) {- msgs.push(- t("common.missing-required-permission", {- permissions: "bb.rollouts.create",- })- );- }- if (project.value.requireIssueApproval && !props.context.issueApproved) {- msgs.push(- t("project.settings.issue-related.require-issue-approval.description")- );- }- if (- project.value.requirePlanCheckNoError &&- props.context.validation.planChecksFailed- ) {- msgs.push(- t(- "project.settings.issue-related.require-plan-check-no-error.description"- )- );- }- return msgs;-});--// Warnings: require_*=false and condition not met (bypassable)-const warningMessages = computed(() => {- const msgs: string[] = [];- if (!project.value.requireIssueApproval && !props.context.issueApproved) {- msgs.push(- t("project.settings.issue-related.require-issue-approval.description")- );- }- if (props.context.validation.planChecksRunning) {- msgs.push(- t(- "custom-approval.issue-review.disallow-approve-reason.some-task-checks-are-still-running"- )- );- } else if (- !project.value.requirePlanCheckNoError &&- props.context.validation.planChecksFailed- ) {- msgs.push(- t(- "project.settings.issue-related.require-plan-check-no-error.description"- )- );- }- return msgs;-});--const handleConfirm = async () => {- if (loading.value) return;- loading.value = true;-- try {- const createdRollout = await rolloutServiceClientConnect.createRollout(- create(CreateRolloutRequestSchema, { parent: plan.value.name })- );-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.created"),- });-- events.emit("status-changed", { eager: true });- emit("confirm");-- router.push(buildPlanDeployRouteFromRolloutName(createdRollout.name));- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.failed"),- description: String(error),- });- } finally {- loading.value = false;- emit("close");- }-};-</script>diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/create/index.ts b/frontend/src/components/Plan/components/HeaderSection/Actions/create/index.tsdeleted file mode 100644index c67422f25f..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/create/index.ts+++ /dev/null@@ -1,5 +0,0 @@-import CreateButton from "./CreateButton.vue";-import CreateIssueButton from "./CreateIssueButton.vue";-import RolloutCreatePanel from "./RolloutCreatePanel.vue";--export { CreateButton, CreateIssueButton, RolloutCreatePanel };diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/export/ExportArchiveDownloadAction.vue b/frontend/src/components/Plan/components/HeaderSection/Actions/export/ExportArchiveDownloadAction.vuedeleted file mode 100644index 7a41ec3959..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/export/ExportArchiveDownloadAction.vue+++ /dev/null@@ -1,106 +0,0 @@-<template>- <NTooltip>- <template #trigger>- <NButton- type="primary"- :loading="state.isExporting"- @click="downloadExportArchive"- v-if="!isExported"- >- <template #icon>- <DownloadIcon class="w-5 h-5" />- </template>- {{ $t("common.download") }}- </NButton>- <div- v-else- class="flex flex-row items-center gap-2 text-sm textlabel leading-8!"- >- <CalendarXIcon class="w-5 h-auto" />- {{ $t("issue.data-export.file-expired") }}- </div>- </template>- <span class="text-sm">- {{ $t("issue.data-export.download-tooltip") }}- </span>- </NTooltip>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import dayjs from "dayjs";-import { first, orderBy } from "lodash-es";-import { CalendarXIcon, DownloadIcon } from "lucide-vue-next";-import { NButton, NTooltip } from "naive-ui";-import { computed, reactive } from "vue";-import { usePlanContext } from "@/components/Plan/logic";-import { useSQLStore } from "@/store";-import {- type TaskRun,- TaskRun_ExportArchiveStatus,-} from "@/types/proto-es/v1/rollout_service_pb";-import { ExportRequestSchema } from "@/types/proto-es/v1/sql_service_pb";-import { extractTaskRunUID, extractTaskUID } from "@/utils";--interface LocalState {- isExporting: boolean;-}--const { rollout, taskRuns, events } = usePlanContext();-const state = reactive<LocalState>({- isExporting: false,-});--const isExported = computed(() => {- const exportTaskRuns = rollout.value?.stages- .flatMap((stage) => stage.tasks)- .map((task) => {- const taskRunsForTask = taskRuns.value.filter(- (taskRun) => extractTaskUID(taskRun.name) === extractTaskUID(task.name)- );- return first(- orderBy(- taskRunsForTask,- (taskRun) => Number(extractTaskRunUID(taskRun.name)),- "desc"- )- );- })- .filter(Boolean) as TaskRun[];- return exportTaskRuns.every(- (taskRun) =>- taskRun.exportArchiveStatus === TaskRun_ExportArchiveStatus.EXPORTED- );-});--const downloadExportArchive = async () => {- if (!rollout.value) return;-- state.isExporting = true;- try {- const content = await useSQLStore().exportData(- create(ExportRequestSchema, {- name: `${rollout.value.name}/stages/-`,- })- );- const buffer = content.buffer.slice(- content.byteOffset,- content.byteOffset + content.byteLength- ) as ArrayBuffer;- const blob = new Blob([buffer], {- type: "application/zip", // the download file is always zip file.- });- const url = window.URL.createObjectURL(blob);-- const formattedDateString = dayjs(new Date()).format("YYYY-MM-DDTHH-mm-ss");- const filename = `export-data-${formattedDateString}.zip`;- const link = document.createElement("a");- link.download = filename;- link.href = url;- link.click();- events.emit("status-changed", { eager: true });- } finally {- state.isExporting = false;- }-};-</script>diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/export/index.ts b/frontend/src/components/Plan/components/HeaderSection/Actions/export/index.tsdeleted file mode 100644index 6baab9ee63..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/export/index.ts+++ /dev/null@@ -1 +0,0 @@-export { default as ExportArchiveDownloadAction } from "./ExportArchiveDownloadAction.vue";diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/index.ts b/frontend/src/components/Plan/components/HeaderSection/Actions/index.tsdeleted file mode 100644index 9793717924..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import Actions from "./Actions.vue";--export default Actions;diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/actions/index.ts b/frontend/src/components/Plan/components/HeaderSection/Actions/registry/actions/index.tsdeleted file mode 100644index a210f4e8ca..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/actions/index.ts+++ /dev/null@@ -1,16 +0,0 @@-import type { ActionDefinition } from "../types";-import { issueActions } from "./issue";-import { planActions } from "./plan";-import { rolloutActions } from "./rollout";--// All actions in priority order for filtering-export const allActions: ActionDefinition[] = [- ...planActions,- ...issueActions,- ...rolloutActions,-].sort((a, b) => a.priority - b.priority);--// Re-export individual actions for testing-export * from "./plan";-export * from "./issue";-export * from "./rollout";diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/actions/issue.ts b/frontend/src/components/Plan/components/HeaderSection/Actions/registry/actions/issue.tsdeleted file mode 100644index ea58106a55..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/actions/issue.ts+++ /dev/null@@ -1,124 +0,0 @@-import { t } from "@/plugins/i18n";-import { State } from "@/types/proto-es/v1/common_pb";-import {- Issue_ApprovalStatus,- IssueStatus,-} from "@/types/proto-es/v1/issue_service_pb";-import type { ActionDefinition } from "../types";--export const ISSUE_CREATE: ActionDefinition = {- id: "ISSUE_CREATE",- label: () => t("plan.ready-for-review"),- buttonType: "primary",- category: "primary",- priority: 5,-- isVisible: (ctx) =>- !ctx.isIssueOnly &&- !ctx.isReleasePlan &&- ctx.plan.issue === "" &&- !ctx.plan.hasRollout &&- ctx.planState === State.ACTIVE,-- isDisabled: (ctx) =>- !ctx.permissions.createIssue ||- ctx.validation.hasEmptySpec ||- ctx.validation.planChecksRunning ||- (ctx.validation.planChecksFailed && ctx.project.enforceSqlReview),-- disabledReason: (ctx) => {- if (!ctx.permissions.createIssue) {- return t("common.missing-required-permission", {- permissions: "bb.issues.create",- });- }- if (ctx.validation.hasEmptySpec) {- return t("plan.navigator.statement-empty");- }- if (ctx.validation.planChecksRunning) {- return t(- "custom-approval.issue-review.disallow-approve-reason.some-task-checks-are-still-running"- );- }- if (ctx.validation.planChecksFailed && ctx.project.enforceSqlReview) {- return t(- "custom-approval.issue-review.disallow-approve-reason.some-task-checks-didnt-pass"- );- }- return undefined;- },-- executeType: "popover:labels",-};--export const ISSUE_REVIEW: ActionDefinition = {- id: "ISSUE_REVIEW",- label: () => t("issue.review.self"),- buttonType: "primary",- category: "primary",- priority: 30,-- isVisible: (ctx) =>- ctx.issueStatus === IssueStatus.OPEN &&- ctx.approvalStatus !== Issue_ApprovalStatus.APPROVED &&- ctx.approvalStatus !== Issue_ApprovalStatus.SKIPPED &&- ctx.permissions.isApprovalCandidate,-- isDisabled: () => false,- disabledReason: () => undefined,-- executeType: "popover:review",-};--export const ISSUE_STATUS_CLOSE: ActionDefinition = {- id: "ISSUE_STATUS_CLOSE",- label: () => t("issue.batch-transition.close"),- buttonType: "default",- category: "secondary",- priority: 90,-- isVisible: (ctx) =>- ctx.issueStatus === IssueStatus.OPEN && !ctx.plan.hasRollout,-- isDisabled: (ctx) => !ctx.permissions.updateIssue,- disabledReason: (ctx) => {- if (!ctx.permissions.updateIssue) {- return t("common.missing-required-permission", {- permissions: "bb.issues.update",- });- }- return undefined;- },-- executeType: "panel:issue-status",-};--export const ISSUE_STATUS_REOPEN: ActionDefinition = {- id: "ISSUE_STATUS_REOPEN",- label: () => t("issue.batch-transition.reopen"),- buttonType: "default",- category: "primary",- priority: 20,-- // Only show reopen for canceled issues, not for done/resolved issues- isVisible: (ctx) => ctx.issueStatus === IssueStatus.CANCELED,-- isDisabled: (ctx) => !ctx.permissions.updateIssue,- disabledReason: (ctx) => {- if (!ctx.permissions.updateIssue) {- return t("common.missing-required-permission", {- permissions: "bb.issues.update",- });- }- return undefined;- },-- executeType: "panel:issue-status",-};--export const issueActions: ActionDefinition[] = [- ISSUE_CREATE,- ISSUE_REVIEW,- ISSUE_STATUS_CLOSE,- ISSUE_STATUS_REOPEN,-];diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/actions/plan.ts b/frontend/src/components/Plan/components/HeaderSection/Actions/registry/actions/plan.tsdeleted file mode 100644index 4ecb061727..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/actions/plan.ts+++ /dev/null@@ -1,67 +0,0 @@-import { t } from "@/plugins/i18n";-import { State } from "@/types/proto-es/v1/common_pb";-import type { ActionDefinition } from "../types";--export const PLAN_CLOSE: ActionDefinition = {- id: "PLAN_CLOSE",- label: () => t("common.close"),- buttonType: "default",- category: "secondary",- priority: 100,-- isVisible: (ctx) =>- !ctx.isIssueOnly &&- ctx.plan.issue === "" &&- !ctx.plan.hasRollout &&- ctx.planState === State.ACTIVE,-- isDisabled: (ctx) => !ctx.permissions.updatePlan,- disabledReason: (ctx) => {- if (!ctx.permissions.updatePlan) {- if (!ctx.isCreator) {- return t("common.missing-required-permission", {- permissions: "bb.plans.update",- });- }- return t("common.only-creator-allowed-action");- }- return undefined;- },-- executeType: "confirm-dialog",- confirmTitle: () => t("common.close"),- confirmContent: () => t("plan.state.close-confirm"),-};--export const PLAN_REOPEN: ActionDefinition = {- id: "PLAN_REOPEN",- label: () => t("common.reopen"),- buttonType: "default",- category: "primary",- priority: 10,-- isVisible: (ctx) =>- !ctx.isIssueOnly &&- ctx.plan.issue === "" &&- !ctx.plan.hasRollout &&- ctx.planState === State.DELETED,-- isDisabled: (ctx) => !ctx.permissions.updatePlan,- disabledReason: (ctx) => {- if (!ctx.permissions.updatePlan) {- if (!ctx.isCreator) {- return t("common.missing-required-permission", {- permissions: "bb.plans.update",- });- }- return t("common.only-creator-allowed-action");- }- return undefined;- },-- executeType: "confirm-dialog",- confirmTitle: () => t("common.reopen"),- confirmContent: () => t("plan.state.reopen-confirm"),-};--export const planActions: ActionDefinition[] = [PLAN_CLOSE, PLAN_REOPEN];diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/actions/rollout.ts b/frontend/src/components/Plan/components/HeaderSection/Actions/registry/actions/rollout.tsdeleted file mode 100644index 7cef8a93e8..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/actions/rollout.ts+++ /dev/null@@ -1,83 +0,0 @@-import { t } from "@/plugins/i18n";-import type { ActionDefinition } from "../types";--export const ROLLOUT_START: ActionDefinition = {- id: "ROLLOUT_START",- label: (ctx) => (ctx.isExportPlan ? t("common.export") : t("common.rollout")),- buttonType: "primary",- category: "primary",- priority: 60,-- isVisible: (ctx) => {- // Only for deferred rollout plans (export/create DB) — rollout created on-demand- // Change database plans: rollout managed in Plan Detail Page's Deploy section- if (!ctx.hasDeferredRollout) return false;- if (!ctx.issue || !ctx.issueApproved) return false;- if (!ctx.rollout) return true;- return ctx.hasStartableTasks;- },-- isDisabled: (ctx) => !ctx.permissions.runTasks,- disabledReason: (ctx) => {- if (!ctx.permissions.runTasks) {- if (ctx.isExportPlan) {- return t("common.only-creator-allowed-export");- }- return t("common.missing-required-permission");- }- return undefined;- },-- executeType: "panel:rollout",-};--export const ROLLOUT_CANCEL: ActionDefinition = {- id: "ROLLOUT_CANCEL",- label: () => t("common.cancel"),- buttonType: "default",- category: "secondary",- priority: 80,-- isVisible: (ctx) => {- // Only for deferred rollout plans — change database rollouts managed on Plan Detail Page- if (!ctx.hasDeferredRollout) return false;- if (!ctx.rollout) return false;- if (!ctx.issueApproved) return false;- if (!ctx.hasRunningTasks) return false;- return true;- },-- isDisabled: (ctx) => !ctx.permissions.runTasks,- disabledReason: (ctx) => {- if (!ctx.permissions.runTasks) {- return t("common.missing-required-permission", {- permissions: "bb.taskRuns.create",- });- }- return undefined;- },-- executeType: "panel:rollout",-};--export const EXPORT_DOWNLOAD: ActionDefinition = {- id: "EXPORT_DOWNLOAD",- label: () => t("common.download"),- buttonType: "primary",- category: "primary",- priority: 0,-- isVisible: (ctx) =>- ctx.isExportPlan && ctx.exportArchiveReady && ctx.isCreator,-- isDisabled: () => false,- disabledReason: () => undefined,-- executeType: "immediate",-};--export const rolloutActions: ActionDefinition[] = [- ROLLOUT_START,- ROLLOUT_CANCEL,- EXPORT_DOWNLOAD,-];diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/components/ActionButton.vue b/frontend/src/components/Plan/components/HeaderSection/Actions/registry/components/ActionButton.vuedeleted file mode 100644index 9b4981bf26..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/components/ActionButton.vue+++ /dev/null@@ -1,34 +0,0 @@-<template>- <NTooltip :disabled="!disabledReason" placement="top">- <template #trigger>- <NButton- :type="action.buttonType"- :disabled="disabled"- size="medium"- tag="div"- @click="$emit('execute', action.id)"- >- {{ action.label(context) }}- </NButton>- </template>- <template #default>- {{ disabledReason }}- </template>- </NTooltip>-</template>--<script setup lang="ts">-import { NButton, NTooltip } from "naive-ui";-import type { ActionContext, ActionDefinition, UnifiedAction } from "../types";--defineProps<{- action: ActionDefinition;- context: ActionContext;- disabled?: boolean;- disabledReason?: string;-}>();--defineEmits<{- (e: "execute", id: UnifiedAction): void;-}>();-</script>diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/components/ActionDropdown.vue b/frontend/src/components/Plan/components/HeaderSection/Actions/registry/components/ActionDropdown.vuedeleted file mode 100644index 5cd3326444..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/components/ActionDropdown.vue+++ /dev/null@@ -1,59 +0,0 @@-<template>- <NDropdown- trigger="click"- placement="bottom-end"- :options="dropdownOptions"- :disabled="globalDisabled"- @select="handleSelect"- >- <NButton- class="px-1!"- quaternary- size="medium"- :disabled="globalDisabled"- :title="globalDisabled ? globalDisabledReason : undefined"- >- <EllipsisVerticalIcon class="w-4 h-4" />- </NButton>- </NDropdown>-</template>--<script setup lang="ts">-import { EllipsisVerticalIcon } from "lucide-vue-next";-import { type DropdownOption, NButton, NDropdown } from "naive-ui";-import { computed } from "vue";-import type { ActionContext, ActionDefinition, UnifiedAction } from "../types";--const props = defineProps<{- actions: ActionDefinition[];- context: ActionContext;- globalDisabled?: boolean;- globalDisabledReason?: string;- isActionDisabled: (action: ActionDefinition) => boolean;- getDisabledReason: (action: ActionDefinition) => string | undefined;-}>();--const emit = defineEmits<{- (e: "execute", id: UnifiedAction): void;-}>();--const dropdownOptions = computed((): DropdownOption[] => {- return props.actions.map((action) => {- const disabled = props.isActionDisabled(action);- const reason = disabled ? props.getDisabledReason(action) : undefined;- return {- key: action.id,- label: action.label(props.context),- disabled,- props: reason ? { title: reason } : undefined,- };- });-});--const handleSelect = (key: string) => {- const action = props.actions.find((a) => a.id === key);- if (action && !props.isActionDisabled(action)) {- emit("execute", action.id);- }-};-</script>diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/components/IssueReviewButton.vue b/frontend/src/components/Plan/components/HeaderSection/Actions/registry/components/IssueReviewButton.vuedeleted file mode 100644index 27a889ffe0..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/components/IssueReviewButton.vue+++ /dev/null@@ -1,267 +0,0 @@-<template>- <!-- Desktop: NPopover -->- <NPopover- v-if="!isMobile"- trigger="click"- placement="bottom-end"- :show="showPanel"- :show-arrow="false"- @update:show="showPanel = $event"- >- <template #trigger>- <NTooltip :disabled="errors.length === 0" placement="top">- <template #trigger>- <NButton- type="primary"- size="medium"- tag="div"- :disabled="errors.length > 0 || loading || disabled"- icon-placement="right"- >- {{ $t("issue.review.self") }}- <template #icon>- <ChevronDownIcon class="w-4 h-4" />- </template>- </NButton>- </template>- <template #default>- <ErrorList :errors="errors" />- </template>- </NTooltip>- </template>-- <template #default>- <IssueReviewForm- v-if="showPanel"- class="w-128 p-1"- :can-approve="canApprove"- :can-reject="canReject"- :loading="loading"- :plan-check-warnings="planCheckWarnings"- :project="project"- @cancel="showPanel = false"- @submit="handleSubmit"- />- </template>- </NPopover>-- <!-- Mobile: Button + Drawer -->- <template v-else>- <NTooltip :disabled="errors.length === 0" placement="top">- <template #trigger>- <NButton- type="primary"- size="medium"- tag="div"- :disabled="errors.length > 0 || loading || disabled"- icon-placement="right"- @click="showPanel = true"- >- {{ $t("issue.review.self") }}- <template #icon>- <ChevronDownIcon class="w-4 h-4" />- </template>- </NButton>- </template>- <template #default>- <ErrorList :errors="errors" />- </template>- </NTooltip>-- <Drawer :show="showPanel" @close="showPanel = false">- <DrawerContent- :title="$t('issue.review.self')"- class="w-[calc(100vw-2rem)] max-w-128"- >- <IssueReviewForm- v-if="showPanel"- compact- :can-approve="canApprove"- :can-reject="canReject"- :loading="loading"- :plan-check-warnings="planCheckWarnings"- :project="project"- @cancel="showPanel = false"- @submit="handleSubmit"- />- </DrawerContent>- </Drawer>- </template>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { ChevronDownIcon } from "lucide-vue-next";-import { NButton, NPopover, NTooltip } from "naive-ui";-import { computed, nextTick, ref } from "vue";-import { useI18n } from "vue-i18n";-import { useRouter } from "vue-router";-import { ErrorList } from "@/components/Plan/components/common";-import { usePlanContext } from "@/components/Plan/logic";-import { useSidebarContext } from "@/components/Plan/logic/sidebar";-import { Drawer, DrawerContent } from "@/components/v2";-import { issueServiceClientConnect } from "@/connect";-import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";-import { buildPlanDeployRouteFromPlanName } from "@/router/dashboard/projectV1RouteHelpers";-import {- pushNotification,- useCurrentProjectV1,- useIssueCommentStore,-} from "@/store";-import {- ApproveIssueRequestSchema,- RejectIssueRequestSchema,-} from "@/types/proto-es/v1/issue_service_pb";-import { PlanCheckRun_Status } from "@/types/proto-es/v1/plan_service_pb";-import { extractIssueUID, extractProjectResourceName } from "@/utils";-import IssueReviewForm, { type ReviewAction } from "./IssueReviewForm.vue";--const props = defineProps<{- canApprove: boolean;- canReject: boolean;- disabled?: boolean;- disabledReason?: string;-}>();--const { t } = useI18n();-const router = useRouter();-const { project } = useCurrentProjectV1();-const { plan, issue, planCheckRuns, events } = usePlanContext();-const issueCommentStore = useIssueCommentStore();-const { mode: sidebarMode } = useSidebarContext();--const isMobile = computed(() => sidebarMode.value === "MOBILE");-const loading = ref(false);-const showPanel = ref(false);--const errors = computed(() => {- const list: string[] = [];- if (props.disabledReason) {- list.push(props.disabledReason);- }- return list;-});--const planCheckWarnings = computed(() => {- const warnings: string[] = [];- if (!planCheckRuns.value) return warnings;-- const failedRuns = planCheckRuns.value.filter(- (run) => run.status === PlanCheckRun_Status.FAILED- );- const runningRuns = planCheckRuns.value.filter(- (run) => run.status === PlanCheckRun_Status.RUNNING- );-- if (failedRuns.length > 0) {- warnings.push(- t(- "custom-approval.issue-review.disallow-approve-reason.some-task-checks-didnt-pass"- )- );- }- if (runningRuns.length > 0) {- warnings.push(- t(- "custom-approval.issue-review.disallow-approve-reason.some-task-checks-are-still-running"- )- );- }-- return warnings;-});--const handleSubmit = async (payload: {- action: ReviewAction;- comment: string;-}) => {- if (loading.value) return;-- const issueValue = issue?.value;- if (!issueValue) return;-- loading.value = true;-- try {- const { action, comment } = payload;-- if (action === "APPROVE") {- const request = create(ApproveIssueRequestSchema, {- name: issueValue.name,- comment,- });- await issueServiceClientConnect.approveIssue(request);- } else if (action === "REJECT") {- const request = create(RejectIssueRequestSchema, {- name: issueValue.name,- comment,- });- await issueServiceClientConnect.rejectIssue(request);- } else if (action === "COMMENT") {- await issueCommentStore.createIssueComment({- issueName: issueValue.name,- comment,- });- }-- events.emit("perform-issue-review-action", { action: "ISSUE_REVIEW" });- showPanel.value = false;- handlePostActionNavigation(action, issueValue);- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.failed"),- description: String(error),- });- } finally {- loading.value = false;- }-};--const handlePostActionNavigation = (- action: ReviewAction,- issueValue: NonNullable<typeof issue.value>-) => {- if (action === "COMMENT") return;- const hasDeferredRollout = plan.value.specs.some(- (spec) =>- spec.config.case === "createDatabaseConfig" ||- spec.config.case === "exportDataConfig"- );- if (hasDeferredRollout) return;-- if (action === "APPROVE") {- const { approvalTemplate, approvers } = issueValue;- const roles = approvalTemplate?.flow?.roles ?? [];- const isLastApproval =- roles.length > 0 && approvers.length + 1 >= roles.length;-- if (isLastApproval) {- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("issue.approval.approved-and-waiting-for-rollout"),- });-- if (!plan.value.hasRollout) return;-- nextTick(() => {- router.push(buildPlanDeployRouteFromPlanName(plan.value.name));- });- return;- }- }-- nextTick(() => {- router.push({- name: PROJECT_V1_ROUTE_ISSUE_DETAIL,- params: {- projectId: extractProjectResourceName(issueValue.name),- issueId: extractIssueUID(issueValue.name),- },- hash: "#issue-comment-editor",- });- });-};-</script>diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/components/IssueReviewForm.vue b/frontend/src/components/Plan/components/HeaderSection/Actions/registry/components/IssueReviewForm.vuedeleted file mode 100644index a76ff6eab1..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/components/IssueReviewForm.vue+++ /dev/null@@ -1,166 +0,0 @@-<template>- <div class="flex flex-col gap-y-4">- <MarkdownEditor- mode="editor"- :content="comment"- :project="project"- :compact="compact"- :maxlength="65536"- @change="(val: string) => (comment = val)"- />-- <NRadioGroup- v-model:value="selectedAction"- :disabled="loading"- class="flex! flex-col gap-y-2"- >- <NRadio value="COMMENT">- <div class="flex items-start gap-2">- <MessageCircleIcon class="w-4 h-4 mt-0.5 text-gray-600 shrink-0" />- <div class="flex flex-col">- <span class="font-medium">{{ $t("common.comment") }}</span>- <span class="text-control-light text-xs">- {{ $t("issue.review.comment-description") }}- </span>- </div>- </div>- </NRadio>-- <NRadio v-if="canApprove" value="APPROVE">- <div class="flex items-start gap-2">- <CheckIcon class="w-4 h-4 mt-0.5 text-green-600 shrink-0" />- <div class="flex flex-col">- <span class="font-medium">{{ $t("common.approve") }}</span>- <span class="text-control-light text-xs">- {{ $t("issue.review.approve-description") }}- </span>- </div>- </div>- </NRadio>-- <NRadio v-if="canReject" value="REJECT">- <div class="flex items-start gap-2">- <XIcon class="w-4 h-4 mt-0.5 text-red-600 shrink-0" />- <div class="flex flex-col">- <span class="font-medium">{{ $t("common.reject") }}</span>- <span class="text-control-light text-xs">- {{ $t("issue.review.reject-description") }}- </span>- </div>- </div>- </NRadio>- </NRadioGroup>-- <NAlert- v-if="selectedAction === 'APPROVE' && planCheckWarnings.length > 0"- type="warning"- size="small"- >- <ul class="text-sm">- <li- v-for="(warning, index) in planCheckWarnings"- :key="index"- class="list-disc list-inside"- >- {{ warning }}- </li>- </ul>- <NCheckbox- v-model:checked="performActionAnyway"- class="mt-2"- size="small"- >- {{- $t("issue.action-anyway", {- action: $t("common.approve"),- })- }}- </NCheckbox>- </NAlert>-- <div class="flex justify-end gap-x-2">- <NButton quaternary @click="$emit('cancel')">- {{ $t("common.cancel") }}- </NButton>- <NTooltip :disabled="confirmErrors.length === 0" placement="top">- <template #trigger>- <NButton- type="primary"- :disabled="confirmErrors.length > 0 || loading"- :loading="loading"- @click="- $emit('submit', {- action: selectedAction,- comment,- })- "- >- {{ $t("common.submit") }}- </NButton>- </template>- <template #default>- <ErrorList :errors="confirmErrors" />- </template>- </NTooltip>- </div>- </div>-</template>--<script setup lang="ts">-import { CheckIcon, MessageCircleIcon, XIcon } from "lucide-vue-next";-import {- NAlert,- NButton,- NCheckbox,- NRadio,- NRadioGroup,- NTooltip,-} from "naive-ui";-import { computed, ref } from "vue";-import { useI18n } from "vue-i18n";-import MarkdownEditor from "@/components/MarkdownEditor";-import { ErrorList } from "@/components/Plan/components/common";-import type { Project } from "@/types/proto-es/v1/project_service_pb";--export type ReviewAction = "APPROVE" | "REJECT" | "COMMENT";--const props = defineProps<{- canApprove: boolean;- canReject: boolean;- loading: boolean;- compact?: boolean;- planCheckWarnings: string[];- project: Project;-}>();--defineEmits<{- (event: "submit", payload: { action: ReviewAction; comment: string }): void;- (event: "cancel"): void;-}>();--const { t } = useI18n();--const comment = ref("");-const selectedAction = ref<ReviewAction>("COMMENT");-const performActionAnyway = ref(false);--const confirmErrors = computed(() => {- const list: string[] = [];- if (selectedAction.value === "COMMENT" && !comment.value.trim()) {- list.push(- t(- "custom-approval.issue-review.disallow-approve-reason.x-field-is-required",- { field: t("common.comment") }- )- );- }- if (- selectedAction.value === "APPROVE" &&- props.planCheckWarnings.length > 0 &&- !performActionAnyway.value- ) {- list.push(...props.planCheckWarnings);- }- return list;-});-</script>diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/components/index.ts b/frontend/src/components/Plan/components/HeaderSection/Actions/registry/components/index.tsdeleted file mode 100644index 59f8fc36a1..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/components/index.ts+++ /dev/null@@ -1,3 +0,0 @@-export { default as ActionButton } from "./ActionButton.vue";-export { default as ActionDropdown } from "./ActionDropdown.vue";-export { default as IssueReviewButton } from "./IssueReviewButton.vue";diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/context.ts b/frontend/src/components/Plan/components/HeaderSection/Actions/registry/context.tsdeleted file mode 100644index 10bd0c0001..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/context.ts+++ /dev/null@@ -1,279 +0,0 @@-import { first, orderBy } from "lodash-es";-import { isApprovalCompleted } from "@/components/Plan/logic/approval";-import { candidatesOfApprovalStepV1, extractUserEmail } from "@/store";-import type { Issue } from "@/types/proto-es/v1/issue_service_pb";-import {- Issue_Approver_Status,- Issue_Type,- IssueStatus,-} from "@/types/proto-es/v1/issue_service_pb";-import type { Plan } from "@/types/proto-es/v1/plan_service_pb";-import type { Project } from "@/types/proto-es/v1/project_service_pb";-import type { Rollout, TaskRun } from "@/types/proto-es/v1/rollout_service_pb";-import {- Task_Status,- Task_Type,- TaskRun_ExportArchiveStatus,- TaskRun_Status,-} from "@/types/proto-es/v1/rollout_service_pb";-import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";-import type { User } from "@/types/proto-es/v1/user_service_pb";-import {- extractTaskRunUID,- extractTaskUID,- hasProjectPermissionV2,- isUserIncludedInList,- isValidIssueName,- isValidPlanName,-} from "@/utils";-import type {- ActionContext,- ActionPermissions,- ActionValidation,-} from "./types";--export interface ContextBuilderInput {- plan: Plan;- issue: Issue | undefined;- rollout: Rollout | undefined;- project: Project;- currentUser: User;- taskRuns: TaskRun[];- isCreating: boolean;- planCheckStatus: Advice_Level;- hasRunningPlanChecks: boolean;- isSpecEmpty: (spec: Plan["specs"][0]) => boolean;-}--function computeIsApprovalCandidate(- issue: Issue | undefined,- currentUser: User,- project: Project-): boolean {- if (!issue) return false;-- const issueApproved = isApprovalCompleted(issue);- if (issueApproved) return false;-- const { approvers, approvalTemplate } = issue;- const hasRejection = approvers.some(- (app: Issue["approvers"][0]) =>- app.status === Issue_Approver_Status.REJECTED- );-- // Cannot approve or reject if already rejected- if (hasRejection) return false;-- const roles = approvalTemplate?.flow?.roles ?? [];- if (roles.length === 0) return false;-- const rejectedIndex = approvers.findIndex(- (ap: Issue["approvers"][0]) => ap.status === Issue_Approver_Status.REJECTED- );- const currentRoleIndex =- rejectedIndex >= 0 ? rejectedIndex : approvers.length;- const currentRole = roles[currentRoleIndex];- if (!currentRole) return false;-- const candidates = candidatesOfApprovalStepV1(issue, currentRole);- if (!isUserIncludedInList(currentUser.email, candidates)) return false;-- // Block self-approval even when matched via ALL_USERS- if (- !project.allowSelfApproval &&- currentUser.email === extractUserEmail(issue.creator)- ) {- return false;- }- return true;-}--function computeExportArchiveReady(- rollout: Rollout | undefined,- taskRuns: TaskRun[],- issue: Issue | undefined,- currentUserEmail: string-): boolean {- if (!issue) return false;- if (![IssueStatus.OPEN, IssueStatus.DONE].includes(issue.status))- return false;- if (currentUserEmail !== extractUserEmail(issue.creator)) return false;-- const exportTasks =- rollout?.stages- .flatMap((stage) => stage.tasks)- .filter((task) => task.type === Task_Type.DATABASE_EXPORT) || [];-- if (exportTasks.length === 0) return false;-- if (- !exportTasks.every((task) =>- [Task_Status.DONE, Task_Status.SKIPPED].includes(task.status)- )- ) {- return false;- }-- // Only consider DONE tasks for archive readiness (skipped tasks don't have archives)- const doneTasks = exportTasks.filter(- (task) => task.status === Task_Status.DONE- );-- // Need at least one DONE task to have an archive to download- if (doneTasks.length === 0) {- return false;- }-- const exportTaskRuns = doneTasks- .map((task) => {- const taskRunsForTask = taskRuns.filter(- (taskRun) => extractTaskUID(taskRun.name) === extractTaskUID(task.name)- );- return first(- orderBy(- taskRunsForTask,- (taskRun) => Number(extractTaskRunUID(taskRun.name)),- "desc"- )- );- })- .filter(Boolean) as TaskRun[];-- if (- exportTaskRuns.length === 0 ||- exportTaskRuns.some(- (taskRun) =>- taskRun.status !== TaskRun_Status.DONE ||- taskRun.exportArchiveStatus ===- TaskRun_ExportArchiveStatus.EXPORT_ARCHIVE_STATUS_UNSPECIFIED- )- ) {- return false;- }-- return true;-}--export function buildActionContext(input: ContextBuilderInput): ActionContext {- const {- plan,- issue,- rollout,- project,- currentUser,- taskRuns,- isCreating,- planCheckStatus,- hasRunningPlanChecks,- isSpecEmpty,- } = input;-- const currentUserEmail = currentUser.email;- const isIssueOnly =- !isValidPlanName(plan.name) && !!isValidIssueName(issue?.name);- const isExportPlan = plan.specs.some(- (spec) => spec.config?.case === "exportDataConfig"- );- const isReleasePlan = plan.specs.some(- (spec) =>- spec.config?.case === "changeDatabaseConfig" &&- !!spec.config.value.release- );- // Plans where rollout is created on-demand when user clicks action button- const hasDeferredRollout = plan.specs.some(- (spec) =>- spec.config?.case === "exportDataConfig" ||- spec.config?.case === "createDatabaseConfig"- );- const isCreator =- currentUserEmail === extractUserEmail(plan.creator || "") ||- (issue ? currentUserEmail === extractUserEmail(issue.creator) : false);-- // Compute permissions- const isApprovalCandidate = computeIsApprovalCandidate(- issue,- currentUser,- project- );- const permissions: ActionPermissions = {- updatePlan:- currentUserEmail === extractUserEmail(plan.creator || "") ||- hasProjectPermissionV2(project, "bb.plans.update"),- createIssue: hasProjectPermissionV2(project, "bb.issues.create"),- updateIssue: hasProjectPermissionV2(project, "bb.issues.update"),- createRollout: hasProjectPermissionV2(project, "bb.rollouts.create"),- runTasks:- issue?.type === Issue_Type.DATABASE_EXPORT- ? currentUserEmail === extractUserEmail(issue.creator)- : hasProjectPermissionV2(project, "bb.taskRuns.create"),- isApprovalCandidate,- };-- // Compute validation state- const validation: ActionValidation = {- hasEmptySpec: plan.specs.some((spec) => isSpecEmpty(spec)),- planChecksRunning: hasRunningPlanChecks,- planChecksFailed: planCheckStatus === Advice_Level.ERROR,- };-- // Compute task-related flags- const allTasks = rollout?.stages.flatMap((stage) => stage.tasks) || [];-- const allTasksFinished = allTasks.every((task) =>- [Task_Status.DONE, Task_Status.SKIPPED].includes(task.status)- );-- const hasDatabaseCreateOrExportTasks = allTasks.some(- (task) =>- task.type === Task_Type.DATABASE_CREATE ||- task.type === Task_Type.DATABASE_EXPORT- );-- const hasStartableTasks = allTasks.some((task) =>- [- Task_Status.NOT_STARTED,- Task_Status.FAILED,- Task_Status.CANCELED,- ].includes(task.status)- );-- const hasRunningTasks = allTasks.some((task) =>- [Task_Status.PENDING, Task_Status.RUNNING].includes(task.status)- );-- // Compute approval status- // Treat approval as complete only after the status is finalized, or after- // approval finding resolves to an empty flow (no approval required).- const issueApproved = isApprovalCompleted(issue);-- return {- plan,- issue,- rollout,- project,-- planState: plan.state,- issueStatus: issue?.status,- approvalStatus: issue?.approvalStatus,-- isCreating,- isIssueOnly,- isExportPlan,- isReleasePlan,- hasDeferredRollout,- isCreator,- issueApproved,- exportArchiveReady: computeExportArchiveReady(- rollout,- taskRuns,- issue,- currentUserEmail- ),- allTasksFinished,- hasDatabaseCreateOrExportTasks,- hasStartableTasks,- hasRunningTasks,- permissions,- validation,- };-}diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/index.ts b/frontend/src/components/Plan/components/HeaderSection/Actions/registry/index.tsdeleted file mode 100644index faa4beb025..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/index.ts+++ /dev/null@@ -1,5 +0,0 @@-export * from "./types";-export * from "./context";-export * from "./useActionRegistry";-export * from "./actions";-export { ActionButton, ActionDropdown, IssueReviewButton } from "./components";diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/types.ts b/frontend/src/components/Plan/components/HeaderSection/Actions/registry/types.tsdeleted file mode 100644index 6617ada71d..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/types.ts+++ /dev/null@@ -1,113 +0,0 @@-import type { ComputedRef } from "vue";-import type { State } from "@/types/proto-es/v1/common_pb";-import type {- Issue,- Issue_ApprovalStatus,- IssueStatus,-} from "@/types/proto-es/v1/issue_service_pb";-import type { Plan } from "@/types/proto-es/v1/plan_service_pb";-import type { Project } from "@/types/proto-es/v1/project_service_pb";-import type { Rollout } from "@/types/proto-es/v1/rollout_service_pb";--// Action type definitions-export type IssueReviewAction = "ISSUE_REVIEW";--export type IssueStatusAction = "ISSUE_STATUS_CLOSE" | "ISSUE_STATUS_REOPEN";--export type IssueAction =- | IssueReviewAction- | IssueStatusAction- | "ISSUE_CREATE";--export type PlanAction = "PLAN_CLOSE" | "PLAN_REOPEN";--export type RolloutAction = "ROLLOUT_START" | "ROLLOUT_CANCEL";--export type ExportAction = "EXPORT_DOWNLOAD";--export type UnifiedAction =- | IssueAction- | PlanAction- | RolloutAction- | ExportAction;--export type ExecuteType =- | "immediate"- | "confirm-dialog"- | "popover:labels"- | "popover:review"- | "panel:issue-status"- | "panel:rollout";--export interface ActionPermissions {- updatePlan: boolean;- createIssue: boolean;- updateIssue: boolean;- createRollout: boolean;- runTasks: boolean;- isApprovalCandidate: boolean;-}--export interface ActionValidation {- hasEmptySpec: boolean;- planChecksRunning: boolean;- planChecksFailed: boolean;-}--export interface ActionContext {- // Entities- plan: Plan;- issue: Issue | undefined;- rollout: Rollout | undefined;- project: Project;-- // Proto enums directly- planState: State;- issueStatus: IssueStatus | undefined;- approvalStatus: Issue_ApprovalStatus | undefined;-- // Derived flags- isCreating: boolean;- isIssueOnly: boolean;- isExportPlan: boolean;- isReleasePlan: boolean;- // Plans where rollout is created on-demand (export, create database)- hasDeferredRollout: boolean;- isCreator: boolean;- issueApproved: boolean; // approval is finalized or not required- exportArchiveReady: boolean;- allTasksFinished: boolean;- hasDatabaseCreateOrExportTasks: boolean;- hasStartableTasks: boolean;- hasRunningTasks: boolean;- // Grouped- permissions: ActionPermissions;- validation: ActionValidation;-}--export type ActionCategory = "primary" | "secondary";--export interface ActionDefinition {- id: UnifiedAction;- label: (ctx: ActionContext) => string;- buttonType: "primary" | "success" | "default";- category: ActionCategory | ((ctx: ActionContext) => ActionCategory);- priority: number;-- isVisible: (ctx: ActionContext) => boolean;- isDisabled: (ctx: ActionContext) => boolean;- disabledReason: (ctx: ActionContext) => string | undefined;-- executeType: ExecuteType;- execute?: (ctx: ActionContext) => Promise<void>;- confirmTitle?: (ctx: ActionContext) => string;- confirmContent?: (ctx: ActionContext) => string;-}--export interface ActionRegistryReturn {- context: ComputedRef<ActionContext>;- primaryAction: ComputedRef<ActionDefinition | undefined>;- secondaryActions: ComputedRef<ActionDefinition[]>;- isActionDisabled: (action: ActionDefinition) => boolean;- getDisabledReason: (action: ActionDefinition) => string | undefined;-}diff --git a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/useActionRegistry.ts b/frontend/src/components/Plan/components/HeaderSection/Actions/registry/useActionRegistry.tsdeleted file mode 100644index 2bb32540d2..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/Actions/registry/useActionRegistry.ts+++ /dev/null@@ -1,88 +0,0 @@-import { computed } from "vue";-import { useSpecsValidation } from "@/components/Plan/components/common";-import { usePlanContext } from "@/components/Plan/logic";-import { useEditorState } from "@/components/Plan/logic/useEditorState";-import { usePlanCheckStatus } from "@/components/Plan/logic/usePlanCheckStatus";-import { t } from "@/plugins/i18n";-import { useCurrentProjectV1, useCurrentUserV1 } from "@/store";-import { allActions } from "./actions";-import { buildActionContext } from "./context";-import type { ActionDefinition, ActionRegistryReturn } from "./types";--export function useActionRegistry(): ActionRegistryReturn {- const currentUser = useCurrentUserV1();- const { project } = useCurrentProjectV1();- const { isCreating, plan, issue, rollout, taskRuns } = usePlanContext();- const editorState = useEditorState();- const { isSpecEmpty } = useSpecsValidation(computed(() => plan.value.specs));- const {- getOverallStatus: planCheckStatus,- hasRunning: hasRunningPlanChecks,- } = usePlanCheckStatus(plan);-- // Build context reactively- const context = computed(() =>- buildActionContext({- plan: plan.value,- issue: issue.value,- rollout: rollout.value,- project: project.value,- currentUser: currentUser.value,- taskRuns: taskRuns.value,- isCreating: isCreating.value,- planCheckStatus: planCheckStatus.value,- hasRunningPlanChecks: hasRunningPlanChecks.value,- isSpecEmpty,- })- );-- // Global disabled state (editor is editing)- const globalDisabled = computed(() => editorState.isEditing.value);- const globalDisabledReason = computed(() =>- globalDisabled.value- ? t("plan.editor.save-changes-before-continuing")- : undefined- );-- // Helper to resolve category (static or dynamic)- const getCategory = (action: ActionDefinition) =>- typeof action.category === "function"- ? action.category(context.value)- : action.category;-- // Filter visible actions (no actions during plan creation)- const visibleActions = computed(() => {- if (isCreating.value) return [];- return allActions.filter((action) => action.isVisible(context.value));- });-- // Primary action (first visible by priority, category=primary)- const primaryAction = computed(() =>- visibleActions.value.find((a) => getCategory(a) === "primary")- );-- // Secondary actions: all secondary-category actions + remaining primary actions (excluding the chosen primary)- const secondaryActions = computed(() =>- visibleActions.value.filter(- (a) =>- getCategory(a) === "secondary" ||- (getCategory(a) === "primary" && a.id !== primaryAction.value?.id)- )- );-- // Check if action is disabled (global or action-specific)- const isActionDisabled = (action: ActionDefinition) =>- globalDisabled.value || action.isDisabled(context.value);-- // Get disabled reason (global takes precedence)- const getDisabledReason = (action: ActionDefinition) =>- globalDisabledReason.value || action.disabledReason(context.value);-- return {- context,- primaryAction,- secondaryActions,- isActionDisabled,- getDisabledReason,- };-}diff --git a/frontend/src/components/Plan/components/HeaderSection/DescriptionSection.vue b/frontend/src/components/Plan/components/HeaderSection/DescriptionSection.vuedeleted file mode 100644index 9c43ba1722..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/DescriptionSection.vue+++ /dev/null@@ -1,209 +0,0 @@-<template>- <div class="flex-1">- <template v-if="!state.isExpanded">- <NButton- v-if="!state.description && allowEdit"- text- size="small"- class="italic opacity-60"- @click="handleExpand($event)"- >- <template #icon>- <PlusIcon class="w-4 h-4" />- </template>- {{ $t("plan.description.placeholder") }}- </NButton>- <div v-else class="mt-1">- <div- class="relative px-2 py-1 rounded-md border border-transparent transition-all duration-200"- :class="[- allowEdit ? 'cursor-pointer hover:border-gray-200' : '',- !state.showFullDescription ? 'max-h-[4.5rem] overflow-hidden' : '',- ]"- @click="allowEdit && handleExpand($event)"- >- <MarkdownEditor- mode="preview"- class="pointer-events-none"- :content="state.description"- :project="project"- />- <!-- Fade overlay when truncated -->- <div- v-if="!state.showFullDescription && isDescriptionLong"- class="absolute bottom-0 left-0 right-0 h-6 bg-gradient-to-t from-white to-transparent pointer-events-none"- />- </div>- <button- v-if="isDescriptionLong"- class="text-xs text-control-placeholder hover:text-control mt-1 px-2"- @click.stop="state.showFullDescription = !state.showFullDescription"- >- {{ state.showFullDescription ? $t("common.show-less") : $t("common.show-more") }}- </button>- </div>- </template>- <div v-else class="py-2">- <div class="flex items-center justify-between">- <span class="text-base font-medium">{{- $t("common.description")- }}</span>- <div class="flex items-center gap-2">- <template v-if="!isCreating">- <NButton- size="small"- :disabled="- state.isUpdating ||- !allowEdit ||- state.description === plan.description- "- @click="handleSave"- >- {{ $t("common.save") }}- </NButton>- <NButton size="small" quaternary @click="handleCancel">- {{ $t("common.cancel") }}- </NButton>- </template>- <NButton v-else size="tiny" @click="handleCancel">- <template #icon>- <ChevronUpIcon class="w-4 h-4" />- </template>- {{ $t("common.collapse") }}- </NButton>- </div>- </div>- <MarkdownEditor- :content="state.description"- mode="editor"- :autofocus="state.shouldAutoFocus"- :project="project"- :placeholder="$t('plan.description.placeholder')"- @change="onUpdateValue"- />- </div>- </div>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { ChevronUpIcon, PlusIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { computed, reactive, watch } from "vue";-import MarkdownEditor from "@/components/MarkdownEditor";-import { useResourcePoller } from "@/components/Plan/logic/poller";-import { planServiceClientConnect } from "@/connect";-import { useCurrentProjectV1 } from "@/store";-import {- PlanSchema,- UpdatePlanRequestSchema,-} from "@/types/proto-es/v1/plan_service_pb";-import { usePlanContext } from "../../logic";--const { project } = useCurrentProjectV1();-const {- isCreating,- plan,- readonly,- issue,- allowEdit: hasPermission,-} = usePlanContext();-const { refreshResources } = useResourcePoller();--const state = reactive({- isUpdating: false,- description: plan.value.description,- isExpanded: false,- shouldAutoFocus: false,- justExpanded: false,- showFullDescription: false,-});--// Description longer than ~3 lines of text-const isDescriptionLong = computed(() => {- return (- (state.description?.length ?? 0) > 150 ||- (state.description?.split("\n").length ?? 0) > 3- );-});--const allowEdit = computed(() => {- if (readonly.value) {- return false;- }- if (isCreating.value) {- return true;- }- // Plans with rollout should have readonly description- if (!issue.value && plan.value.hasRollout) {- return false;- }- return hasPermission.value;-});--const handleExpand = (event: MouseEvent) => {- if (!allowEdit.value) return;- event.stopPropagation();- state.shouldAutoFocus = true;- state.isExpanded = true;- state.justExpanded = true;- // Add a small delay before allowing click outside to work- setTimeout(() => {- state.shouldAutoFocus = false;- state.justExpanded = false;- }, 100);-};--const handleCancel = () => {- state.description = plan.value.description;- state.isExpanded = false;- if (isCreating.value) {- plan.value.description = state.description;- }-};--const handleSave = async () => {- if (isCreating.value) {- plan.value.description = state.description;- state.isExpanded = false;- return;- }-- if (!allowEdit.value) return;-- try {- state.isUpdating = true;- const planPatch = create(PlanSchema, {- ...plan.value,- description: state.description,- });- const request = create(UpdatePlanRequestSchema, {- plan: planPatch,- updateMask: { paths: ["description"] },- });- const response = await planServiceClientConnect.updatePlan(request);- Object.assign(plan.value, response);- refreshResources(["plan"], true /** force */);- state.isExpanded = false;- } finally {- state.isUpdating = false;- }-};--const onUpdateValue = (value: string) => {- state.description = value;- if (isCreating.value) {- plan.value.description = state.description;- }-};--watch(- () => plan.value.description,- (newValue) => {- if (state.description !== newValue) {- state.description = newValue;- }- },- { immediate: true }-);-</script>diff --git a/frontend/src/components/Plan/components/HeaderSection/HeaderSection.vue b/frontend/src/components/Plan/components/HeaderSection/HeaderSection.vuedeleted file mode 100644index 3035c57c6f..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/HeaderSection.vue+++ /dev/null@@ -1,131 +0,0 @@-<template>- <div class="py-2 px-2 sm:px-4">- <div class="flex flex-row items-center justify-between gap-2">- <NTag v-if="showClosedTag" round type="default">- <template #icon>- <BanIcon class="w-4 h-4" />- </template>- {{ $t("common.closed") }}- </NTag>- <NTag v-else-if="showDraftTag" round>- <template #icon>- <CircleDotDashedIcon class="w-4 h-4" />- </template>- {{ $t("common.draft") }}- </NTag>- <NTag v-else-if="showDoneTag" round type="success">- <template #icon>- <CheckCircle2Icon class="w-4 h-4" />- </template>- {{ $t("common.approved") }}- </NTag>- <TitleInput />- <div class="flex flex-row items-center justify-end">- <Actions />- <!-- Mobile hamburger menu -->- <NButton- v-if="hasSidebar && sidebarMode === 'MOBILE'"- class="px-1!"- quaternary- size="medium"- @click="handleMobileSidebarOpen"- >- <MenuIcon class="w-5 h-5" />- </NButton>- </div>- </div>- <DescriptionSection v-if="showDescriptionSection" />- </div>-</template>--<script lang="ts" setup>-import {- BanIcon,- CheckCircle2Icon,- CircleDotDashedIcon,- MenuIcon,-} from "lucide-vue-next";-import { NButton, NTag } from "naive-ui";-import { computed } from "vue";-import { useRoute } from "vue-router";-import {- PROJECT_V1_ROUTE_ISSUE_DETAIL,- PROJECT_V1_ROUTE_PLAN_DETAIL,- PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,- PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,-} from "@/router/dashboard/projectV1";-import { State } from "@/types/proto-es/v1/common_pb";-import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";-import { isValidPlanName } from "@/utils";-import { usePlanContext } from "../../logic";-import { useSidebarContext } from "../../logic/sidebar";-import Actions from "./Actions";-import DescriptionSection from "./DescriptionSection.vue";-import TitleInput from "./TitleInput.vue";--const route = useRoute();-const { isCreating, plan, issue } = usePlanContext();--const isPlanDetailPage = computed(() => {- return (- route.name === PROJECT_V1_ROUTE_PLAN_DETAIL ||- route.name === PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS ||- route.name === PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL- );-});--const isIssueDetailPage = computed(() => {- return route.name === PROJECT_V1_ROUTE_ISSUE_DETAIL;-});--const hasSidebar = computed(() => {- // Check if we're in a layout with sidebar (Issue overview tab only)- // The sidebar only exists when there's an issue AND we're on the overview tab- if (!plan.value.issue) return false;-- return isIssueDetailPage.value;-});--const { mode: sidebarMode, mobileSidebarOpen } = useSidebarContext();--const handleMobileSidebarOpen = () => {- mobileSidebarOpen.value = true;-};--const showDraftTag = computed(() => {- // Only show draft tag on plan detail page- if (!isPlanDetailPage.value) return false;- return (- !isCreating.value &&- isValidPlanName(plan.value.name) &&- !plan.value.issue &&- !plan.value.hasRollout- );-});--const showClosedTag = computed(() => {- // On plan detail page: show when plan is deleted- if (isPlanDetailPage.value) {- return plan.value.state === State.DELETED;- }- // On issue detail page: show when issue is canceled- if (isIssueDetailPage.value) {- return issue.value?.status === IssueStatus.CANCELED;- }- return false;-});--const showDoneTag = computed(() => {- // Only show done tag on issue detail page- if (!isIssueDetailPage.value) return false;- return issue.value?.status === IssueStatus.DONE;-});--const showDescriptionSection = computed(() => {- if (isCreating.value) return true;- // On Plan Detail Page: always show description- if (isPlanDetailPage.value) return isValidPlanName(plan.value.name);- // On Issue page: description is managed by the Issue page itself- return false;-});-</script>diff --git a/frontend/src/components/Plan/components/HeaderSection/TitleInput.vue b/frontend/src/components/Plan/components/HeaderSection/TitleInput.vuedeleted file mode 100644index 119e656c15..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/TitleInput.vue+++ /dev/null@@ -1,224 +0,0 @@-<template>- <div class="flex-1">- <NInput- v-model:value="state.title"- :style="style"- :loading="state.isUpdating"- :disabled="!allowEdit || state.isUpdating"- :maxlength="200"- size="medium"- required- class="bb-plan-title-input"- @focus="state.isEditing = true"- @blur="onBlur"- @keydown.enter="onEnter"- @update:value="onUpdateValue"- />- </div>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { NInput } from "naive-ui";-import type { CSSProperties } from "vue";-import { computed, reactive, watch } from "vue";-import { useI18n } from "vue-i18n";-import { issueServiceClientConnect, planServiceClientConnect } from "@/connect";-import { pushNotification, useCurrentProjectV1 } from "@/store";-import {- IssueSchema,- UpdateIssueRequestSchema,-} from "@/types/proto-es/v1/issue_service_pb";-import {- PlanSchema,- UpdatePlanRequestSchema,-} from "@/types/proto-es/v1/plan_service_pb";-import { hasProjectPermissionV2 } from "@/utils";-import { usePlanContext } from "../../logic";--type ViewMode = "EDIT" | "VIEW";--const { t } = useI18n();-const { project } = useCurrentProjectV1();-const {- isCreating,- plan,- issue,- readonly,- allowEdit: hasPermission,-} = usePlanContext();--const state = reactive({- isEditing: false,- isUpdating: false,- title: "",-});--// Watch for changes in issue/plan to update the title-watch(- () => [plan.value, issue.value],- () => {- state.title = issue.value ? issue.value.title : plan.value.title;- },- { immediate: true }-);--const viewMode = computed((): ViewMode => {- if (isCreating.value) return "EDIT";- return state.isEditing ? "EDIT" : "VIEW";-});--const style = computed(() => {- const style: CSSProperties = {- cursor: "default",- "--n-color-disabled": "transparent",- "--n-font-size": "18px",- "font-weight": "bold",- };- const border =- viewMode.value === "EDIT"- ? "1px solid rgb(var(--color-control-border))"- : "none";- style["--n-border"] = border;- style["--n-border-disabled"] = border;-- return style;-});--const allowEdit = computed(() => {- if (readonly.value) {- return false;- }- if (isCreating.value) {- return true;- }- // Plans with rollout should have readonly title- if (!issue.value && plan.value.hasRollout) {- return false;- }-- // If issue exists, check issue permissions- if (issue.value) {- // Allowed if current user has related permission.- if (hasProjectPermissionV2(project.value, "bb.issues.update")) {- return true;- }- return false;- }-- return hasPermission.value;-});--const onBlur = async () => {- const cleanup = () => {- state.isEditing = false;- state.isUpdating = false;- };-- if (isCreating.value) {- cleanup();- return;- }-- // If issue exists, update issue title- if (issue.value) {- if (state.title === issue.value.title) {- cleanup();- return;- }- try {- state.isUpdating = true;- const issuePatch = create(IssueSchema, {- ...issue.value,- title: state.title,- });- const request = create(UpdateIssueRequestSchema, {- issue: issuePatch,- updateMask: { paths: ["title"] },- });- const response = await issueServiceClientConnect.updateIssue(request);- Object.assign(issue.value, response);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });- } catch (error) {- console.error("Failed to update issue title:", error);- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.error"),- description: String(error),- });- // Revert the title - use optional chaining in case issue becomes undefined- state.title = issue.value?.title || "";- } finally {- cleanup();- }- return;- }-- // Update plan title- if (state.title === plan.value.title) {- cleanup();- return;- }- try {- state.isUpdating = true;- const planPatch = create(PlanSchema, {- ...plan.value,- title: state.title,- });- const request = create(UpdatePlanRequestSchema, {- plan: planPatch,- updateMask: { paths: ["title"] },- });- const response = await planServiceClientConnect.updatePlan(request);- Object.assign(plan.value, response);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });- } catch (error) {- console.error("Failed to update plan title:", error);- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.error"),- description: String(error),- });- // Revert the title- state.title = plan.value.title;- } finally {- cleanup();- }-};--const onEnter = (e: KeyboardEvent) => {- if (e.isComposing) return;- const input = e.target as HTMLInputElement;- input.blur();-};--const onUpdateValue = (value: string) => {- if (!isCreating.value) {- return;- }- // When creating, update issue title if issue exists, plan title otherwise- if (issue.value) {- issue.value.title = value;- } else {- plan.value.title = value;- }-};-</script>--<style>-.bb-plan-title-input input {- cursor: text !important;- color: var(--n-text-color) !important;- text-decoration-color: var(--n-text-color) !important;-}-</style>diff --git a/frontend/src/components/Plan/components/HeaderSection/index.ts b/frontend/src/components/Plan/components/HeaderSection/index.tsdeleted file mode 100644index 3843a93df5..0000000000--- a/frontend/src/components/Plan/components/HeaderSection/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import HeaderSection from "./HeaderSection.vue";--export default HeaderSection;diff --git a/frontend/src/components/Plan/components/IssueReviewView/AccessGrantView.vue b/frontend/src/components/Plan/components/IssueReviewView/AccessGrantView.vuedeleted file mode 100644index 9036cbd0c0..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/AccessGrantView.vue+++ /dev/null@@ -1,9 +0,0 @@-<template>- <div class="w-full flex flex-col gap-y-4">- <AccessGrantDetailsSection />- </div>-</template>--<script lang="ts" setup>-import { AccessGrantDetailsSection } from "./AccessGrantView";-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/AccessGrantView/AccessGrantDetailsSection.vue b/frontend/src/components/Plan/components/IssueReviewView/AccessGrantView/AccessGrantDetailsSection.vuedeleted file mode 100644index fcffce4c74..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/AccessGrantView/AccessGrantDetailsSection.vue+++ /dev/null@@ -1,138 +0,0 @@-<template>- <div class="flex flex-col gap-y-4">- <h3 class="text-base font-medium">- {{ $t("issue.access-grant.details") }}- </h3>-- <div v-if="isLoading" class="flex items-center justify-center py-8">- <BBSpin />- </div>-- <div v-else-if="accessGrant" class="p-4 border rounded-sm flex flex-col gap-y-4">- <!-- Target Databases -->- <div v-if="accessGrant.targets.length > 0" class="flex flex-col gap-y-2">- <span class="text-sm text-control-light">- {{ $t("common.databases") }}- </span>- <div class="flex flex-wrap gap-2">- <div- v-for="target in accessGrant.targets"- :key="target"- class="inline-flex items-center gap-2 px-2 py-1.5 border rounded-sm min-w-0"- >- <DatabaseDisplay- :database="target"- :show-environment="true"- size="medium"- class="flex-1 min-w-0"- />- </div>- </div>- </div>-- <!-- Query -->- <div v-if="accessGrant.query" class="flex flex-col gap-y-2">- <span class="text-sm text-control-light">- {{ $t("common.statement") }}- </span>- <BBAttention- v-if="accessGrant.unmask"- :type="'warning'"- >- {{ $t("sql-editor.unmask-warning") }}- </BBAttention>- <div class="max-h-[30em] overflow-auto rounded-xs p-4 bg-gray-50">- <NConfigProvider :hljs="hljs">- <NCode language="sql" :code="accessGrant.query" />- </NConfigProvider>- </div>- <NCheckbox :checked="accessGrant.unmask" :disabled="true">- <span class="text-base">- {{ $t("sql-editor.access-type-unmask") }}- </span>- </NCheckbox>- </div>-- <!-- Expiration -->- <div class="flex flex-col gap-y-1">- <span class="text-sm text-control-light">- <template v-if="expirationInfo.type === 'duration'">- {{ $t("common.duration") }}- </template>- <template v-else>- {{ $t("issue.access-grant.expired-at") }}- </template>- </span>- <div class="text-base">- <template v-if="expirationInfo.type === 'datetime'">- {{ expirationInfo.value }}- </template>- <template v-else-if="expirationInfo.type === 'duration'">- {{ expirationInfo.value }}- </template>- <template v-else>- {{ $t("project.members.never-expires") }}- </template>- </div>- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import hljs from "highlight.js/lib/core";-import { NCheckbox, NCode, NConfigProvider } from "naive-ui";-import { computed, ref, watchEffect } from "vue";-import { BBAttention, BBSpin } from "@/bbkit";-import DatabaseDisplay from "@/components/Plan/components/common/DatabaseDisplay.vue";-import { useAccessGrantStore, useDatabaseV1Store } from "@/store";-import { isValidDatabaseName } from "@/types";-import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";-import { extractProjectResourceName, hasProjectPermissionV2 } from "@/utils";-import { getAccessGrantExpirationText } from "@/utils/accessGrant";-import { usePlanContextWithIssue } from "../../../logic";--const { issue, project } = usePlanContextWithIssue();-const dbStore = useDatabaseV1Store();-const accessGrantStore = useAccessGrantStore();--const isLoading = ref(true);-const accessGrant = ref<AccessGrant>();--const expirationInfo = computed(() => {- if (!accessGrant.value) return { type: "never" as const };- return getAccessGrantExpirationText(accessGrant.value);-});--watchEffect(async () => {- const name = issue.value.accessGrant;- if (!name) {- isLoading.value = false;- return;- }- try {- let grant: AccessGrant | undefined;- if (hasProjectPermissionV2(project.value, "bb.accessGrants.get")) {- grant = await accessGrantStore.getAccessGrant(name);- } else {- const parent = `projects/${extractProjectResourceName(issue.value.name)}`;- const response = await accessGrantStore.searchMyAccessGrants({- parent,- filter: { name },- });- grant = response.accessGrants[0];- }- accessGrant.value = grant;- // Pre-fetch databases for display- if (accessGrant.value) {- for (const target of accessGrant.value.targets) {- if (isValidDatabaseName(target)) {- dbStore.getOrFetchDatabaseByName(target);- }- }- }- } finally {- isLoading.value = false;- }-});-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/AccessGrantView/index.ts b/frontend/src/components/Plan/components/IssueReviewView/AccessGrantView/index.tsdeleted file mode 100644index 81d961574d..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/AccessGrantView/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import AccessGrantDetailsSection from "./AccessGrantDetailsSection.vue";--export { AccessGrantDetailsSection };diff --git a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/ActivitySection.vue b/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/ActivitySection.vuedeleted file mode 100644index b1513d3d78..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/ActivitySection.vue+++ /dev/null@@ -1,12 +0,0 @@-<template>- <div class="flex flex-col gap-y-4">- <h3 class="text-base font-medium">- {{ $t("common.activity") }}- </h3>- <IssueCommentList />- </div>-</template>--<script setup lang="ts">-import IssueCommentList from "./IssueCommentList.vue";-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentList.vue b/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentList.vuedeleted file mode 100644index cc6353a37b..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentList.vue+++ /dev/null@@ -1,141 +0,0 @@-<template>- <div class="flex flex-col">- <ul>- <IssueDescriptionComment :issue-comments="issueComments" />- <IssueCommentView- v-for="(item, index) in issueComments"- :key="item.name"- class="group"- :is-last="index === issueComments.length - 1"- :issue-comment="item"- >- <template v-if="allowEditComment(item)" #subject-suffix>- <NButton- v-if="!commentEdit.state.editMode"- quaternary- size="tiny"- class="text-gray-500 hover:text-gray-700"- @click.prevent="commentEdit.startEditComment(item)"- >- <PencilIcon class="w-3.5 h-3.5" />- </NButton>- </template>-- <template v-if="item.comment" #comment>- <EditableMarkdownContent- :content="item.comment"- :edit-content="commentEdit.state.editContent"- :project="project"- :is-editing="isEditingComment(item.name)"- :allow-save="commentEdit.allowUpdateComment.value"- @update:edit-content="commentEdit.state.editContent = $event"- @save="commentEdit.saveEditComment"- @cancel="commentEdit.cancelEditComment"- />- </template>- </IssueCommentView>- </ul>-- <div- v-if="!commentEdit.state.editMode && commentEdit.allowCreateComment.value"- class="mt-2"- >- <div class="flex gap-3">- <div class="shrink-0 pt-1">- <UserAvatar :user="commentEdit.currentUser.value" />- </div>- <div class="min-w-0 flex-1">- <h3 class="sr-only" id="issue-comment-editor"></h3>- <MarkdownEditor- mode="editor"- :content="commentEdit.state.newComment"- :project="project"- :maxlength="65536"- @change="(val: string) => (commentEdit.state.newComment = val)"- @submit="handleCreateComment"- />- <div class="mt-3 flex items-center justify-end">- <NButton- type="primary"- :disabled="commentEdit.state.newComment.length === 0"- @click.prevent="handleCreateComment"- >- {{ $t("common.comment") }}- </NButton>- </div>- </div>- </div>- </div>- </div>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { PencilIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { computed, onMounted, watch, watchEffect } from "vue";-import { useRoute } from "vue-router";-import MarkdownEditor from "@/components/MarkdownEditor";-import { usePlanContext } from "@/components/Plan/logic";-import UserAvatar from "@/components/User/UserAvatar.vue";-import { useCurrentProjectV1, useIssueCommentStore } from "@/store";-import { ListIssueCommentsRequestSchema } from "@/types/proto-es/v1/issue_service_pb";-import { IssueCommentView, useCommentEdit } from "./IssueCommentView";-import EditableMarkdownContent from "./IssueCommentView/EditableMarkdownContent.vue";-import IssueDescriptionComment from "./IssueCommentView/IssueDescriptionComment.vue";--const route = useRoute();-const { project } = useCurrentProjectV1();-const { events } = usePlanContext();-const issueCommentStore = useIssueCommentStore();--const commentEdit = useCommentEdit(project);-const { issueName, allowEditComment } = commentEdit;--const isEditingComment = (commentName: string): boolean => {- return (- commentEdit.state.editMode &&- commentEdit.state.activeComment?.name === commentName- );-};--const fetchIssueComments = async () => {- if (!issueName.value) return;- await issueCommentStore.listIssueComments(- create(ListIssueCommentsRequestSchema, {- parent: issueName.value,- pageSize: 1000,- })- );-};--watchEffect(fetchIssueComments);--// Refresh comments when a review or status action is performed-events.on("perform-issue-review-action", fetchIssueComments);-events.on("perform-issue-status-action", fetchIssueComments);--const issueComments = computed(() => {- if (!issueName.value) return [];- return issueCommentStore.getIssueComments(issueName.value);-});--const handleCreateComment = async () => {- await commentEdit.createComment(commentEdit.state.newComment);- await fetchIssueComments();-};--onMounted(() => {- watch(- () => route.hash,- (hash) => {- if (hash.match(/^#activity(\d+)/)) {- const elem =- document.querySelector(hash) || document.querySelector("#activity");- setTimeout(() => elem?.scrollIntoView());- }- },- { immediate: true }- );-});-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/ActionCreator.vue b/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/ActionCreator.vuedeleted file mode 100644index e05e741818..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/ActionCreator.vue+++ /dev/null@@ -1,24 +0,0 @@-<template>- <UserLink v-if="user" :title="user.title" :email="user.email" />- <span v-else class="font-medium text-error">{{ $t("common.unknown") }}</span>-</template>--<script lang="ts" setup>-import { computedAsync } from "@vueuse/core";-import { UserLink } from "@/components/v2/Model/cells";-import { useUserStore } from "@/store";--const props = defineProps<{- // Format: users/{email}- // Issue comments always have a real user creator- creator: string;-}>();--const userStore = useUserStore();--const user = computedAsync(() => {- return userStore.getOrFetchUserByIdentifier({- identifier: props.creator,- });-});-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/ActionIcon.vue b/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/ActionIcon.vuedeleted file mode 100644index 9702f6206e..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/ActionIcon.vue+++ /dev/null@@ -1,215 +0,0 @@-<template>- <div class="relative">- <div v-if="iconConfig.type === 'avatar'" class="relative pl-0.5">- <div- class="w-7 h-7 bg-white rounded-full ring-4 ring-white flex items-center justify-center"- >- <UserAvatar- :user="user"- override-class="w-7 h-7 font-medium"- override-text-size="0.8rem"- />- </div>- </div>- <div v-else class="relative" :class="iconConfig.wrapper">- <div- class="rounded-full ring-4 ring-white flex items-center justify-center"- :class="iconConfig.container"- >- <component :is="iconConfig.icon" :class="iconConfig.iconClass" />- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import { computedAsync } from "@vueuse/core";-import {- CheckCircle2Icon,- CircleAlertIcon,- CodeIcon,- MinusIcon,- PencilIcon,- PlayCircleIcon,- PlayIcon,- PlusIcon,- ThumbsUpIcon,-} from "lucide-vue-next";-import type { Component } from "vue";-import { computed } from "vue";-import { SkipIcon } from "@/components/Icon";-import UserAvatar from "@/components/User/UserAvatar.vue";-import { getIssueCommentType, IssueCommentType, useUserStore } from "@/store";-import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";-import { IssueComment_Approval_Status } from "@/types/proto-es/v1/issue_service_pb";--type ActionIconType =- | "avatar"- | "create"- | "update"- | "run"- | "approve-review"- | "reject-review"- | "re-request-review"- | "rollout"- | "cancel"- | "fail"- | "complete"- | "skip"- | "commit";--interface IconConfig {- type: "avatar" | "icon";- wrapper?: string;- container?: string;- icon?: Component;- iconClass?: string;-}--const ICON_CONFIGS: Record<- Exclude<ActionIconType, "avatar">,- Omit<IconConfig, "type">-> = {- create: {- wrapper: "pl-0.5",- container: "w-7 h-7 bg-control-bg",- icon: PlusIcon,- iconClass: "w-5 h-5 text-control",- },- update: {- wrapper: "pl-0.5",- container: "w-7 h-7 bg-control-bg",- icon: PencilIcon,- iconClass: "w-4 h-4 text-control",- },- run: {- wrapper: "pl-0.5",- container: "w-7 h-7 bg-control-bg",- icon: PlayCircleIcon,- iconClass: "w-5 h-5 text-control",- },- rollout: {- wrapper: "pl-0.5",- container: "w-7 h-7 bg-control-bg",- icon: PlayCircleIcon,- iconClass: "w-5 h-5 text-control",- },- "approve-review": {- wrapper: "pl-0.5",- container: "w-7 h-7 bg-success",- icon: ThumbsUpIcon,- iconClass: "w-4 h-4 text-white",- },- "reject-review": {- wrapper: "pl-0.5",- container: "w-7 h-7 bg-warning",- icon: PencilIcon,- iconClass: "w-4 h-4 text-white",- },- "re-request-review": {- wrapper: "pl-0.5",- container: "w-7 h-7 bg-control-bg icon-re-request-review",- icon: PlayIcon,- iconClass: "w-4 h-4 text-control ml-px",- },- cancel: {- wrapper: "pl-0.5",- container: "w-7 h-7 bg-control-bg",- icon: MinusIcon,- iconClass: "w-5 h-5 text-control",- },- fail: {- wrapper: "pl-0.5",- container: "w-7 h-7 bg-white",- icon: CircleAlertIcon,- iconClass: "w-5 h-5 text-error",- },- complete: {- wrapper: "pl-0.5",- container: "w-7 h-7 bg-white",- icon: CheckCircle2Icon,- iconClass: "w-6 h-6 text-success",- },- skip: {- wrapper: "pl-1",- container: "w-6 h-6 bg-gray-200",- icon: SkipIcon,- iconClass: "w-5 h-5 text-gray-500",- },- commit: {- wrapper: "pl-0.5",- container: "w-7 h-7 bg-control-bg",- icon: CodeIcon,- iconClass: "w-5 h-5 text-control",- },-};--const props = defineProps<{- issueComment: IssueComment;-}>();--const userStore = useUserStore();--const user = computedAsync(() => {- return userStore.getOrFetchUserByIdentifier({- identifier: props.issueComment.creator,- });-});--const iconType = computed((): ActionIconType => {- const { issueComment } = props;- const commentType = getIssueCommentType(issueComment);-- if (- commentType === IssueCommentType.APPROVAL &&- issueComment.event?.case === "approval"- ) {- const { status } = issueComment.event.value;- switch (status) {- case IssueComment_Approval_Status.APPROVED:- return "approve-review";- case IssueComment_Approval_Status.REJECTED:- return "reject-review";- case IssueComment_Approval_Status.PENDING:- return "re-request-review";- }- }-- if (- commentType === IssueCommentType.ISSUE_UPDATE &&- issueComment.event?.case === "issueUpdate"- ) {- const { toTitle, toDescription, toLabels, fromLabels } =- issueComment.event.value;- if (- toTitle !== undefined ||- toDescription !== undefined ||- toLabels.length !== 0 ||- fromLabels.length !== 0- ) {- return "update";- }- }-- if (commentType === IssueCommentType.PLAN_SPEC_UPDATE) {- return "update";- }-- // Issue comments always have a real user creator- return "avatar";-});--const iconConfig = computed((): IconConfig => {- const type = iconType.value;- if (type === "avatar") {- return { type };- }- return { type: "icon", ...ICON_CONFIGS[type] };-});-</script>--<style scoped>-.icon-re-request-review :deep(path) {- stroke-width: 3 !important;-}-</style>diff --git a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/ActionSentence.vue b/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/ActionSentence.vuedeleted file mode 100644index 0cd930748f..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/ActionSentence.vue+++ /dev/null@@ -1,120 +0,0 @@-<template>- <Renderer />-</template>--<script lang="tsx" setup>-import { defineComponent } from "vue";-import { Translation, useI18n } from "vue-i18n";-import { usePlanContext } from "@/components/Plan/logic";-import { SpecLink } from "@/components/v2";-import { getIssueCommentType, IssueCommentType } from "@/store";-import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";-import {- IssueComment_Approval_Status,- IssueStatus,-} from "@/types/proto-es/v1/issue_service_pb";-import {- extractPlanUID,- extractProjectResourceName,- getSpecDisplayInfo,-} from "@/utils";-import StatementUpdate from "./StatementUpdate.vue";--const props = defineProps<{- issueComment: IssueComment;-}>();--const { t } = useI18n();-const { plan } = usePlanContext();--const renderActionSentence = () => {- const { issueComment } = props;- const commentType = getIssueCommentType(issueComment);- if (- commentType === IssueCommentType.APPROVAL &&- issueComment.event?.case === "approval"- ) {- const { status } = issueComment.event.value;- let verb = "";- if (status === IssueComment_Approval_Status.APPROVED) {- verb = t("custom-approval.issue-review.approved-issue");- } else if (status === IssueComment_Approval_Status.REJECTED) {- verb = t("custom-approval.issue-review.rejected-issue");- } else if (status === IssueComment_Approval_Status.PENDING) {- verb = t("custom-approval.issue-review.re-requested-review");- }- if (verb) {- return verb;- }- } else if (- commentType === IssueCommentType.ISSUE_UPDATE &&- issueComment.event?.case === "issueUpdate"- ) {- const {- fromTitle,- toTitle,- fromDescription,- toDescription,- fromStatus,- toStatus,- fromLabels,- toLabels,- } = issueComment.event.value;- if (fromTitle !== undefined && toTitle !== undefined) {- return t("activity.sentence.changed-from-to", {- name: t("issue.issue-name").toLowerCase(),- oldValue: fromTitle,- newValue: toTitle,- });- } else if (fromDescription !== undefined && toDescription !== undefined) {- return t("activity.sentence.changed-description");- } else if (fromStatus !== undefined && toStatus !== undefined) {- if (toStatus === IssueStatus.DONE) {- return t("activity.sentence.resolved-issue");- } else if (toStatus === IssueStatus.CANCELED) {- return t("activity.sentence.canceled-issue");- } else if (toStatus === IssueStatus.OPEN) {- return t("activity.sentence.reopened-issue");- }- } else if (fromLabels.length !== 0 || toLabels.length !== 0) {- return t("activity.sentence.changed-labels");- }- } else if (- commentType === IssueCommentType.PLAN_SPEC_UPDATE &&- issueComment.event?.case === "planSpecUpdate"- ) {- const { spec, fromSheet, toSheet } = issueComment.event.value;- if (fromSheet !== undefined && toSheet !== undefined) {- const specs = plan.value.specs ?? [];- const specInfo = getSpecDisplayInfo(specs, spec);- const planName = plan.value.name;- const projectName = extractProjectResourceName(planName);- const planUID = extractPlanUID(planName);-- return (- <Translation keypath="dynamic.activity.sentence.modified-sql-of-spec-link">- {{- spec: () => (- <SpecLink- projectName={projectName}- planUID={planUID}- specId={specInfo?.specId ?? ""}- displayIndex={specInfo?.displayIndex ?? 0}- />- ),- link: () => (- <StatementUpdate oldSheet={fromSheet} newSheet={toSheet} />- ),- }}- </Translation>- );- }- }- return "";-};--const Renderer = defineComponent({- name: "ActionSentenceRenderer",- render: () => <span>{renderActionSentence()}</span>,-});-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/EditableMarkdownContent.vue b/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/EditableMarkdownContent.vuedeleted file mode 100644index a2389c9463..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/EditableMarkdownContent.vue+++ /dev/null@@ -1,65 +0,0 @@-<template>- <div>- <p v-if="!isEditing && !content">- <i class="text-gray-400 italic">{{ placeholder }}</i>- </p>- <MarkdownEditor- v-else- :mode="isEditing ? 'editor' : 'preview'"- :content="isEditing ? editContent : content"- :project="project"- :maxlength="maxlength"- :max-height="maxHeight"- @change="(val: string) => emit('update:editContent', val)"- @submit="emit('save')"- />- <div- v-if="isEditing"- class="flex gap-x-2 mt-2 items-center justify-end"- >- <NButton quaternary size="small" @click.prevent="emit('cancel')">- {{ $t("common.cancel") }}- </NButton>- <NButton- size="small"- :disabled="!allowSave"- :loading="isSaving"- @click.prevent="emit('save')"- >- {{ $t("common.save") }}- </NButton>- </div>- </div>-</template>--<script lang="ts" setup>-import { NButton } from "naive-ui";-import MarkdownEditor from "@/components/MarkdownEditor";-import type { Project } from "@/types/proto-es/v1/project_service_pb";--withDefaults(- defineProps<{- content: string;- editContent: string;- project: Project;- isEditing: boolean;- allowSave: boolean;- isSaving?: boolean;- placeholder?: string;- maxlength?: number;- maxHeight?: number;- }>(),- {- isSaving: false,- placeholder: "",- maxlength: 65536,- maxHeight: Number.MAX_SAFE_INTEGER,- }-);--const emit = defineEmits<{- (e: "update:editContent", value: string): void;- (e: "save"): void;- (e: "cancel"): void;-}>();-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/IssueCommentAction.vue b/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/IssueCommentAction.vuedeleted file mode 100644index 3893f3f24e..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/IssueCommentAction.vue+++ /dev/null@@ -1,65 +0,0 @@-<template>- <div class="min-w-0 flex-1">- <div- class="rounded-lg border overflow-hidden"- :class="- $slots.comment- ? 'ml-3 border-gray-200 bg-white'- : 'ml-1 border-transparent'- "- >- <div class="px-3 py-2" :class="$slots.comment ? 'bg-gray-50' : ''">- <div class="flex items-center justify-between">- <div class="flex items-center gap-x-2 text-sm min-w-0 flex-wrap">- <ActionCreator :creator="issueComment.creator" />-- <ActionSentence- :issue-comment="issueComment"- class="text-gray-600 wrap-break-word min-w-0"- />-- <HumanizeTs- :ts="- getTimeForPbTimestampProtoEs(issueComment.createTime, 0) / 1000- "- class="text-gray-500"- />-- <span- v-if="- getTimeForPbTimestampProtoEs(issueComment.createTime) !==- getTimeForPbTimestampProtoEs(issueComment.updateTime) &&- getIssueCommentType(issueComment) ===- IssueCommentType.USER_COMMENT- "- class="text-gray-500 text-xs"- >- ({{ $t("common.edited") }})- </span>- </div>-- <slot name="subject-suffix"></slot>- </div>- </div>- <div- v-if="$slots.comment"- class="px-4 py-3 border-t border-gray-200 text-sm text-gray-700 whitespace-pre-wrap wrap-break-word"- >- <slot name="comment" />- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import HumanizeTs from "@/components/misc/HumanizeTs.vue";-import { getIssueCommentType, IssueCommentType } from "@/store";-import { getTimeForPbTimestampProtoEs } from "@/types";-import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";-import ActionCreator from "./ActionCreator.vue";-import ActionSentence from "./ActionSentence.vue";--defineProps<{- issueComment: IssueComment;-}>();-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/IssueCommentView.vue b/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/IssueCommentView.vuedeleted file mode 100644index 002320b986..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/IssueCommentView.vue+++ /dev/null@@ -1,35 +0,0 @@-<template>- <li>- <div :id="issueComment.name" class="relative pb-4">- <span- v-if="!isLast"- class="absolute left-4 -ml-px h-full w-0.5 bg-gray-200"- aria-hidden="true"- ></span>- <div class="relative flex items-start">- <div class="pt-1.5">- <ActionIcon :issue-comment="issueComment" />- </div>-- <IssueCommentAction- :issue-comment="issueComment"- >- <template v-for="(_, name) in $slots" :key="name" #[name]>- <slot :name="name" />- </template>- </IssueCommentAction>- </div>- </div>- </li>-</template>--<script lang="ts" setup>-import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";-import ActionIcon from "./ActionIcon.vue";-import IssueCommentAction from "./IssueCommentAction.vue";--defineProps<{- isLast: boolean;- issueComment: IssueComment;-}>();-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/IssueDescriptionComment.vue b/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/IssueDescriptionComment.vuedeleted file mode 100644index 5cbbe07ac4..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/IssueDescriptionComment.vue+++ /dev/null@@ -1,165 +0,0 @@-<template>- <li>- <div class="relative pb-4">- <span- v-if="issueComments.length > 0"- class="absolute left-4 -ml-px h-full w-0.5 bg-block-border"- aria-hidden="true"- ></span>- <div class="relative flex items-start">- <div class="relative">- <div class="pt-1.5 bg-white"></div>- <UserAvatar override-class="w-7 h-7 font-medium" :user="creator" />- <div- class="absolute -bottom-1 -right-1 w-4 h-4 bg-control-bg rounded-full ring-2 ring-white flex items-center justify-center"- >- <PlusIcon class="w-4 h-4 text-control" />- </div>- </div>-- <div class="ml-3 min-w-0 flex-1">- <div class="rounded-lg border border-gray-200 bg-white overflow-hidden">- <div class="px-3 py-2 bg-gray-50">- <div class="flex items-center justify-between">- <div- class="flex items-center gap-x-2 text-sm min-w-0 flex-wrap"- >- <ActionCreator :creator="creatorName" />- <span class="text-gray-600 wrap-break-word min-w-0">{{- $t("activity.sentence.created-issue")- }}</span>- <HumanizeTs- :ts="getTimeForPbTimestampProtoEs(createTime, 0) / 1000"- class="text-gray-500"- />- </div>- <NButton- v-if="allowEdit && !state.isEditing"- quaternary- size="tiny"- @click.prevent="startEdit"- >- <PencilIcon class="w-3.5 h-3.5" />- </NButton>- </div>- </div>- <div- class="px-4 py-3 border-t border-gray-200 text-sm text-gray-700"- >- <EditableMarkdownContent- :content="description"- :edit-content="state.editContent"- :project="project"- :is-editing="state.isEditing"- :allow-save="allowSave"- :is-saving="state.isSaving"- :placeholder="$t('issue.no-description-provided')"- @update:edit-content="state.editContent = $event"- @save="saveEdit"- @cancel="cancelEdit"- />- </div>- </div>- </div>- </div>- </div>- </li>-</template>--<script lang="ts" setup>-import { create } from "@bufbuild/protobuf";-import type { Timestamp } from "@bufbuild/protobuf/wkt";-import { PencilIcon, PlusIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { computed, reactive } from "vue";-import HumanizeTs from "@/components/misc/HumanizeTs.vue";-import { usePlanContext } from "@/components/Plan/logic";-import UserAvatar from "@/components/User/UserAvatar.vue";-import { issueServiceClientConnect } from "@/connect";-import { useCurrentProjectV1, useUserStore } from "@/store";-import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";-import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";-import {- IssueSchema,- UpdateIssueRequestSchema,-} from "@/types/proto-es/v1/issue_service_pb";-import { hasProjectPermissionV2 } from "@/utils";-import ActionCreator from "./ActionCreator.vue";-import EditableMarkdownContent from "./EditableMarkdownContent.vue";--defineProps<{- issueComments: IssueComment[];-}>();--const { issue } = usePlanContext();-const userStore = useUserStore();-const { project } = useCurrentProjectV1();--const state = reactive({- isEditing: false,- editContent: "",- isSaving: false,-});--const creatorName = computed(() => {- return issue.value?.creator || "";-});--const createTime = computed((): Timestamp | undefined => {- return issue.value?.createTime;-});--const creator = computed(() => {- return (- userStore.getUserByIdentifier(creatorName.value) ??- unknownUser(creatorName.value)- );-});--const description = computed(() => {- return issue.value?.description || "";-});--const allowEdit = computed(() => {- return hasProjectPermissionV2(project.value, "bb.issues.update");-});--const allowSave = computed(() => {- return state.editContent !== description.value;-});--const startEdit = () => {- state.editContent = description.value;- state.isEditing = true;-};--const cancelEdit = () => {- state.isEditing = false;- state.editContent = "";-};--const saveEdit = async () => {- if (!allowSave.value || !issue.value) return;-- try {- state.isSaving = true;-- const issuePatch = create(IssueSchema, {- name: issue.value.name,- description: state.editContent,- });- const request = create(UpdateIssueRequestSchema, {- issue: issuePatch,- updateMask: { paths: ["description"] },- });- const response = await issueServiceClientConnect.updateIssue(request);- Object.assign(issue.value, response);-- cancelEdit();- } catch (error) {- console.error("Failed to update description:", error);- } finally {- state.isSaving = false;- }-};-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/StageName.vue b/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/StageName.vuedeleted file mode 100644index 307fac4607..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/StageName.vue+++ /dev/null@@ -1,30 +0,0 @@-<template>- <router-link- :to="link"- exact-active-class=""- class="font-medium text-main hover:border-b hover:border-b-main"- >- <EnvironmentV1Name- :link="false"- :environment="environmentStore.getEnvironmentByName(stage.environment)"- />- </router-link>-</template>--<script lang="ts" setup>-import { computed } from "vue";-import { EnvironmentV1Name } from "@/components/v2";-import { buildStageRoute } from "@/router/dashboard/projectV1RouteHelpers";-import { useEnvironmentV1Store } from "@/store";-import type { Stage } from "@/types/proto-es/v1/rollout_service_pb";--const props = defineProps<{- stage: Stage;-}>();--const environmentStore = useEnvironmentV1Store();--const link = computed(() => {- return buildStageRoute(props.stage.name);-});-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/StatementUpdate.vue b/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/StatementUpdate.vuedeleted file mode 100644index 080d36372c..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/StatementUpdate.vue+++ /dev/null@@ -1,85 +0,0 @@-<template>- <NButton text type="primary" v-bind="$attrs" @click="showPanel = true">- {{ $t("common.view-details") }}- </NButton>-- <BBModal- v-if="showPanel"- :title="$t('common.detail')"- header-class="border-0!"- container-class="pt-0!"- @close="showPanel = false"- >- <div- style="width: calc(100vw - 9rem); height: calc(100vh - 10rem)"- class="relative"- >- <DiffEditor- v-if="!isPreparingOldStatement && !isPreparingNewStatement"- class="w-full h-full border rounded-md overflow-clip"- :original="oldStatement"- :modified="newStatement"- :readonly="true"- />- <div- v-else- class="absolute inset-0 flex flex-col items-center justify-center"- >- <BBSpin />- </div>- </div>- </BBModal>-</template>--<script setup lang="ts">-import { asyncComputed } from "@vueuse/core";-import { NButton } from "naive-ui";-import { ref } from "vue";-import { BBModal, BBSpin } from "@/bbkit";-import { DiffEditor } from "@/components/MonacoEditor";-import { useSheetV1Store } from "@/store";-import { UNKNOWN_ID } from "@/types";-import { extractSheetUID, getSheetStatement } from "@/utils";--const props = defineProps<{- // Format: projects/{project}/sheets/{sheet}- oldSheet: string;- // Format: projects/{project}/sheets/{sheet}- newSheet: string;-}>();--const showPanel = ref(false);--const prepareStatement = async (sheetName: string) => {- if (extractSheetUID(sheetName) === String(UNKNOWN_ID)) return "";- // Use any (basic or full) view of sheets here to save data size- const sheet = await useSheetV1Store().getOrFetchSheetByName(sheetName);- if (!sheet) return "";- return getSheetStatement(sheet);-};--const isPreparingOldStatement = ref(false);-const isPreparingNewStatement = ref(false);--const oldStatement = asyncComputed(- () => {- return prepareStatement(props.oldSheet);- },- "",- {- evaluating: isPreparingOldStatement,- lazy: true,- }-);--const newStatement = asyncComputed(- () => {- return prepareStatement(props.newSheet);- },- "",- {- evaluating: isPreparingNewStatement,- lazy: true,- }-);-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/TaskName.vue b/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/TaskName.vuedeleted file mode 100644index 72f16a5584..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/TaskName.vue+++ /dev/null@@ -1,44 +0,0 @@-<template>- <router-link- :to="task.name"- exact-active-class=""- class="font-medium text-main hover:border-b hover:border-b-main"- >- <span>{{ databaseName }}</span>- <span class="ml-1 text-control-placeholder">#{{ taskUID }}</span>- </router-link>-</template>--<script lang="ts" setup>-import { computed } from "vue";-import { useProjectV1Store } from "@/store";-import { projectNamePrefix } from "@/store/modules/v1/common";-import type { Plan } from "@/types/proto-es/v1/plan_service_pb";-import type { Task } from "@/types/proto-es/v1/rollout_service_pb";-import {- databaseForTask,- extractDatabaseResourceName,- extractProjectResourceName,- extractTaskUID,-} from "@/utils";--const props = defineProps<{- plan: Plan;- task: Task;-}>();--const project = computed(() => {- return useProjectV1Store().getProjectByName(- `${projectNamePrefix}${extractProjectResourceName(props.plan.name)}`- );-});--const databaseName = computed(() => {- const db = databaseForTask(project.value, props.task);- return extractDatabaseResourceName(db.name).databaseName;-});--const taskUID = computed(() => {- return extractTaskUID(props.task.name);-});-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/index.ts b/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/index.tsdeleted file mode 100644index 29bc214b37..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/index.ts+++ /dev/null@@ -1,4 +0,0 @@-import IssueCommentView from "./IssueCommentView.vue";--export * from "./useCommentEdit";-export { IssueCommentView };diff --git a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/useCommentEdit.ts b/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/useCommentEdit.tsdeleted file mode 100644index 7871be8589..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/IssueCommentView/useCommentEdit.ts+++ /dev/null@@ -1,106 +0,0 @@-import type { ComputedRef, Ref } from "vue";-import { computed, reactive } from "vue";-import { usePlanContext } from "@/components/Plan/logic";-import {- extractUserEmail,- getIssueCommentType,- IssueCommentType,- useCurrentUserV1,- useIssueCommentStore,-} from "@/store";-import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";-import type { Project } from "@/types/proto-es/v1/project_service_pb";-import { hasProjectPermissionV2 } from "@/utils";--interface CommentEditState {- editMode: boolean;- activeComment?: IssueComment;- editContent: string;- newComment: string;-}--export function useCommentEdit(project: Ref<Project> | ComputedRef<Project>) {- const { plan, issue } = usePlanContext();- const currentUser = useCurrentUserV1();- const issueCommentStore = useIssueCommentStore();-- const issueName = computed(() => issue.value?.name || plan.value.issue);-- const state = reactive<CommentEditState>({- editMode: false,- editContent: "",- newComment: "",- });-- const allowCreateComment = computed(() => {- return hasProjectPermissionV2(project.value, "bb.issueComments.create");- });-- const allowEditComment = (comment: IssueComment): boolean => {- const commentType = getIssueCommentType(comment);- // Check if comment is user-editable- const isEditable =- commentType === IssueCommentType.USER_COMMENT ||- (commentType === IssueCommentType.APPROVAL && comment.comment !== "");-- if (!isEditable) {- return false;- }- if (currentUser.value.email === extractUserEmail(comment.creator)) {- return true;- }- return hasProjectPermissionV2(project.value, "bb.issueComments.update");- };-- const allowUpdateComment = computed(() => {- return (- !!state.editContent && state.editContent !== state.activeComment?.comment- );- });-- const startEditComment = (comment: IssueComment) => {- state.activeComment = comment;- state.editMode = true;- state.editContent = comment.comment;- };-- const cancelEditComment = () => {- state.activeComment = undefined;- state.editMode = false;- state.editContent = "";- };-- const saveEditComment = async () => {- if (!state.activeComment || !state.editContent) {- return;- }-- await issueCommentStore.updateIssueComment({- issueCommentName: state.activeComment.name,- comment: state.editContent,- });- cancelEditComment();- };-- const createComment = async (comment: string) => {- if (!issueName.value) return;- await issueCommentStore.createIssueComment({- issueName: issueName.value,- comment,- });- state.newComment = "";- };-- return {- state,- issueName,- currentUser,- allowCreateComment,- allowEditComment,- allowUpdateComment,- startEditComment,- cancelEditComment,- saveEditComment,- createComment,- };-}diff --git a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/index.ts b/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/index.tsdeleted file mode 100644index 5627692a1e..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/ActivitySection/index.ts+++ /dev/null@@ -1 +0,0 @@-export { default as ActivitySection } from "./ActivitySection.vue";diff --git a/frontend/src/components/Plan/components/IssueReviewView/DatabaseChangeView/DatabaseChangeView.vue b/frontend/src/components/Plan/components/IssueReviewView/DatabaseChangeView/DatabaseChangeView.vuedeleted file mode 100644index f0b7b31928..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/DatabaseChangeView/DatabaseChangeView.vue+++ /dev/null@@ -1,58 +0,0 @@-<template>- <div class="w-full flex flex-col">- <!-- Spec Tabs with content (read-only on Issue page) -->- <SpecTabs v-model:selected-spec-id="selectedSpecId">- <div v-if="selectedSpec" class="flex flex-col gap-2">- <TargetListSection />- <StatementSection header-variant="section" />- <OptionsSection />- </div>- </SpecTabs>-- </div>-</template>--<script setup lang="ts">-import { computed, provide, ref, watch } from "vue";-import { usePlanContext } from "../../../logic";-import {- FORCE_READONLY_KEY,- provideSelectedSpec,-} from "../../SpecDetailView/context";-import TargetListSection from "../../SpecDetailView/TargetListSection.vue";-import StatementSection from "../../StatementSection/StatementSection.vue";-import OptionsSection from "./OptionsSection.vue";-import SpecTabs from "./SpecTabs.vue";--const { plan } = usePlanContext();--// Issue page shows changes read-only — editing happens on Plan Detail Page-provide(FORCE_READONLY_KEY, true);--// Local state for selected spec (not route-based)-const selectedSpecId = ref<string>(plan.value.specs[0]?.id ?? "");--const selectedSpec = computed(() => {- return plan.value.specs.find((spec) => spec.id === selectedSpecId.value);-});--provideSelectedSpec(- computed(() => {- const spec = selectedSpec.value;- if (!spec) {- throw new Error("No spec selected");- }- return spec;- })-);--watch(- () => plan.value.specs,- (specs) => {- if (specs.length > 0 && !specs.find((s) => s.id === selectedSpecId.value)) {- selectedSpecId.value = specs[0].id;- }- },- { immediate: true }-);-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/DatabaseChangeView/OptionsSection.vue b/frontend/src/components/Plan/components/IssueReviewView/DatabaseChangeView/OptionsSection.vuedeleted file mode 100644index 1bd48a9793..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/DatabaseChangeView/OptionsSection.vue+++ /dev/null@@ -1,117 +0,0 @@-<template>- <div v-if="shouldShow" class="flex flex-col gap-1">- <span class="text-base">{{ $t("plan.options.self") }}</span>- <div class="flex flex-wrap items-center gap-x-4 sm:gap-x-6 gap-y-1">- <div v-if="shouldShowInstanceRoleSection" class="flex items-center gap-1">- <span class="text-sm text-control-light">{{ $t("common.role.self") }}</span>- <InstanceRoleSelect />- </div>- <div v-if="shouldShowTransactionModeSection" class="flex items-center gap-1">- <span class="text-sm text-control-light">{{- $t("issue.transaction-mode.label")- }}</span>- <TransactionModeSwitch />- </div>- <div v-if="shouldShowIsolationLevelSection" class="flex items-center gap-1">- <span class="text-sm text-control-light">{{- $t("plan.isolation-level.self")- }}</span>- <IsolationLevelSelect />- </div>- <div v-if="shouldShowPreBackupSection" class="flex items-center gap-1">- <span class="text-sm text-control-light">{{ $t("task.prior-backup") }}</span>- <PreBackupSwitch />- </div>- <div v-if="shouldShowGhostSection" class="flex items-center gap-1">- <span class="text-sm text-control-light">{{- $t("task.online-migration.self")- }}</span>- <GhostSwitch />- </div>- </div>- </div>-</template>--<script setup lang="ts">-import { computed } from "vue";-import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";-import { usePlanContext } from "../../../logic";-import { provideGhostSettingContext } from "../../Configuration/GhostSection/context";-import GhostSwitch from "../../Configuration/GhostSection/GhostSwitch.vue";-import { provideInstanceRoleSettingContext } from "../../Configuration/InstanceRoleSection/context";-import InstanceRoleSelect from "../../Configuration/InstanceRoleSection/InstanceRoleSelect.vue";-import { provideIsolationLevelSettingContext } from "../../Configuration/IsolationLevelSection/context";-import IsolationLevelSelect from "../../Configuration/IsolationLevelSection/IsolationLevelSelect.vue";-import { providePreBackupSettingContext } from "../../Configuration/PreBackupSection/context";-import PreBackupSwitch from "../../Configuration/PreBackupSection/PreBackupSwitch.vue";-import { provideTransactionModeSettingContext } from "../../Configuration/TransactionModeSection/context";-import TransactionModeSwitch from "../../Configuration/TransactionModeSection/TransactionModeSwitch.vue";-import {- useForceReadonly,- useSelectedSpec,-} from "../../SpecDetailView/context";--const { isCreating, plan, events, issue, readonly, allowEdit, project } =- usePlanContext();-const { selectedSpec } = useSelectedSpec();--const forceReadonly = useForceReadonly();--const allowChange = computed(() => {- if (forceReadonly || readonly?.value) {- return false;- }-- // Allow changes when creating- if (isCreating.value) {- return true;- }-- // Disallow changes if the plan has started rollout.- if (plan.value.hasRollout) {- return false;- }-- // If issue is not open, disallow- if (issue?.value && issue.value.status !== IssueStatus.OPEN) {- return false;- }-- return allowEdit.value;-});--const providerArgs = {- project,- plan,- selectedSpec,- isCreating,- issue,- allowChange,-};--const { shouldShow: shouldShowTransactionModeSection, events: txEvents } =- provideTransactionModeSettingContext(providerArgs);-const { shouldShow: shouldShowInstanceRoleSection, events: roleEvents } =- provideInstanceRoleSettingContext(providerArgs);-const { shouldShow: shouldShowIsolationLevelSection, events: isoEvents } =- provideIsolationLevelSettingContext(providerArgs);-const { shouldShow: shouldShowGhostSection, events: ghostEvents } =- provideGhostSettingContext(providerArgs);-const { shouldShow: shouldShowPreBackupSection, events: backupEvents } =- providePreBackupSettingContext(providerArgs);--const shouldShow = computed(- () =>- shouldShowTransactionModeSection.value ||- shouldShowIsolationLevelSection.value ||- shouldShowInstanceRoleSection.value ||- shouldShowGhostSection.value ||- shouldShowPreBackupSection.value-);--// Forward all setting updates to plan context-const emitStatusChanged = () => events.emit("status-changed", { eager: true });-[txEvents, roleEvents, isoEvents, ghostEvents, backupEvents].forEach((e) =>- e.on("update", emitStatusChanged)-);-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/DatabaseChangeView/SpecTabs.vue b/frontend/src/components/Plan/components/IssueReviewView/DatabaseChangeView/SpecTabs.vuedeleted file mode 100644index ba65ff1306..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/DatabaseChangeView/SpecTabs.vue+++ /dev/null@@ -1,237 +0,0 @@-<template>- <div>- <!-- Tab Bar -->- <div class="flex items-center justify-between border-b border-control-border">- <div class="flex items-center">- <button- v-for="(spec, index) in specs"- :key="spec.id"- class="flex items-center gap-1 px-3 py-1.5 -mb-px text-sm border rounded-t-md cursor-pointer transition-colors"- :class="- selectedSpecId === spec.id- ? 'font-medium text-main bg-white border-control-border border-b-white'- : 'text-control-light bg-transparent border-transparent hover:text-control'- "- @click="$emit('update:selectedSpecId', spec.id)"- >- <span class="opacity-60">#{{ index + 1 }}</span>- <span>{{ getSpecTitle(spec) }}</span>- <NTooltip v-if="isSpecEmpty(spec)">- <template #trigger>- <span class="text-error">*</span>- </template>- {{ $t("plan.navigator.statement-empty") }}- </NTooltip>- <NDropdown- v-if="canModifySpecs && specs.length > 1"- :options="getDropdownOptions()"- trigger="click"- placement="bottom-end"- size="small"- @select="(key) => handleDropdownSelect(key, spec)"- >- <NButton @click.stop text size="tiny">- <template #icon>- <MoreVerticalIcon :size="14" class="text-control-light" />- </template>- </NButton>- </NDropdown>- </button>- </div>-- <RouterLink- v-if="forceReadonly"- :to="planRoute"- class="text-sm text-accent hover:underline px-3"- >- {{ $t("plan.go-to-plan-page") }} →- </RouterLink>- <NButton- v-else-if="canModifySpecs"- type="default"- size="small"- @click="showAddSpecDrawer = true"- >- {{ $t("plan.add-spec") }}- </NButton>- </div>-- <!-- Content Area -->- <div class="bg-white border-x border-b border-control-border rounded-b-lg py-2 px-3">- <slot />- </div>- </div>-- <AddSpecDrawer v-model:show="showAddSpecDrawer" @created="handleSpecCreated" />-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { MoreVerticalIcon, TrashIcon } from "lucide-vue-next";-import type { DropdownOption } from "naive-ui";-import { NButton, NDropdown, NTooltip, useDialog } from "naive-ui";-import { computed, h, ref } from "vue";-import { useI18n } from "vue-i18n";-import { RouterLink } from "vue-router";-import { planServiceClientConnect } from "@/connect";-import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS } from "@/router/dashboard/projectV1";-import { buildPlanDeployRouteFromPlanName } from "@/router/dashboard/projectV1RouteHelpers";-import {- pushNotification,- useCurrentProjectV1,- useSheetV1Store,-} from "@/store";-import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";-import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";-import { UpdatePlanRequestSchema } from "@/types/proto-es/v1/plan_service_pb";-import {- extractPlanUID,- extractProjectResourceName,- extractSheetUID,-} from "@/utils";-import { getLocalSheetByName, usePlanContext } from "../../../logic";-import { getSpecTitle } from "../../../logic/utils";-import AddSpecDrawer from "../../AddSpecDrawer.vue";-import { useSpecsValidation } from "../../common";-import { useForceReadonly } from "../../SpecDetailView/context";--const props = defineProps<{ selectedSpecId: string }>();-const emit = defineEmits<{ "update:selectedSpecId": [specId: string] }>();--const dialog = useDialog();-const { t } = useI18n();-const { plan, issue, isCreating } = usePlanContext();-const sheetStore = useSheetV1Store();-const { project } = useCurrentProjectV1();--const forceReadonly = useForceReadonly();-const planRoute = computed(() => {- if (plan.value.hasRollout) {- return buildPlanDeployRouteFromPlanName(plan.value.name);- }-- return {- name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,- params: {- projectId: extractProjectResourceName(project.value.name),- planId: extractPlanUID(plan.value.name),- },- };-});-const specs = computed(() => plan.value.specs);-const { isSpecEmpty } = useSpecsValidation(specs);-const showAddSpecDrawer = ref(false);-const canModifySpecs = computed(- () =>- !forceReadonly &&- (isCreating.value || !plan.value.hasRollout) &&- issue.value?.status !== IssueStatus.CANCELED &&- issue.value?.status !== IssueStatus.DONE-);--const getDropdownOptions = (): DropdownOption[] =>- specs.value.length > 1- ? [- {- key: "delete",- label: t("common.delete"),- icon: () => h(TrashIcon, { size: 16 }),- },- ]- : [];--const handleDropdownSelect = (key: string, spec: Plan_Spec) => {- if (key === "delete") handleDeleteSpec(spec);-};--// Helper to update plan on server with optimistic update rollback on failure-const updatePlanSpecs = async (onError: () => void) => {- const request = create(UpdatePlanRequestSchema, {- plan: plan.value,- updateMask: { paths: ["specs"] },- });- try {- const response = await planServiceClientConnect.updatePlan(request);- Object.assign(plan.value, response);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });- return true;- } catch (error) {- onError();- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.error"),- description: String(error),- });- return false;- }-};--const handleSpecCreated = async (spec: Plan_Spec) => {- // For existing plans, create sheet on server first if needed- if (!isCreating.value) {- const config = spec.config;- if (- config.case === "changeDatabaseConfig" ||- config.case === "exportDataConfig"- ) {- const uid = extractSheetUID(config.value.sheet);- if (uid.startsWith("-")) {- const createdSheet = await sheetStore.createSheet(- project.value.name,- getLocalSheetByName(config.value.sheet)- );- config.value.sheet = createdSheet.name;- }- }- plan.value.specs.push(spec);- const success = await updatePlanSpecs(() => {- const idx = plan.value.specs.findIndex((s) => s.id === spec.id);- if (idx >= 0) plan.value.specs.splice(idx, 1);- });- if (!success) return;- } else {- plan.value.specs.push(spec);- }- emit("update:selectedSpecId", spec.id);-};--const handleDeleteSpec = (spec: Plan_Spec) => {- dialog.warning({- title: t("plan.spec.delete-change.title"),- content: t("plan.spec.delete-change.content"),- positiveText: t("common.delete"),- negativeText: t("common.cancel"),- onPositiveClick: async () => {- if (specs.value.length <= 1) {- pushNotification({- module: "bytebase",- style: "WARN",- title: "Cannot delete last spec",- });- return;- }-- const specIndex = plan.value.specs.findIndex((s) => s.id === spec.id);- if (specIndex < 0) return;-- const removedSpec = plan.value.specs.splice(specIndex, 1)[0];-- if (!isCreating.value) {- const success = await updatePlanSpecs(() => {- plan.value.specs.splice(specIndex, 0, removedSpec);- });- if (!success) return;- }-- if (props.selectedSpecId === spec.id && specs.value.length > 0) {- emit("update:selectedSpecId", specs.value[0].id);- }- },- });-};-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/DatabaseChangeView/index.ts b/frontend/src/components/Plan/components/IssueReviewView/DatabaseChangeView/index.tsdeleted file mode 100644index 3b08af7bb5..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/DatabaseChangeView/index.ts+++ /dev/null@@ -1 +0,0 @@-export { default as DatabaseChangeView } from "./DatabaseChangeView.vue";diff --git a/frontend/src/components/Plan/components/IssueReviewView/DatabaseCreateView.vue b/frontend/src/components/Plan/components/IssueReviewView/DatabaseCreateView.vuedeleted file mode 100644index bbbe0dad2e..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/DatabaseCreateView.vue+++ /dev/null@@ -1,197 +0,0 @@-<template>- <div class="w-full flex flex-col gap-y-4">- <!-- Database Information Section -->- <div class="flex flex-col gap-y-2">- <h3 class="text-base font-medium">- {{ $t("common.overview") }}- </h3>- <div class="flex items-center gap-x-5 gap-y-2 flex-wrap">- <!-- Environment -->- <div class="flex items-center gap-2">- <span class="text-sm font-medium text-gray-600"- >{{ $t("common.environment") }}:</span- >- <EnvironmentV1Name :environment="environment" />- </div>-- <!-- Instance -->- <div class="flex items-center gap-2">- <span class="text-sm font-medium text-gray-600"- >{{ $t("common.instance") }}:</span- >- <InstanceV1Name- v-if="isValidInstanceName(instance.name)"- :instance="instance"- />- <span v-else class="text-gray-900">{{ displayInstanceName }}</span>- </div>-- <!-- Database Name -->- <div class="flex items-center gap-2">- <span class="text-sm font-medium text-gray-600"- >{{ $t("common.database") }}:</span- >- <template v-if="isTaskDone && createdDatabase">- <router-link- :to="databaseV1Url(createdDatabase)"- class="normal-link"- >- {{ extractDatabaseResourceName(createdDatabase.name).databaseName }}- </router-link>- <span class="text-sm text-gray-500"- >({{ $t("common.created") }})</span- >- </template>- <span v-else class="text-gray-900">- {{ databaseName }}- </span>- </div>-- <!-- Task Status (only when rollout exists) -->- <div v-if="createDatabaseTask" class="flex items-center gap-2">- <span class="text-sm font-medium text-gray-600"- >{{ $t("common.status") }}:</span- >- <TaskStatus :status="createDatabaseTask.status" size="small" />- </div>- </div>-- <!-- Task Run Table (only when rollout exists and has task runs) -->- <div- v-if="rollout && createDatabaseTask && taskRunsForCreateDatabase.length > 0"- class="mt-4"- >- <TaskRunTable- :task="createDatabaseTask"- :task-runs="taskRunsForCreateDatabase"- />- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import { computed, watchEffect } from "vue";-import TaskStatus from "@/components/RolloutV1/components/Task/TaskStatus.vue";-import TaskRunTable from "@/components/RolloutV1/components/TaskRun/TaskRunTable.vue";-import { EnvironmentV1Name, InstanceV1Name } from "@/components/v2";-import {- useCurrentProjectV1,- useEnvironmentV1Store,- useInstanceV1Store,- useSheetV1Store,-} from "@/store";-import type { Plan_CreateDatabaseConfig } from "@/types/proto-es/v1/plan_service_pb";-import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";-import { isValidInstanceName } from "@/types/v1/instance";-import {- databaseV1Url,- extractCoreDatabaseInfoFromDatabaseCreateTask,- extractDatabaseResourceName,-} from "@/utils";-import { extractInstanceResourceName } from "@/utils/v1/instance";-import { usePlanContext } from "../..";--const { plan, rollout, taskRuns } = usePlanContext();-const { project } = useCurrentProjectV1();-const environmentStore = useEnvironmentV1Store();-const instanceStore = useInstanceV1Store();-const sheetStore = useSheetV1Store();--// Get the first (and typically only) create database spec-const createDatabaseSpec = computed(() => {- return plan.value.specs.find(- (spec) => spec.config?.case === "createDatabaseConfig"- );-});--const createDatabaseConfig = computed(() => {- return createDatabaseSpec.value?.config?.value as Plan_CreateDatabaseConfig;-});--// Extract database information-const environment = computed(() => {- return environmentStore.getEnvironmentByName(- createDatabaseConfig.value.environment- );-});--const instance = computed(() => {- return instanceStore.getInstanceByName(createDatabaseConfig.value.target);-});--// The instance resource name from the target, in case the instance is not found or no permission to view.-const displayInstanceName = computed(() => {- return extractInstanceResourceName(createDatabaseConfig.value.target);-});--const databaseName = computed(() => {- return createDatabaseConfig.value.database || "";-});--// Find the task related to this create database spec (only exists after rollout is created)-const createDatabaseTask = computed(() => {- if (!rollout.value || !createDatabaseSpec.value) return null;-- // Find the task that matches this spec- for (const stage of rollout.value.stages) {- for (const task of stage.tasks) {- if (task.specId === createDatabaseSpec.value.id) {- return task;- }- }- }- return null;-});--// Get the sheet name from the task payload (when rollout exists)-const sheetName = computed(() => {- if (!createDatabaseTask.value) return null;-- if (createDatabaseTask.value.payload.case === "databaseCreate") {- return createDatabaseTask.value.payload.value.sheet;- }- return null;-});--// Fetch the sheet when sheetName changes-watchEffect(() => {- if (sheetName.value) {- sheetStore.getOrFetchSheetByName(sheetName.value);- }-});--// Fetch the instance when target changes-watchEffect(() => {- const target = createDatabaseConfig.value?.target;- if (target) {- instanceStore.getOrFetchInstanceByName(target);- }-});--// Get task runs for this specific create database task-const taskRunsForCreateDatabase = computed(() => {- if (!rollout.value || !createDatabaseTask.value) return [];-- const taskName = createDatabaseTask.value.name;- return taskRuns.value.filter((taskRun) =>- taskRun.name.startsWith(taskName + "/")- );-});--// Check if the task is completed-const isTaskDone = computed(() => {- return createDatabaseTask.value?.status === Task_Status.DONE;-});--// Get the created database info for completed tasks-const createdDatabase = computed(() => {- if (!isTaskDone.value || !createDatabaseTask.value) return null;-- return extractCoreDatabaseInfoFromDatabaseCreateTask(- project.value,- createDatabaseTask.value,- plan.value- );-});-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView.vue b/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView.vuedeleted file mode 100644index acb7189d85..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView.vue+++ /dev/null@@ -1,29 +0,0 @@-<template>- <div class="w-full flex flex-col gap-y-4">- <!-- Targets Section (before rollout) or Tasks Section (after rollout) -->- <TasksSection v-if="rollout" />- <TargetsSection v-else />-- <!-- Execution History Section (only show when rollout exists and has task runs) -->- <ExecutionHistorySection v-if="rollout && taskRuns.length > 0" />-- <LimitsSection />- <OptionsSection />-- <StatementSection header-variant="section" />- </div>-</template>--<script lang="ts" setup>-import { usePlanContext } from "../../logic";-import StatementSection from "../StatementSection";-import {- ExecutionHistorySection,- LimitsSection,- OptionsSection,- TargetsSection,- TasksSection,-} from "./DatabaseExportView";--const { rollout, taskRuns } = usePlanContext();-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/ExecutionHistorySection.vue b/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/ExecutionHistorySection.vuedeleted file mode 100644index c31e172991..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/ExecutionHistorySection.vue+++ /dev/null@@ -1,92 +0,0 @@-<template>- <div class="flex flex-col gap-y-4">- <!-- Execution History Section -->- <div class="flex flex-col gap-y-3">- <div class="flex items-center justify-between">- <h3 class="text-base font-medium">- {{ $t("task-run.history") }}- </h3>- </div>-- <!-- Task Runs Table -->- <div v-if="allTaskRuns.length > 0">- <TaskRunTable- :task-runs="visibleTaskRuns"- :show-database-column="true"- :virtual-scroll="expanded && allTaskRuns.length > VIRTUAL_SCROLL_THRESHOLD"- :max-height="expanded && allTaskRuns.length > VIRTUAL_SCROLL_THRESHOLD ? '80vh' : undefined"- />- <div v-if="hasMore" class="flex justify-center mt-2">- <NButton quaternary size="small" @click="expanded = !expanded">- <template v-if="expanded">- {{ $t("common.collapse") }}- </template>- <template v-else>- {{ $t("common.show-more") }}- ({{ remainingCount }} {{ $t("common.remaining") }})- </template>- </NButton>- </div>- </div>-- <!-- No task runs message -->- <div v-else class="text-center text-control-light py-8">- {{ $t("common.no-data") }}- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import { NButton } from "naive-ui";-import { computed } from "vue";-import TaskRunTable from "@/components/RolloutV1/components/TaskRun/TaskRunTable.vue";-import type { TaskRun } from "@/types/proto-es/v1/rollout_service_pb";-import { extractTaskUID } from "@/utils";-import { usePlanContext } from "../../../logic";-import { useExpandableList, VIRTUAL_SCROLL_THRESHOLD } from ".";--const { plan, rollout, taskRuns } = usePlanContext();--// Get the export data spec-const exportDataSpec = computed(() => {- return plan.value.specs.find(- (spec) => spec.config?.case === "exportDataConfig"- );-});--// Find export tasks related to this spec-const exportTasks = computed(() => {- if (!rollout.value || !exportDataSpec.value) return [];-- const tasks = [];- for (const stage of rollout.value.stages) {- for (const task of stage.tasks) {- if (task.specId === exportDataSpec.value.id) {- tasks.push(task);- }- }- }- return tasks;-});--// Get all task runs for export tasks (empty if no rollout)-const allTaskRuns = computed((): TaskRun[] => {- if (!rollout.value || exportTasks.value.length === 0) return [];-- const exportTaskUIDs = new Set(- exportTasks.value.map((task) => extractTaskUID(task.name))- );-- return taskRuns.value.filter((taskRun) =>- exportTaskUIDs.has(extractTaskUID(taskRun.name))- );-});--const {- expanded,- hasMore,- visibleItems: visibleTaskRuns,- remainingCount,-} = useExpandableList(allTaskRuns);-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/LimitsSection.vue b/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/LimitsSection.vuedeleted file mode 100644index 6cce3101c1..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/LimitsSection.vue+++ /dev/null@@ -1,32 +0,0 @@-<template>- <div class="w-full flex flex-col gap-y-2">- <h3 class="text-base font-medium">- {{ $t("issue.data-export.limits") }}- </h3>-- <div class="flex items-center gap-x-2">- <span class="text-sm">- {{ $t("settings.general.workspace.maximum-sql-result.size.self") }}- </span>- <span class="font-medium">- {{ maximumResultSize }} MB- </span>- </div>- </div>-</template>--<script lang="tsx" setup>-import { computed } from "vue";-import { DEFAULT_MAX_RESULT_SIZE_IN_MB, useSettingV1Store } from "@/store";--const settingStore = useSettingV1Store();--const maximumResultSize = computed(() => {- let size = settingStore.workspaceProfile.sqlResultSize;- if (size <= 0) {- size = BigInt(DEFAULT_MAX_RESULT_SIZE_IN_MB * 1024 * 1024);- }-- return Number(size) / 1024 / 1024;-});-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/OptionsSection.vue b/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/OptionsSection.vuedeleted file mode 100644index 1ff12fa329..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/OptionsSection.vue+++ /dev/null@@ -1,207 +0,0 @@-<template>- <div class="flex flex-col gap-y-2">- <div class="flex items-center justify-between">- <h3 class="text-base font-medium">- {{ $t("issue.data-export.options") }}- </h3>- <div- v-if="shouldShowEditButton || isEditing"- class="flex flex-row justify-end items-center gap-2"- >- <template v-if="!isEditing">- <NButton size="small" @click="handleEdit">- {{ $t("common.edit") }}- </NButton>- </template>- <template v-else>- <NButton size="small" :disabled="!hasChanges" @click="handleSave">- {{ $t("common.save") }}- </NButton>- <NButton size="small" quaternary @click="handleCancel">- {{ $t("common.cancel") }}- </NButton>- </template>- </div>- </div>-- <div class="p-3 border rounded-sm flex flex-col gap-y-3">- <!-- Format Display/Edit -->- <div class="flex items-center gap-4">- <span class="text-sm">- {{ $t("issue.data-export.format") }}- </span>- <ExportFormatSelector- v-model:format="editableConfig.format"- :editable="optionsEditable"- />- </div>-- <!-- Password Protection Display/Edit -->- <ExportPasswordInputer- v-model:password="editableConfig.password"- :editable="optionsEditable"- />- </div>- </div>-</template>--<script lang="ts" setup>-import { clone, create } from "@bufbuild/protobuf";-import { NButton } from "naive-ui";-import { computed, reactive, watch } from "vue";-import { useI18n } from "vue-i18n";-import { planServiceClientConnect } from "@/connect";-import { pushNotification } from "@/store";-import {- Plan_ExportDataConfigSchema,- PlanSchema,- UpdatePlanRequestSchema,-} from "@/types/proto-es/v1/plan_service_pb";-import { usePlanContext } from "../../../logic";-import ExportFormatSelector from "../../ExportOption/ExportFormatSelector.vue";-import ExportPasswordInputer from "../../ExportOption/ExportPasswordInputer.vue";--const { t } = useI18n();-const { plan, readonly, isCreating } = usePlanContext();--// Get export config from plan context-const exportDataConfig = computed(() => {- const exportDataSpec = plan.value.specs.find(- (spec) => spec.config?.case === "exportDataConfig"- );- if (exportDataSpec?.config.case === "exportDataConfig") {- return exportDataSpec.config.value;- }- return null;-});--// Local editing state-const state = reactive({- isEditing: false,- editableConfig: create(Plan_ExportDataConfigSchema, {}),-});--// Initialize editableConfig when exportDataConfig becomes available-watch(- exportDataConfig,- (config) => {- if (config && !state.isEditing) {- state.editableConfig = clone(Plan_ExportDataConfigSchema, config);- }- },- { immediate: true }-);--const isEditing = computed(() => state.isEditing);--// Check if we should show edit button (similar to statement section logic)-const shouldShowEditButton = computed(() => {- // Not allowed to edit if readonly- if (readonly.value) {- return false;- }- // Need not to show "Edit" while the plan is still pending create- if (isCreating.value) {- return false;- }- // Will show another button group as [Save][Cancel] while editing- if (state.isEditing) {- return false;- }- if (plan.value.hasRollout) {- return false;- }- return true;-});--const optionsEditable = computed(() => {- return isCreating.value || state.isEditing;-});--const editableConfig = computed(() => state.editableConfig);--// Check if the editable config has changes compared to the original-const hasChanges = computed(() => {- if (!state.isEditing || !exportDataConfig.value) {- return false;- }-- // Compare the current editable config with the original config- return (- state.editableConfig.format !== exportDataConfig.value.format ||- state.editableConfig.password !== exportDataConfig.value.password- );-});--// Event handlers-const handleEdit = () => {- if (!exportDataConfig.value) return;-- state.isEditing = true;- state.editableConfig = clone(- Plan_ExportDataConfigSchema,- exportDataConfig.value- );-};--const handleSave = async () => {- try {- const exportDataSpec = plan.value.specs.find(- (spec) => spec.config?.case === "exportDataConfig"- );-- if (!exportDataSpec) {- throw new Error("Cannot find export data spec to update");- }-- const planPatch = clone(PlanSchema, plan.value);- const specToPatch = planPatch.specs.find(- (spec) => spec.id === exportDataSpec.id- );-- if (!specToPatch || specToPatch.config.case !== "exportDataConfig") {- throw new Error("Cannot find export data spec to update");- }-- // Update the export config- specToPatch.config.value = clone(- Plan_ExportDataConfigSchema,- state.editableConfig- );-- const request = create(UpdatePlanRequestSchema, {- plan: planPatch,- updateMask: { paths: ["specs"] },- });-- const response = await planServiceClientConnect.updatePlan(request);- Object.assign(plan.value, response);-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.error"),- description: `Failed to update export options: ${error}`,- });- return; // Don't exit editing mode if save failed- }-- state.isEditing = false;-};--const handleCancel = () => {- state.isEditing = false;- if (exportDataConfig.value) {- state.editableConfig = clone(- Plan_ExportDataConfigSchema,- exportDataConfig.value- );- }-};-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/TargetsSection.vue b/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/TargetsSection.vuedeleted file mode 100644index 1f1b312009..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/TargetsSection.vue+++ /dev/null@@ -1,71 +0,0 @@-<template>- <div class="flex flex-col gap-y-2">- <template v-if="targets.length > 0">- <h3 class="text-base font-medium">- {{ $t("plan.targets.title") }}- </h3>- <div class="flex flex-wrap gap-2">- <div- v-for="target in targets"- :key="target"- class="inline-flex items-center gap-2 px-2 py-1.5 border rounded-sm min-w-0"- >- <template v-if="isValidDatabaseName(target)">- <DatabaseDisplay- :database="target"- :show-environment="true"- size="medium"- class="flex-1 min-w-0"- />- </template>- <template v-else-if="isValidDatabaseGroupName(target)">- <DatabaseGroupTargetDisplay :target="target" class="px-1 py-1" />- </template>- <template v-else>- <span class="text-sm">{{ target }}</span>- </template>- </div>- </div>- </template>- <div v-else class="text-center text-control-light py-8">- {{ $t("common.no-data") }}- </div>- </div>-</template>--<script lang="ts" setup>-import { computed, watchEffect } from "vue";-import DatabaseDisplay from "@/components/Plan/components/common/DatabaseDisplay.vue";-import DatabaseGroupTargetDisplay from "@/components/Plan/components/SpecDetailView/DatabaseGroupTargetDisplay.vue";-import { useDatabaseV1Store, useDBGroupStore } from "@/store";-import { isValidDatabaseGroupName, isValidDatabaseName } from "@/types";-import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";-import { usePlanContext } from "../../../logic";--const { plan } = usePlanContext();-const dbStore = useDatabaseV1Store();-const dbGroupStore = useDBGroupStore();--const targets = computed(() => {- const exportDataSpec = plan.value.specs.find(- (spec) => spec.config?.case === "exportDataConfig"- );- if (exportDataSpec?.config.case === "exportDataConfig") {- return exportDataSpec.config.value.targets || [];- }- return [];-});--// Fetch target data-watchEffect(() => {- for (const target of targets.value) {- if (isValidDatabaseName(target)) {- dbStore.getOrFetchDatabaseByName(target);- } else if (isValidDatabaseGroupName(target)) {- dbGroupStore.getOrFetchDBGroupByName(target, {- view: DatabaseGroupView.FULL,- });- }- }-});-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/TasksSection.vue b/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/TasksSection.vuedeleted file mode 100644index bb33e73b2c..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/TasksSection.vue+++ /dev/null@@ -1,102 +0,0 @@-<template>- <div class="flex flex-col gap-y-2">- <template v-if="tasks.length > 0">- <h3 class="text-base font-medium">- {{ $t("common.task", tasks.length) }}- </h3>- <div- class="flex flex-wrap gap-2"- :class="expanded && hasMore ? 'max-h-96 overflow-y-auto' : ''"- >- <div- v-for="task in visibleTasks"- :key="task.name"- class="inline-flex items-center gap-2 px-2 py-1.5 border rounded-sm min-w-0"- >- <TaskStatus :status="task.status" size="tiny" class="shrink-0" />- <DatabaseDisplay- :database="task.target"- :show-environment="true"- size="medium"- class="flex-1 min-w-0"- />- <TaskStatusActions- :task="task"- :stage="getStageForTask(task)!"- :size="'tiny'"- @action-confirmed="handleActionConfirmed"- />- </div>- <button- v-if="hasMore"- class="text-sm px-2 text-accent cursor-pointer"- @click="expanded = !expanded"- >- <template v-if="expanded">- {{ $t("common.collapse") }}- </template>- <template v-else>- {{ $t("common.show-more") }}- ({{ remainingCount }} {{ $t("common.remaining") }})- </template>- </button>- </div>- </template>- <div v-else class="text-center text-control-light py-8">- {{ $t("common.no-data") }}- </div>- </div>-</template>--<script lang="ts" setup>-import { computed, watchEffect } from "vue";-import DatabaseDisplay from "@/components/Plan/components/common/DatabaseDisplay.vue";-import { emitPlanStatusChanged } from "@/components/Plan/logic";-import TaskStatus from "@/components/RolloutV1/components/Task/TaskStatus.vue";-import TaskStatusActions from "@/components/RolloutV1/components/Task/TaskStatusActions.vue";-import { useDatabaseV1Store } from "@/store";-import type { Stage, Task } from "@/types/proto-es/v1/rollout_service_pb";-import { usePlanContextWithRollout } from "../../../logic";-import { useExpandableList } from ".";--const { plan, rollout, events } = usePlanContextWithRollout();-const dbStore = useDatabaseV1Store();--const tasks = computed(() => {- const exportDataSpec = plan.value.specs.find(- (spec) => spec.config?.case === "exportDataConfig"- );- if (!exportDataSpec) return [];-- return rollout.value.stages- .flatMap((stage) => stage.tasks)- .filter((task) => task.specId === exportDataSpec.id);-});--const {- expanded,- hasMore,- visibleItems: visibleTasks,- remainingCount,-} = useExpandableList(tasks);--// Get the stage that contains a given task-const getStageForTask = (task: Task): Stage | undefined => {- return rollout.value.stages.find((stage) =>- stage.tasks.some((t) => t.name === task.name)- );-};--// Handle action confirmed - trigger data refresh-const handleActionConfirmed = () => {- emitPlanStatusChanged(events, { refreshMode: "fast-follow" });-};--// Fetch task target databases-watchEffect(() => {- const targets = tasks.value.map((task) => task.target);- if (targets.length > 0) {- dbStore.batchGetOrFetchDatabases(targets);- }-});-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/index.ts b/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/index.tsdeleted file mode 100644index 69eecebad1..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/DatabaseExportView/index.ts+++ /dev/null@@ -1,23 +0,0 @@-import { type Ref, computed, ref } from "vue";--const DEFAULT_DISPLAY_COUNT = 10;-export const VIRTUAL_SCROLL_THRESHOLD = 50;--export function useExpandableList<T>(items: Ref<T[]>) {- const expanded = ref(false);- const hasMore = computed(() => items.value.length > DEFAULT_DISPLAY_COUNT);- const visibleItems = computed(() => {- if (expanded.value || !hasMore.value) return items.value;- return items.value.slice(0, DEFAULT_DISPLAY_COUNT);- });- const remainingCount = computed(- () => items.value.length - DEFAULT_DISPLAY_COUNT- );- return { expanded, hasMore, visibleItems, remainingCount };-}--export { default as ExecutionHistorySection } from "./ExecutionHistorySection.vue";-export { default as LimitsSection } from "./LimitsSection.vue";-export { default as OptionsSection } from "./OptionsSection.vue";-export { default as TargetsSection } from "./TargetsSection.vue";-export { default as TasksSection } from "./TasksSection.vue";diff --git a/frontend/src/components/Plan/components/IssueReviewView/IssueBaseLayout.vue b/frontend/src/components/Plan/components/IssueReviewView/IssueBaseLayout.vuedeleted file mode 100644index ef244fd0ab..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/IssueBaseLayout.vue+++ /dev/null@@ -1,52 +0,0 @@-<template>- <div class="flex-1 flex w-full border-t -mt-px">- <!-- Left Panel - Activity -->- <div class="flex-1 shrink p-4 flex flex-col gap-y-4 overflow-x-auto">- <slot />- <ActivitySection />- </div>-- <!-- Desktop Sidebar -->- <div- v-if="sidebarMode === 'DESKTOP'"- class="shrink-0 flex flex-col border-l"- :style="{- width: `${desktopSidebarWidth}px`,- }"- >- <Sidebar />- </div>-- <!-- Mobile Sidebar -->- <template v-if="sidebarMode === 'MOBILE'">- <Drawer :show="mobileSidebarOpen" @close="mobileSidebarOpen = false">- <div- style="- min-width: 240px;- width: 80vw;- max-width: 320px;- padding: 0.5rem;- "- >- <Sidebar />- </div>- </Drawer>- </template>- </div>-</template>--<script setup lang="ts">-import { Drawer } from "@/components/v2";-import { usePlanContextWithIssue } from "../..";-import { useSidebarContext } from "../../logic/sidebar";-import { ActivitySection } from "./ActivitySection";-import { Sidebar } from "./Sidebar";--usePlanContextWithIssue();--const {- mode: sidebarMode,- desktopSidebarWidth,- mobileSidebarOpen,-} = useSidebarContext();-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/OverviewSection.vue b/frontend/src/components/Plan/components/IssueReviewView/OverviewSection.vuedeleted file mode 100644index 52ffba7da2..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/OverviewSection.vue+++ /dev/null@@ -1,95 +0,0 @@-<template>- <div class="w-full overflow-y-auto">- <div class="grid grid-cols-[auto_1fr] gap-y-4 gap-x-8">- <!-- SQL Checks -->- <h3 class="text-base text-control">- {{ $t("plan.navigator.checks") }}- </h3>- <div class="flex items-center gap-4">- <PlanCheckStatusCount- :plan="plan"- clickable- @click="selectedResultStatus = $event"- />- <span v-if="!hasAnyChecks" class="text-sm text-control">- {{ $t("plan.overview.no-checks") }}- </span>- </div>-- <!-- Stages -->- <template v-if="rollout">- <h3 class="text-base text-control">- {{ $t("rollout.stage.self", 2) }}- </h3>- <div class="flex items-center gap-1 flex-wrap">- <template v-if="rollout.stages.length > 0">- <div- v-for="(stage, index) in rollout.stages"- :key="stage.name"- class="flex items-center gap-1"- >- <div- class="flex items-center gap-1 cursor-pointer hover:opacity-80 transition-opacity"- @click="navigateToStage(stage.name)"- >- <TaskStatus- :status="getStageStatus(stage)"- size="small"- disabled- />- <EnvironmentV1Name- :environment="getEnvironmentEntity(stage.environment)"- :link="false"- />- </div>- <span- v-if="index < rollout.stages.length - 1"- class="text-gray-400 text-sm mx-2"- >- →- </span>- </div>- </template>- <span v-else class="text-sm text-control">- {{ $t("common.no-data") }}- </span>- </div>- </template>- </div>- </div>-- <ChecksDrawer- v-if="selectedResultStatus"- :status="selectedResultStatus"- @close="selectedResultStatus = undefined"- />-</template>--<script setup lang="ts">-import { ref } from "vue";-import { useRouter } from "vue-router";-import TaskStatus from "@/components/RolloutV1/components/Task/TaskStatus.vue";-import { EnvironmentV1Name } from "@/components/v2";-import { buildStageRoute } from "@/router/dashboard/projectV1RouteHelpers";-import { useEnvironmentV1Store } from "@/store";-import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";-import { getStageStatus } from "@/utils";-import { usePlanCheckStatus, usePlanContext } from "../../logic";-import ChecksDrawer from "../ChecksView/ChecksDrawer.vue";-import PlanCheckStatusCount from "../PlanCheckStatusCount.vue";--const { plan, rollout } = usePlanContext();-const environmentStore = useEnvironmentV1Store();-const router = useRouter();-const { hasAnyStatus: hasAnyChecks } = usePlanCheckStatus(plan);--const selectedResultStatus = ref<Advice_Level | undefined>(undefined);--const getEnvironmentEntity = (environmentName: string) => {- return environmentStore.getEnvironmentByName(environmentName);-};--const navigateToStage = (stageName: string) => {- router.push(buildStageRoute(stageName));-};-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/RoleGrantView.vue b/frontend/src/components/Plan/components/IssueReviewView/RoleGrantView.vuedeleted file mode 100644index 47fd0e7a42..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/RoleGrantView.vue+++ /dev/null@@ -1,10 +0,0 @@-<template>- <div class="w-full flex flex-col gap-y-4">- <!-- Role Grant Details Section -->- <RequestDetailsSection />- </div>-</template>--<script lang="ts" setup>-import { RequestDetailsSection } from "./RoleGrantView";-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/RoleGrantView/RequestDetailsSection.vue b/frontend/src/components/Plan/components/IssueReviewView/RoleGrantView/RequestDetailsSection.vuedeleted file mode 100644index 259a3a1492..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/RoleGrantView/RequestDetailsSection.vue+++ /dev/null@@ -1,105 +0,0 @@-<template>- <div class="flex flex-col gap-y-4">- <h3 class="text-base font-medium">- {{ $t("issue.role-grant.details") }}- </h3>-- <div class="p-4 border rounded-sm flex flex-col gap-y-4">- <!-- Requested Role -->- <div v-if="requestRoleName" class="flex flex-col gap-y-2">- <span class="text-sm text-control-light">- {{ $t("role.self") }}- </span>- <div class="text-base">- {{ displayRoleTitle(requestRoleName) }}- </div>- </div>-- <div v-if="requestRole" class="flex flex-col gap-y-2">- <span class="text-sm text-control-light">- {{ $t("common.permissions") }}- ({{- requestRole.permissions.length- }})- </span>- <div class="max-h-[10em] overflow-auto border rounded-sm p-2">- <p- v-for="permission in requestRole.permissions"- :key="permission"- class="text-sm leading-5"- >- {{ permission }}- </p>- </div>- </div>-- <!-- Database Resources -->- <div v-if="condition?.databaseResources" class="flex flex-col gap-y-2">- <span class="text-sm text-control-light">- {{ $t("common.database") }}- </span>- <div>- <span v-if="condition.databaseResources.length === 0">- {{ $t("issue.role-grant.all-databases") }}- </span>- <DatabaseResourceTable- v-else- class="w-full"- :database-resource-list="condition.databaseResources"- />- </div>- </div>-- <!-- Expiration Time -->- <div class="flex flex-col gap-y-2">- <span class="text-sm text-control-light">- {{ $t("issue.role-grant.expired-at") }}- </span>- <div class="text-base">- {{- condition?.expiredTime- ? dayjs(new Date(condition.expiredTime)).format("LLL")- : $t("project.members.never-expires")- }}- </div>- </div>- </div>- </div>-</template>--<script setup lang="ts">-import { computedAsync } from "@vueuse/core";-import dayjs from "dayjs";-import { computed } from "vue";-import { DatabaseResourceTable } from "@/components/IssueV1/components";-import { useRoleStore } from "@/store";-import { displayRoleTitle } from "@/utils";-import { convertFromCELString } from "@/utils/issue/cel";-import { usePlanContextWithIssue } from "../../../logic";--const { issue } = usePlanContextWithIssue();-const roleStore = useRoleStore();--const requestRoleName = computed(() => {- return issue.value.roleGrant?.role;-});--const requestRole = computed(() =>- roleStore.getRoleByName(requestRoleName?.value ?? "")-);--const condition = computedAsync(- async () => {- try {- const conditionExpression = await convertFromCELString(- issue.value.roleGrant?.condition?.expression ?? ""- );- return conditionExpression;- } catch (error) {- console.error("Failed to parse CEL expression:", error);- return undefined;- }- },- undefined // default value while loading or on error-);-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/RoleGrantView/index.ts b/frontend/src/components/Plan/components/IssueReviewView/RoleGrantView/index.tsdeleted file mode 100644index d8be9bb964..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/RoleGrantView/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import RequestDetailsSection from "./RequestDetailsSection.vue";--export { RequestDetailsSection };diff --git a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/ApprovalFlowSection.vue b/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/ApprovalFlowSection.vuedeleted file mode 100644index 4f5bd2fe49..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/ApprovalFlowSection.vue+++ /dev/null@@ -1,111 +0,0 @@-<template>- <div>- <div class="w-full flex flex-row items-center gap-2 flex-wrap">- <h3 class="textinfolabel">{{ $t("issue.approval-flow.self") }}</h3>- <FeatureBadge :feature="PlanFeature.FEATURE_APPROVAL_WORKFLOW" />- <RiskLevelIcon- :risk-level="issue.riskLevel"- :title="approvalTemplate?.title?.trim()"- />- <div class="grow" />- <NTag class="truncate" v-if="statusTag" size="small" round :type="statusTag.type">- {{ statusTag.label }}- </NTag>- </div>-- <div class="mt-2">- <div- v-if="issue.approvalStatus === Issue_ApprovalStatus.CHECKING"- class="flex items-center gap-x-2 text-sm text-control-placeholder"- >- <BBSpin :size="16" />- <span>- {{ $t("custom-approval.issue-review.generating-approval-flow") }}- </span>- </div>- <NTimeline- v-else-if="approvalSteps.length > 0"- size="large"- class="pl-1 mt-1"- >- <ApprovalStepItem- v-for="(step, index) in approvalSteps"- :key="index"- :step="step"- :step-index="index"- :step-number="index + 1"- :issue="issue"- :readonly="hasRollout"- />- </NTimeline>- <div- v-else- class="flex items-center text-sm text-control-placeholder gap-x-1"- >- {{ $t("custom-approval.approval-flow.skip") }}- </div>- </div>- </div>-</template>--<script setup lang="ts">-import type { TagProps } from "naive-ui";-import { NTag, NTimeline } from "naive-ui";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import { BBSpin } from "@/bbkit";-import FeatureBadge from "@/components/FeatureGuard/FeatureBadge.vue";-import type { Issue } from "@/types/proto-es/v1/issue_service_pb";-import { Issue_ApprovalStatus } from "@/types/proto-es/v1/issue_service_pb";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";-import ApprovalStepItem from "./ApprovalStepItem.vue";-import RiskLevelIcon from "./RiskLevelIcon.vue";--interface StatusTag {- label: string;- type?: TagProps["type"];-}--const props = withDefaults(- defineProps<{- issue: Issue;- hasRollout?: boolean;- }>(),- { hasRollout: false }-);--const { t } = useI18n();--const approvalTemplate = computed(() => {- return props.issue.approvalTemplate;-});--const approvalSteps = computed(() => {- return approvalTemplate.value?.flow?.roles || [];-});--const statusTag = computed((): StatusTag | undefined => {- const status = props.issue.approvalStatus;- if (approvalSteps.value.length === 0) return undefined;-- if (status === Issue_ApprovalStatus.APPROVED) {- return {- label: t("issue.table.approved"),- type: "success",- };- }- if (status === Issue_ApprovalStatus.REJECTED) {- return {- label: t("common.rejected"),- type: "warning",- };- }- if (status === Issue_ApprovalStatus.PENDING) {- return {- label: t("common.under-review"),- type: "info",- };- }- return undefined;-});-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/ApprovalStepItem.vue b/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/ApprovalStepItem.vuedeleted file mode 100644index d374cb1bdd..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/ApprovalStepItem.vue+++ /dev/null@@ -1,141 +0,0 @@-<template>- <NTimelineItem :type="timelineItemType">- <template #icon>- <div- class="p-1 rounded-full flex items-center justify-center z-10"- :class="iconClass"- >- <ThumbsUp v-if="status === 'approved'" class="w-4 h-4 text-white" />- <X v-else-if="status === 'rejected'" class="w-4 h-4 text-white" />- <User v-else-if="status === 'current'" class="w-4 h-4 text-white" />- <div v-else class="flex w-4 h-4 justify-center items-center">- <span class="text-sm font-medium text-gray-600">{{ stepNumber }}</span>- </div>- </div>- </template>-- <div>- <div class="text-sm font-medium text-gray-900">- {{ roleName }}- </div>-- <div class="mt-1 text-sm text-gray-600">- <!-- Approved -->- <div v-if="status === 'approved'" class="flex flex-row items-center gap-1">- <span class="text-xs">- {{ $t("custom-approval.issue-review.approved-by") }}- </span>- <ApprovalUserView- v-if="stepApprover"- :candidate="stepApprover.principal"- />- </div>-- <!-- Rejected -->- <div v-else-if="status === 'rejected'" class="flex flex-col gap-1">- <div class="flex flex-row items-center gap-1">- <span class="text-xs">- {{ $t("custom-approval.issue-review.rejected-by") }}- </span>- <ApprovalUserView- v-if="stepApprover"- :candidate="stepApprover.principal"- />- </div>- <div v-if="canReRequest && !readonly" class="mt-1">- <NButton- size="tiny"- strong- secondary- type="info"- :loading="reRequesting"- @click="handleReRequestReview"- >- <template #icon>- <RotateCcwIcon class="w-3 h-3" />- </template>- {{ $t("custom-approval.issue-review.re-request-review") }}- </NButton>- </div>- </div>-- <!-- Current -->- <div v-else-if="status === 'current'" class="flex flex-col gap-1">- <template v-if="!readonly">- <PotentialApprovers :users="potentialApprovers" />- <div- v-if="showSelfApprovalTip"- class="px-1 py-0.5 border rounded-sm text-xs bg-yellow-50 border-yellow-600 text-yellow-600"- >- {{ $t("custom-approval.issue-review.self-approval-not-allowed") }}- </div>- </template>- </div>- </div>- </div>- </NTimelineItem>-</template>--<script setup lang="ts">-import { RotateCcwIcon, ThumbsUp, User, X } from "lucide-vue-next";-import { NButton, NTimelineItem } from "naive-ui";-import { computed, toRef } from "vue";-import type { Issue } from "@/types/proto-es/v1/issue_service_pb";-import ApprovalUserView from "./ApprovalUserView.vue";-import PotentialApprovers from "./PotentialApprovers.vue";-import { useApprovalStep } from "./useApprovalStep";--const props = withDefaults(- defineProps<{- step: string;- stepIndex: number;- stepNumber: number;- issue: Issue;- readonly?: boolean;- }>(),- {- readonly: false,- }-);--const {- status,- stepApprover,- roleName,- canReRequest,- reRequesting,- handleReRequestReview,- potentialApprovers,- showSelfApprovalTip,-} = useApprovalStep(- toRef(props, "issue"),- toRef(props, "step"),- toRef(props, "stepIndex")-);--const timelineItemType = computed(() => {- switch (status.value) {- case "approved":- return "success";- case "rejected":- return "warning";- case "current":- return "info";- default:- return "default";- }-});--const iconClass = computed(() => {- switch (status.value) {- case "approved":- return "bg-green-500";- case "rejected":- return "bg-yellow-500";- case "current":- return "bg-blue-500";- default:- return "bg-gray-200";- }-});-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/ApprovalUserView.vue b/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/ApprovalUserView.vuedeleted file mode 100644index 4da6b9896d..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/ApprovalUserView.vue+++ /dev/null@@ -1,42 +0,0 @@-<template>- <UserNameCell- v-if="candidateUser"- :user="candidateUser"- size="tiny"- :show-mfa-enabled="false"- :show-source="false"- :allow-edit="false"- :show-email="false"- />-</template>--<script setup lang="ts">-import { computedAsync } from "@vueuse/core";-import { UserNameCell } from "@/components/v2/Model/cells";-import { useUserStore } from "@/store";-import { AccountType, getAccountTypeByEmail } from "@/types";-import { State } from "@/types/proto-es/v1/common_pb";--const props = defineProps<{- // candidate in users/{email} format.- candidate: string;-}>();--const userStore = useUserStore();--const candidateUser = computedAsync(async () => {- const user = await userStore.getOrFetchUserByIdentifier({- identifier: props.candidate,- });- if (!user) {- return;- }- if (- getAccountTypeByEmail(user.email) !== AccountType.USER ||- user.state !== State.ACTIVE- ) {- return;- }- return user;-});-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/PotentialApprovers.vue b/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/PotentialApprovers.vuedeleted file mode 100644index 8c9f8c3e0f..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/PotentialApprovers.vue+++ /dev/null@@ -1,75 +0,0 @@-<template>- <template v-if="users.length > 0">- <!-- Show tooltip with text when there are more than 3 users -->- <NPopover- v-if="users.length > 3"- placement="bottom-end"- :show-arrow="false"- >- <template #trigger>- <span class="text-xs text-gray-600 cursor-pointer hover:text-blue-600">- {{ triggerText }}- </span>- </template>- <div class="max-w-xs">- <div class="flex flex-col gap-y-1 max-h-64 overflow-y-auto">- <UserNameCell- v-for="user in users"- :key="user.name"- :user="user"- size="small"- :show-mfa-enabled="false"- :show-source="false"- :allow-edit="false"- />- </div>- </div>- </NPopover>- <!-- Show user avatars when 3 or fewer users -->- <div v-else class="flex flex-col items-start gap-1">- <UserNameCell- v-for="user in users"- :key="user.name"- :user="user"- size="tiny"- :show-mfa-enabled="false"- :show-source="false"- :allow-edit="false"- :show-email="false"- />- </div>- </template>-</template>--<script setup lang="ts">-import { NPopover } from "naive-ui";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import { UserNameCell } from "@/components/v2/Model/cells";-import type { User } from "@/types/proto-es/v1/user_service_pb";--const props = defineProps<{- users: User[];-}>();--const { t } = useI18n();--const triggerText = computed(() => {- if (props.users.length === 0) return "";-- const displayUsers = props.users.slice(0, 3);- const remainingCount = props.users.length - displayUsers.length;- const names = displayUsers- .map((user) => user.title || user.email.split("@")[0])- .join(", ");-- if (remainingCount === 0) {- return names;- } else {- return t("custom-approval.issue-review.and-n-other-users", {- names,- count: remainingCount,- });- }-});-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/RiskLevelIcon.vue b/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/RiskLevelIcon.vuedeleted file mode 100644index e9f062ee0e..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/RiskLevelIcon.vue+++ /dev/null@@ -1,53 +0,0 @@-<template>- <NTooltip v-if="riskLevel">- <template #trigger>- <ShieldCheckIcon- v-if="riskLevel === RiskLevel.LOW"- class="w-4 h-4 text-success"- />- <ShieldAlertIcon- v-else-if="riskLevel === RiskLevel.MODERATE"- class="w-4 h-4 text-warning"- />- <ShieldAlertIcon- v-else-if="riskLevel === RiskLevel.HIGH"- class="w-4 h-4 text-error"- />- </template>- <div class="flex flex-col gap-1">- <div>- <span>{{ riskLevelText }}</span>- <span class="opacity-60 ml-1">({{ $t("issue.risk-level.self") }})</span>- </div>- <div v-if="title" class="text-sm opacity-80">{{ title }}</div>- </div>- </NTooltip>-</template>--<script setup lang="ts">-import { ShieldAlertIcon, ShieldCheckIcon } from "lucide-vue-next";-import { NTooltip } from "naive-ui";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import { RiskLevel } from "@/types/proto-es/v1/common_pb";--const props = defineProps<{- riskLevel: RiskLevel;- title?: string;-}>();--const { t } = useI18n();--const riskLevelText = computed(() => {- switch (props.riskLevel) {- case RiskLevel.LOW:- return t("issue.risk-level.low");- case RiskLevel.MODERATE:- return t("issue.risk-level.moderate");- case RiskLevel.HIGH:- return t("issue.risk-level.high");- default:- return "";- }-});-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/index.ts b/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/index.tsdeleted file mode 100644index 66b5133789..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/index.ts+++ /dev/null@@ -1 +0,0 @@-export { default as ApprovalFlowSection } from "./ApprovalFlowSection.vue";diff --git a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/useApprovalStep.ts b/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/useApprovalStep.tsdeleted file mode 100644index fbca9f3aaa..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/useApprovalStep.ts+++ /dev/null@@ -1,231 +0,0 @@-import { create } from "@bufbuild/protobuf";-import { computedAsync } from "@vueuse/core";-import { uniq } from "lodash-es";-import type { Ref } from "vue";-import { computed, ref, watchEffect } from "vue";-import { useI18n } from "vue-i18n";-import { tryUsePlanContext } from "@/components/Plan/logic";-import { issueServiceClientConnect } from "@/connect";-import {- pushNotification,- useCurrentProjectV1,- useCurrentUserV1,- useGroupStore,- useProjectIamPolicyStore,- useUserStore,-} from "@/store";-import { userNamePrefix } from "@/store/modules/v1/common";-import { groupBindingPrefix } from "@/types";-import { State } from "@/types/proto-es/v1/common_pb";-import type {- Issue,- Issue_Approver,-} from "@/types/proto-es/v1/issue_service_pb";-import {- Issue_Approver_Status,- RequestIssueRequestSchema,-} from "@/types/proto-es/v1/issue_service_pb";-import {- displayRoleTitle,- ensureUserFullName,- isBindingPolicyExpired,- memberMapToRolesInProjectIAM,-} from "@/utils";--export type ApprovalStepStatus =- | "approved"- | "rejected"- | "current"- | "pending";--export function useApprovalStep(- issue: Ref<Issue>,- step: Ref<string>,- stepIndex: Ref<number>-) {- const { t } = useI18n();- const { project } = useCurrentProjectV1();- const planContext = tryUsePlanContext();- const currentUser = useCurrentUserV1();- const userStore = useUserStore();- const groupStore = useGroupStore();- const projectIamPolicyStore = useProjectIamPolicyStore();-- const currentUserEmail = computed(() => currentUser.value.email);- const reRequesting = ref(false);-- // Get the approver for this specific step- const stepApprover = computed(- (): Issue_Approver | undefined => issue.value.approvers[stepIndex.value]- );-- const status = computed((): ApprovalStepStatus => {- if (stepApprover.value?.status === Issue_Approver_Status.APPROVED) {- return "approved";- }- if (stepApprover.value?.status === Issue_Approver_Status.REJECTED) {- return "rejected";- }- // Check if all previous steps are approved- for (let i = 0; i < stepIndex.value; i++) {- const prevApprover = issue.value.approvers[i];- if (- !prevApprover ||- (prevApprover.status !== Issue_Approver_Status.APPROVED &&- prevApprover.status !== Issue_Approver_Status.REJECTED)- ) {- return "pending";- }- if (prevApprover.status === Issue_Approver_Status.REJECTED) {- return "pending";- }- }- return "current";- });-- const canReRequest = computed(() => {- const isCreator = issue.value.creator === `users/${currentUserEmail.value}`;- const stepIsRejected =- stepApprover.value?.status === Issue_Approver_Status.REJECTED;- return isCreator && stepIsRejected;- });-- const handleReRequestReview = async () => {- if (reRequesting.value) return;-- reRequesting.value = true;- try {- const request = create(RequestIssueRequestSchema, {- name: issue.value.name,- });- await issueServiceClientConnect.requestIssue(request);- if (planContext) {- planContext.events.emit("status-changed", { eager: true });- }-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("custom-approval.issue-review.re-request-review-success"),- });- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.failed"),- description: String(error),- });- } finally {- reRequesting.value = false;- }- };-- const roleName = computed((): string => {- if (step.value) {- return displayRoleTitle(step.value);- }- return t("custom-approval.approval-flow.node.approver");- });-- const stepRoles = computed(() => {- return [step.value].filter((role) => !!role);- });-- // Pre-fetch groups for the step- watchEffect(async () => {- const groupNames: string[] = [];- for (const role of stepRoles.value) {- const policy = projectIamPolicyStore.getProjectIamPolicy(- project.value.name- );- for (const binding of policy.bindings) {- if (binding.role !== role || isBindingPolicyExpired(binding)) {- continue;- }- for (const member of binding.members) {- if (member.startsWith(groupBindingPrefix)) {- groupNames.push(member);- }- }- }- }- await groupStore.batchGetOrFetchGroups(groupNames);- });-- // Get candidates for this approval step (only regular users, not service accounts or workload identities)- const candidateEmails = computed(() => {- const candidates: string[] = [];- for (const role of stepRoles.value) {- const policy = projectIamPolicyStore.getProjectIamPolicy(- project.value.name- );- const memberMap = memberMapToRolesInProjectIAM(policy, role);- for (const fullname of memberMap.keys()) {- if (fullname.startsWith(userNamePrefix)) {- candidates.push(fullname);- }- }- }- return uniq(candidates);- });-- const isCurrentUserInCandidates = computed(() => {- const currentUserPrincipal = `users/${currentUserEmail.value}`;- return candidateEmails.value.includes(currentUserPrincipal);- });-- const filteredCandidateEmails = computed(() => {- if (- !project.value.allowSelfApproval &&- issue.value.creator === `users/${currentUserEmail.value}`- ) {- const currentUserPrincipal = `users/${currentUserEmail.value}`;- return candidateEmails.value.filter(- (email) => email !== currentUserPrincipal- );- }- return candidateEmails.value;- });-- const showSelfApprovalTip = computed(() => {- return (- status.value === "current" &&- !project.value.allowSelfApproval &&- issue.value.creator === `users/${currentUserEmail.value}` &&- isCurrentUserInCandidates.value- );- });-- const potentialApprovers = computedAsync(async () => {- if (- status.value !== "current" ||- filteredCandidateEmails.value.length === 0- ) {- return [];- }-- const users = await userStore.batchGetOrFetchUsers(- filteredCandidateEmails.value.map(ensureUserFullName)- );- return users- .filter((user) => {- return user && user.state === State.ACTIVE;- })- .sort((a, b) => {- if (a.email === currentUserEmail.value) return -1;- if (b.email === currentUserEmail.value) return 1;- return a.title.localeCompare(b.title);- });- }, []);-- return {- status,- stepApprover,- roleName,- canReRequest,- reRequesting,- handleReRequestReview,- potentialApprovers,- showSelfApprovalTip,- };-}diff --git a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ChecksSection.vue b/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ChecksSection.vuedeleted file mode 100644index eb09e31090..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/ChecksSection.vue+++ /dev/null@@ -1,107 +0,0 @@-<template>- <div class="flex flex-col gap-y-1">- <div class="flex items-center justify-between">- <h3 class="textlabel">- {{ $t("plan.navigator.checks") }}- </h3>- <NButton- v-if="allowRunChecks"- size="tiny"- :loading="isRunningChecks"- @click="runChecks"- >- <template #icon>- <PlayIcon class="w-4 h-4" />- </template>- {{ $t("plan.run") }}- </NButton>- </div>- <div class="flex items-center gap-2">- <PlanCheckStatusCount- :plan="plan"- clickable- @click="selectedResultStatus = $event"- />- <span v-if="!hasAnyChecks" class="text-sm text-control-placeholder">- {{ $t("plan.overview.no-checks") }}- </span>- </div>-- <ChecksDrawer- v-if="selectedResultStatus"- :status="selectedResultStatus"- @close="selectedResultStatus = undefined"- />- </div>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import type { ConnectError } from "@connectrpc/connect";-import { PlayIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { computed, ref } from "vue";-import { planServiceClientConnect } from "@/connect";-import {- extractUserEmail,- pushNotification,- useCurrentProjectV1,- useCurrentUserV1,-} from "@/store";-import { RunPlanChecksRequestSchema } from "@/types/proto-es/v1/plan_service_pb";-import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";-import { hasProjectPermissionV2 } from "@/utils";-import { usePlanCheckStatus, usePlanContext } from "../../../logic";-import { useResourcePoller } from "../../../logic/poller";-import ChecksDrawer from "../../ChecksView/ChecksDrawer.vue";-import PlanCheckStatusCount from "../../PlanCheckStatusCount.vue";--const currentUser = useCurrentUserV1();-const { plan } = usePlanContext();-const { project } = useCurrentProjectV1();-const { refreshResources } = useResourcePoller();-const { hasAnyStatus: hasAnyChecks } = usePlanCheckStatus(plan);--const isRunningChecks = ref(false);-const selectedResultStatus = ref<Advice_Level | undefined>(undefined);--const allowRunChecks = computed(() => {- // Once a rollout exists, the plan is frozen — re-running checks produces- // the same result and is misleading for the user.- if (plan.value.hasRollout) return false;- const me = currentUser.value;- if (extractUserEmail(plan.value.creator) === me.email) {- return true;- }- return hasProjectPermissionV2(project.value, "bb.planCheckRuns.run");-});--const runChecks = async () => {- if (!plan.value.name) return;-- isRunningChecks.value = true;- try {- const request = create(RunPlanChecksRequestSchema, {- name: plan.value.name,- });- await planServiceClientConnect.runPlanChecks(request);-- refreshResources(["plan", "planCheckRuns"], true);-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: "Plan checks started",- });- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: "Failed to run plan checks",- description: (error as ConnectError).message,- });- } finally {- isRunningChecks.value = false;- }-};-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/Sidebar.vue b/frontend/src/components/Plan/components/IssueReviewView/Sidebar/Sidebar.vuedeleted file mode 100644index f0157c7947..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/Sidebar.vue+++ /dev/null@@ -1,93 +0,0 @@-<template>- <div class="w-full flex flex-col p-4 gap-4">- <!-- 1. Checks - Health status -->- <div v-if="isDatabaseChangePlan" class="flex flex-col gap-2">- <NAlert v-if="showChecksManualRolloutHint" type="warning">- {{ $t("issue.checks-manual-rollout-hint") }}- </NAlert>- <ChecksSection />- </div>-- <!-- 2. Approval Flow - Reviewers -->- <ApprovalFlowSection :issue="issue" :has-rollout="plan.hasRollout" />-- <!-- 3. Labels - Metadata -->- <IssueLabels- :project="project"- :value="issue.labels || []"- :disabled="!allowChange"- @update:value="onIssueLabelsUpdate"- />- </div>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { NAlert } from "naive-ui";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import IssueLabels from "@/components/IssueV1/components/Sidebar/IssueLabels.vue";-import { isApprovalCompleted } from "@/components/Plan/logic/approval";-import { useResourcePoller } from "@/components/Plan/logic/poller";-import { usePlanCheckStatus } from "@/components/Plan/logic/usePlanCheckStatus";-import { issueServiceClientConnect } from "@/connect";-import { pushNotification, useCurrentProjectV1 } from "@/store";-import {- IssueStatus,- UpdateIssueRequestSchema,-} from "@/types/proto-es/v1/issue_service_pb";-import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";-import { hasProjectPermissionV2 } from "@/utils";-import { usePlanContextWithIssue } from "../../../logic/context";-import ApprovalFlowSection from "./ApprovalFlowSection/ApprovalFlowSection.vue";-import ChecksSection from "./ChecksSection.vue";--const { t } = useI18n();-const { plan, issue } = usePlanContextWithIssue();-const { project } = useCurrentProjectV1();-const { refreshResources } = useResourcePoller();-const { getOverallStatus: planCheckStatus } = usePlanCheckStatus(plan);--const isDatabaseChangePlan = computed(- () =>- plan.value.specs.length > 0 &&- plan.value.specs.every(- (spec) => spec.config?.case === "changeDatabaseConfig"- )-);--const issueApprovalCompleted = computed(() => isApprovalCompleted(issue.value));--const showChecksManualRolloutHint = computed(() => {- return (- !plan.value.hasRollout &&- planCheckStatus.value === Advice_Level.ERROR &&- issueApprovalCompleted.value- );-});--const allowChange = computed(() => {- if (issue.value.status !== IssueStatus.OPEN) {- return false;- }- return hasProjectPermissionV2(project.value, "bb.issues.update");-});--const onIssueLabelsUpdate = async (labels: string[]) => {- const issuePatch = {- ...issue.value,- labels,- };- const request = create(UpdateIssueRequestSchema, {- issue: issuePatch,- updateMask: { paths: ["labels"] },- });- await issueServiceClientConnect.updateIssue(request);- refreshResources(["issue"], true /** force */);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });-};-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/StagesSection.vue b/frontend/src/components/Plan/components/IssueReviewView/Sidebar/StagesSection.vuedeleted file mode 100644index 362312ca7f..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/StagesSection.vue+++ /dev/null@@ -1,54 +0,0 @@-<template>- <div v-if="rollout" class="flex flex-col gap-y-1">- <h3 class="textlabel">- {{ $t("rollout.stage.self", 2) }}- </h3>- <div class="flex flex-wrap items-center gap-y-1">- <template v-if="rollout.stages.length > 0">- <template v-for="(stage, index) in rollout.stages" :key="stage.name">- <div- class="flex items-center gap-1 cursor-pointer hover:opacity-80 transition-opacity"- @click="navigateToStage(stage.name)"- >- <TaskStatus :status="getStageStatus(stage)" size="small" disabled />- <EnvironmentV1Name- :environment="getEnvironmentEntity(stage.environment)"- :link="false"- />- </div>- <span- v-if="index < rollout.stages.length - 1"- class="mx-2 text-control-placeholder"- >- →- </span>- </template>- </template>- <span v-else class="text-sm text-control-placeholder">- {{ $t("common.no-data") }}- </span>- </div>- </div>-</template>--<script setup lang="ts">-import { useRouter } from "vue-router";-import TaskStatus from "@/components/RolloutV1/components/Task/TaskStatus.vue";-import { EnvironmentV1Name } from "@/components/v2";-import { buildStageRoute } from "@/router/dashboard/projectV1RouteHelpers";-import { useEnvironmentV1Store } from "@/store";-import { getStageStatus } from "@/utils";-import { usePlanContext } from "../../../logic";--const { rollout } = usePlanContext();-const environmentStore = useEnvironmentV1Store();-const router = useRouter();--const getEnvironmentEntity = (environmentName: string) => {- return environmentStore.getEnvironmentByName(environmentName);-};--const navigateToStage = (stageName: string) => {- router.push(buildStageRoute(stageName));-};-</script>diff --git a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/index.ts b/frontend/src/components/Plan/components/IssueReviewView/Sidebar/index.tsdeleted file mode 100644index 54aabdb28e..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/Sidebar/index.ts+++ /dev/null@@ -1 +0,0 @@-export { default as Sidebar } from "./Sidebar.vue";diff --git a/frontend/src/components/Plan/components/IssueReviewView/index.ts b/frontend/src/components/Plan/components/IssueReviewView/index.tsdeleted file mode 100644index 27e3dc3ad4..0000000000--- a/frontend/src/components/Plan/components/IssueReviewView/index.ts+++ /dev/null@@ -1 +0,0 @@-export { default as IssueReviewView } from "./IssueBaseLayout.vue";diff --git a/frontend/src/components/Plan/components/PlanCheckRunStatusIcon.vue b/frontend/src/components/Plan/components/PlanCheckRunStatusIcon.vuedeleted file mode 100644index f591b3162d..0000000000--- a/frontend/src/components/Plan/components/PlanCheckRunStatusIcon.vue+++ /dev/null@@ -1,75 +0,0 @@-<template>- <span- v-if="hasAnyChecks"- class="flex items-center justify-center select-none shrink-0"- :class="iconClass()"- >- <template v-if="planCheckRunStatus === Advice_Level.ERROR">- <XIcon />- </template>- <template v-else-if="planCheckRunStatus === Advice_Level.WARNING">- <span class="text-xs font-bold" aria-hidden="true">!</span>- </template>- <template v-else-if="planCheckRunStatus === Advice_Level.SUCCESS">- <CheckIcon />- </template>- <template v-else-if="hasRunningChecks">- <span- class="w-2.5 h-2.5 rounded-full border-2 border-control"- aria-hidden="true"- ></span>- </template>- </span>-</template>--<script lang="ts" setup>-import type { PropType } from "vue";-import { computed } from "vue";-import type { Plan, PlanCheckRun } from "@/types/proto-es/v1/plan_service_pb";-import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";-import CheckIcon from "~icons/heroicons-solid/check";-import XIcon from "~icons/heroicons-solid/x";-import { useResolvedPlanCheckStatus } from "../logic";--export type SizeType = "small" | "normal";--const props = defineProps({- plan: {- required: true,- type: Object as PropType<Plan>,- },- planCheckRuns: {- type: Array as PropType<PlanCheckRun[] | undefined>,- default: undefined,- },- size: {- type: String as PropType<SizeType>,- default: "normal",- },-});--const planCheckRunsRef = computed(() => props.planCheckRuns);--const {- overallAdviceLevel: planCheckRunStatus,- hasAnyStatus: hasAnyChecks,- hasRunning: hasRunningChecks,-} = useResolvedPlanCheckStatus(- computed(() => props.plan),- planCheckRunsRef-);--const iconClass = () => {- const sizeClass = props.size === "normal" ? "w-4 h-4" : "w-3.5 h-3.5";- switch (planCheckRunStatus.value) {- case Advice_Level.ERROR:- return `${sizeClass} text-error`;- case Advice_Level.WARNING:- return `${sizeClass} text-warning`;- case Advice_Level.SUCCESS:- return `${sizeClass} text-success`;- default:- return `${sizeClass} text-warning`;- }-};-</script>diff --git a/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckSection.vue b/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckSection.vuedeleted file mode 100644index 1a72f50ca5..0000000000--- a/frontend/src/components/Plan/components/PlanCheckSection/PlanCheckSection.vue+++ /dev/null@@ -1,208 +0,0 @@-<template>- <div v-if="shouldShow" class="flex flex-col gap-y-2">- <!-- Row 1: Title + Run button -->- <div class="flex items-center justify-between gap-2">- <div class="flex flex-row items-center gap-2">- <h3 class="textlabel uppercase">{{ $t("plan.checks.self") }}</h3>- <NTooltip v-if="isStatementOversized" style="max-width: 20rem">- <template #trigger>- <NTag type="warning" round size="tiny">- <template #icon>- <CircleQuestionMarkIcon class="size-3" />- </template>- {{ $t("common.skipped") }}- </NTag>- </template>- {{ $t("issue.sql-check.statement-is-too-large") }}- </NTooltip>- </div>- <NButton- v-if="allowRunChecks"- size="tiny"- :loading="isRunningChecks"- @click="runChecks"- >- <template #icon>- <PlayIcon class="w-4 h-4" />- </template>- {{ $t("plan.run") }}- </NButton>- </div>-- <!-- Row 2: Status badges -->- <div class="flex items-center flex-wrap gap-2 min-w-0">- <PlanCheckStatusCount- :plan="plan"- :plan-check-runs="checksOfSelectedSpec"- :show-label="true"- clickable- @click="openChecksDrawer($event)"- />-- <NTooltip- v-if="checksOfSelectedSpec.length > 0 && affectedRows > 0"- style="max-width: 20rem"- >- <template #trigger>- <NTag round :bordered="false">- <div class="flex items-center gap-1">- <span class="text-sm text-control-light">{{- $t("task.check-type.affected-rows.self")- }}</span>- <span class="text-sm">- {{ affectedRows }}- </span>- <CircleQuestionMarkIcon- class="size-3.5 text-control-light opacity-80"- />- </div>- </NTag>- </template>- {{ $t("task.check-type.affected-rows.description") }}- </NTooltip>- </div>-- <ChecksDrawer- v-model:show="showChecksDrawer"- :status="selectedResultStatus"- :plan-check-runs="checksOfSelectedSpec"- />- </div>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import type { ConnectError } from "@connectrpc/connect";-import { CircleQuestionMarkIcon, PlayIcon } from "lucide-vue-next";-import { NButton, NTag, NTooltip } from "naive-ui";-import { computed, ref, watch } from "vue";-import { STATEMENT_SKIP_CHECK_THRESHOLD } from "@/components/SQLCheck/common";-import { planServiceClientConnect } from "@/connect";-import {- extractUserEmail,- pushNotification,- useCurrentProjectV1,- useCurrentUserV1,-} from "@/store";-import { State } from "@/types/proto-es/v1/common_pb";-import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";-import { RunPlanChecksRequestSchema } from "@/types/proto-es/v1/plan_service_pb";-import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";-import { hasProjectPermissionV2 } from "@/utils";-import {- planCheckRunListForSpec,- planSpecHasPlanChecks,- usePlanCheckStatus,- usePlanContext,-} from "../../logic";-import { useResourcePoller } from "../../logic/poller";-import ChecksDrawer from "../ChecksView/ChecksDrawer.vue";-import PlanCheckStatusCount from "../PlanCheckStatusCount.vue";-import { useSelectedSpec } from "../SpecDetailView/context";-import { useSpecSheet } from "../StatementSection/useSpecSheet";--const currentUser = useCurrentUserV1();-const { project } = useCurrentProjectV1();-const { plan, issue, planCheckRuns } = usePlanContext();-const { selectedSpec } = useSelectedSpec();-const { refreshResources } = useResourcePoller();-const { statusCountString } = usePlanCheckStatus(plan);-const { sheet } = useSpecSheet(selectedSpec);--const isRunningChecks = ref(false);-const showChecksDrawer = ref(false);-const selectedResultStatus = ref<Advice_Level>(Advice_Level.SUCCESS);--const shouldShow = computed(() => {- return planSpecHasPlanChecks(selectedSpec.value);-});--const allowRunChecks = computed(() => {- if (plan.value.state === State.DELETED) return false;- if (issue.value && issue.value.status !== IssueStatus.OPEN) return false;- // Once a rollout exists, the plan is frozen — re-running checks produces- // the same result and is misleading for the user.- if (plan.value.hasRollout) return false;- const me = currentUser.value;- if (extractUserEmail(plan.value.creator) === me.email) {- return true;- }- return hasProjectPermissionV2(project.value, "bb.planCheckRuns.run");-});--const checksOfSelectedSpec = computed(() => {- return planCheckRunListForSpec(planCheckRuns.value, selectedSpec.value);-});--const affectedRows = computed(() => {- const summaryReportResults = checksOfSelectedSpec.value.filter((check) =>- check.results.some((result) => result.report.case === "sqlSummaryReport")- );- return summaryReportResults.reduce((acc, check) => {- if (check.results) {- check.results.forEach((result) => {- if (- result.report?.case === "sqlSummaryReport" &&- result.report.value.affectedRows !== undefined- ) {- acc += result.report.value.affectedRows;- }- });- }- return acc;- }, 0n);-});--const isStatementOversized = computed(() => {- if (!sheet.value) return false;- return sheet.value.contentSize > STATEMENT_SKIP_CHECK_THRESHOLD;-});--const runChecks = async () => {- if (!plan.value.name || !selectedSpec.value) return;-- isRunningChecks.value = true;- try {- const request = create(RunPlanChecksRequestSchema, {- name: plan.value.name,- });- await planServiceClientConnect.runPlanChecks(request);-- // After running checks, we need to refresh the plan and plan check runs.- refreshResources(["plan", "planCheckRuns"], true /** force */);-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: "Plan checks started",- });- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: "Failed to run plan checks",- description: (error as ConnectError).message,- });- } finally {- isRunningChecks.value = false;- }-};--const openChecksDrawer = (status: Advice_Level) => {- selectedResultStatus.value = status;- showChecksDrawer.value = true;-};--// Prepare plan check runs.-watch(- [() => selectedSpec.value.id, statusCountString],- async () => {- if (planSpecHasPlanChecks(selectedSpec.value)) {- await refreshResources(["planCheckRuns"], true /** force */);- }- },- {- immediate: true,- }-);-</script>diff --git a/frontend/src/components/Plan/components/PlanCheckSection/index.ts b/frontend/src/components/Plan/components/PlanCheckSection/index.tsdeleted file mode 100644index b84a918147..0000000000--- a/frontend/src/components/Plan/components/PlanCheckSection/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import PlanCheckSection from "./PlanCheckSection.vue";--export default PlanCheckSection;diff --git a/frontend/src/components/Plan/components/PlanCheckStatusCount.vue b/frontend/src/components/Plan/components/PlanCheckStatusCount.vuedeleted file mode 100644index 77ef989ecc..0000000000--- a/frontend/src/components/Plan/components/PlanCheckStatusCount.vue+++ /dev/null@@ -1,145 +0,0 @@-<template>- <div class="flex items-center gap-2" v-if="hasAnyStatus">- <template v-if="displayMode === 'icon'">- <PlanCheckRunStatusIcon- :plan="plan"- :plan-check-runs="planCheckRuns"- :size="size"- />- </template>- <!-- Default display mode: show all status counts with icons -->- <template v-else>- <div class="flex items-center gap-3 flex-wrap">- <div- v-if="statusSummary.running > 0"- class="flex items-center gap-1 text-control"- >- <LoaderIcon :class="iconSizeClass" class="animate-spin" />- <span>{{ $t("task.status.running") }}</span>- </div>- <div- v-if="statusSummary.error > 0"- class="flex items-center gap-1 text-error"- :class="getItemClass(Advice_Level.ERROR)"- @click="handleClick('error')"- >- <XCircleIcon :class="iconSizeClass" />- <span v-if="showLabel">{{ $t("common.error") }}</span>- <span>{{ statusSummary.error }}</span>- </div>- <div- v-if="statusSummary.warning > 0"- class="flex items-center gap-1 text-warning"- :class="getItemClass(Advice_Level.WARNING)"- @click="handleClick('warning')"- >- <AlertCircleIcon :class="iconSizeClass" />- <span v-if="showLabel">{{ $t("common.warning") }}</span>- <span>{{ statusSummary.warning }}</span>- </div>- <div- v-if="statusSummary.success > 0"- class="flex items-center gap-1 text-success"- :class="getItemClass(Advice_Level.SUCCESS)"- @click="handleClick('success')"- >- <CheckCircleIcon :class="iconSizeClass" />- <span v-if="showLabel">{{ $t("common.success") }}</span>- <span>{{ statusSummary.success }}</span>- </div>- </div>- </template>- </div>-</template>--<script setup lang="ts">-import {- AlertCircleIcon,- CheckCircleIcon,- LoaderIcon,- XCircleIcon,-} from "lucide-vue-next";-import { computed, type PropType } from "vue";-import type { Plan, PlanCheckRun } from "@/types/proto-es/v1/plan_service_pb";-import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";-import { useResolvedPlanCheckStatus } from "../logic";-import PlanCheckRunStatusIcon from "./PlanCheckRunStatusIcon.vue";--type DisplayMode = "icon" | "default";-type SizeType = "small" | "normal";--const props = defineProps({- plan: {- required: true,- type: Object as PropType<Plan>,- },- displayMode: {- type: String as PropType<DisplayMode>,- default: "default",- },- size: {- type: String as PropType<SizeType>,- default: "normal",- },- showLabel: {- type: Boolean,- default: false,- },- clickable: {- type: Boolean,- default: false,- },- selectedStatus: {- type: Number as PropType<Advice_Level | undefined>,- default: undefined,- },- planCheckRuns: {- type: Array as PropType<PlanCheckRun[] | undefined>,- default: undefined,- },-});--const emit = defineEmits<{- click: [status: Advice_Level];-}>();--const planCheckRunsRef = computed(() => props.planCheckRuns);--const { statusSummary, hasAnyStatus } = useResolvedPlanCheckStatus(- computed(() => props.plan),- planCheckRunsRef-);--const iconSizeClass = computed(() => {- return props.size === "normal" ? "w-5 h-5" : "w-4 h-4";-});--const handleClick = (statusType: "error" | "warning" | "success") => {- if (!props.clickable) return;-- const statusMap = {- error: Advice_Level.ERROR,- warning: Advice_Level.WARNING,- success: Advice_Level.SUCCESS,- };-- emit("click", statusMap[statusType]);-};--const getItemClass = (status: Advice_Level) => {- const classes: string[] = [];-- if (props.clickable) {- classes.push("cursor-pointer");- }-- if (props.selectedStatus === status) {- classes.push("bg-gray-100 rounded-lg px-2 py-1");- } else if (props.selectedStatus !== undefined) {- // Add some padding to align with selected items- classes.push("px-2 py-1");- }-- return classes;-};-</script>diff --git a/frontend/src/components/Plan/components/RefreshIndicator.vue b/frontend/src/components/Plan/components/RefreshIndicator.vuedeleted file mode 100644index 96b41686ba..0000000000--- a/frontend/src/components/Plan/components/RefreshIndicator.vue+++ /dev/null@@ -1,84 +0,0 @@-<template>- <div class="hidden sm:flex items-center gap-2">- <NTooltip v-if="lastRefreshDisplay && lastRefreshAbsolute">- <template #trigger>- <span class="text-xs text-gray-400">- {{- $t("plan.refresh-indicator.last-refresh", { time: lastRefreshDisplay })- }}- </span>- </template>- <span>{{ lastRefreshAbsolute }}</span>- </NTooltip>- <NButton- class="opacity-60"- size="tiny"- quaternary- :loading="isRefreshing"- :disabled="isRefreshing"- @click="handleRefresh"- >- <template #icon>- <RefreshCcwIcon class="w-3 h-3" />- </template>- <span>{{ $t("common.refresh") }}</span>- </NButton>- </div>-</template>--<script setup lang="ts">-import { RefreshCcwIcon } from "lucide-vue-next";-import { NButton, NTooltip } from "naive-ui";-import { computed, onUnmounted, ref } from "vue";-import { formatAbsoluteDateTime, formatRelativeTime } from "@/utils";-import { useResourcePoller } from "../logic/poller";--const currentTime = ref(Date.now());-const REFRESH_INDICATOR_NOW_THRESHOLD_MS = 3_000;--const resourcePoller = useResourcePoller();--const isRefreshing = computed(() => {- return resourcePoller.isRefreshing.value;-});--// Update current time every second to keep the display fresh-const timer = ref(- setInterval(() => {- currentTime.value = Date.now();- }, 1000)-);--// Clean up timer on unmount-onUnmounted(() => {- clearInterval(timer.value);-});--const lastRefreshTime = computed(() => resourcePoller.lastRefreshTime.value);-const lastRefreshAbsolute = computed(() => {- if (!lastRefreshTime.value) return null;- return formatAbsoluteDateTime(lastRefreshTime.value);-});--const lastRefreshDisplay = computed(() => {- if (!lastRefreshTime.value) return null;-- // Force reactivity by using currentTime (triggers every second)- void currentTime.value;-- const diff = Date.now() - lastRefreshTime.value;- if (diff < 3_600_000) {- return formatRelativeTime(lastRefreshTime.value, {- nowThresholdMs: REFRESH_INDICATOR_NOW_THRESHOLD_MS,- });- }- return formatAbsoluteDateTime(lastRefreshTime.value);-});--const handleRefresh = async () => {- await resourcePoller.refreshResources(- ["issue", "plan", "planCheckRuns", "rollout", "taskRuns"],- true /** force */- );-};-</script>diff --git a/frontend/src/components/Plan/components/SQLCheckSection/AdviceStatusIcon.vue b/frontend/src/components/Plan/components/SQLCheckSection/AdviceStatusIcon.vuedeleted file mode 100644index 0bc7aa7231..0000000000--- a/frontend/src/components/Plan/components/SQLCheckSection/AdviceStatusIcon.vue+++ /dev/null@@ -1,51 +0,0 @@-<template>- <NTooltip>- <template #trigger>- <template v-if="status === Advice_Level.SUCCESS">- <CheckIcon :size="16" class="text-success" />- </template>- <template v-else-if="status === Advice_Level.WARNING">- <TriangleAlertIcon :size="16" class="text-warning" />- </template>- <template v-else-if="status === Advice_Level.ERROR">- <CircleAlertIcon :size="16" class="text-error" />- </template>- <template v-else>- <PlayIcon :size="16" />- </template>- </template>- {{ statusMessage }}- </NTooltip>-</template>--<script setup lang="ts">-import {- CheckIcon,- CircleAlertIcon,- PlayIcon,- TriangleAlertIcon,-} from "lucide-vue-next";-import { NTooltip } from "naive-ui";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";--const props = defineProps<{- status: Advice_Level;-}>();--const { t } = useI18n();--const statusMessage = computed(() => {- switch (props.status) {- case Advice_Level.SUCCESS:- return "Success";- case Advice_Level.WARNING:- return "Warning";- case Advice_Level.ERROR:- return "Error";- default:- return t("issue.sql-check.not-executed-yet");- }-});-</script>diff --git a/frontend/src/components/Plan/components/SQLCheckSection/SQLCheckBadge.vue b/frontend/src/components/Plan/components/SQLCheckSection/SQLCheckBadge.vuedeleted file mode 100644index da70a53eb8..0000000000--- a/frontend/src/components/Plan/components/SQLCheckSection/SQLCheckBadge.vue+++ /dev/null@@ -1,93 +0,0 @@-<template>- <NTag- :class="[clickable && 'cursor-pointer']"- :type="tagType"- round- @click="handleClick"- >- <template #icon>- <template v-if="status === 'RUNNING'">- <TaskSpinner class="h-4 w-4 text-info" />- </template>- <template v-else-if="status === 'SUCCESS'">- <CheckIcon :size="16" class="text-success" />- </template>- <template v-else-if="status === 'WARNING'">- <TriangleAlertIcon :size="16" />- </template>- <template v-else-if="status === 'ERROR'">- <CircleAlertIcon :size="16" />- </template>- </template>- <span>{{ $t("task.check-type.sql-review.self") }}</span>- </NTag>-- <SQLCheckPanel- v-if="showDetailPanel"- :project="project.name"- :database="database as Database"- :advices="advices"- @close="showDetailPanel = false"- />-</template>--<script setup lang="ts">-import { CheckIcon, CircleAlertIcon, TriangleAlertIcon } from "lucide-vue-next";-import { NTag } from "naive-ui";-import { computed, ref } from "vue";-import TaskSpinner from "@/components/misc/TaskSpinner.vue";-import { SQLCheckPanel } from "@/components/SQLCheck";-import type { Database } from "@/types/proto-es/v1/database_service_pb";-import type { Advice } from "@/types/proto-es/v1/sql_service_pb";-import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";-import { usePlanSQLCheckContext } from "./context";--const props = defineProps<{- advices: Advice[];- isRunning?: boolean;-}>();--defineEmits<{- (event: "click"): void;-}>();--const { database, project } = usePlanSQLCheckContext();-const showDetailPanel = ref(false);--const status = computed(() => {- const { isRunning, advices } = props;- if (isRunning) {- return "RUNNING";- }- if (advices.some((adv) => adv.status === Advice_Level.ERROR)) {- return "ERROR";- }- if (advices.some((adv) => adv.status === Advice_Level.WARNING)) {- return "WARNING";- }- return "SUCCESS";-});--const clickable = computed(() => {- return status.value === "ERROR" || status.value === "WARNING";-});--const tagType = computed(() => {- switch (status.value) {- case "SUCCESS":- return "default";- case "RUNNING":- return "info";- case "WARNING":- return "warning";- case "ERROR":- return "error";- }- // Should not reach here.- return "default";-});--const handleClick = () => {- showDetailPanel.value = true;-};-</script>diff --git a/frontend/src/components/Plan/components/SQLCheckSection/SQLCheckButton.vue b/frontend/src/components/Plan/components/SQLCheckSection/SQLCheckButton.vuedeleted file mode 100644index 3aef6a557f..0000000000--- a/frontend/src/components/Plan/components/SQLCheckSection/SQLCheckButton.vue+++ /dev/null@@ -1,196 +0,0 @@-<template>- <NPopover :disabled="statementErrors.length === 0" to="body">- <template #trigger>- <NButton- style="--n-padding: 0 14px 0 10px"- :disabled="statementErrors.length > 0"- :style="buttonStyle"- tag="div"- size="small"- @click="handleButtonClick"- >- <template #icon>- <BBSpin v-if="isRunning" :size="20" />- <heroicons-outline:play v-else class="w-4 h-4" />- </template>- <template #default>- <template v-if="isRunning">- {{ $t("task.checking") }}- </template>- <template v-else>- {{ $t("task.run-checks") }}- </template>- </template>- </NButton>- </template>- <template #default>- <ErrorList :errors="statementErrors" />- </template>- </NPopover>-- <SQLCheckPanel- v-if="checkResult && advices && showDetailPanel"- :project="project.name"- :database="database as Database"- :advices="advices"- :affected-rows="checkResult.affectedRows"- :risk-level="checkResult.riskLevel"- :confirm="confirmDialog"- :override-title="$t('issue.sql-check.sql-review-violations')"- :show-code-location="showCodeLocation"- :allow-force-continue="allowForceContinue"- @close="onPanelClose"- >- <template #row-title-extra="{ row }">- <slot name="row-title-extra" :row="row" :confirm="confirmDialog" />- </template>- </SQLCheckPanel>-</template>--<script lang="ts" setup>-import { create } from "@bufbuild/protobuf";-import { asyncComputed } from "@vueuse/core";-import { NButton, NPopover } from "naive-ui";-import { computed, ref } from "vue";-import { useI18n } from "vue-i18n";-import { BBSpin } from "@/bbkit";-import ErrorList from "@/components/misc/ErrorList.vue";-import { SQLCheckPanel } from "@/components/SQLCheck";-import { STATEMENT_SKIP_CHECK_THRESHOLD } from "@/components/SQLCheck/common";-import { releaseServiceClientConnect } from "@/connect";-import type { Database } from "@/types/proto-es/v1/database_service_pb";-import type { CheckReleaseResponse } from "@/types/proto-es/v1/release_service_pb";-import {- CheckReleaseRequestSchema,- CheckReleaseResponseSchema,- Release_Type,-} from "@/types/proto-es/v1/release_service_pb";-import {- Advice_Level,- AdviceSchema,- Advice_Level as ProtoESAdvice_Level,-} from "@/types/proto-es/v1/sql_service_pb";-import type { Defer, VueStyle } from "@/utils";-import { defer } from "@/utils";-import { useSpecSheet } from "../StatementSection/useSpecSheet";-import { usePlanSQLCheckContext } from "./context";--withDefaults(- defineProps<{- buttonStyle?: VueStyle;- showCodeLocation?: boolean;- }>(),- {- buttonStyle: undefined,- showCodeLocation: undefined,- }-);--const { t } = useI18n();-const { database, project, selectedSpec, upsertResult } =- usePlanSQLCheckContext();-const { sheetStatement } = useSpecSheet(computed(() => selectedSpec.value));--const isRunning = ref(false);-const showDetailPanel = ref(false);-const allowForceContinue = ref(true);-const confirmDialog = ref<Defer<boolean>>();-const checkResult = ref<CheckReleaseResponse | undefined>();--const advices = computed(() => {- return checkResult.value?.results.flatMap((r) => r.advices);-});--const statementErrors = asyncComputed(async () => {- if (sheetStatement.value.length === 0) {- return [t("issue.sql-check.statement-is-required")];- }- if (new Blob([sheetStatement.value]).size > STATEMENT_SKIP_CHECK_THRESHOLD) {- return [t("issue.sql-check.statement-is-too-large")];- }- return [];-}, []);--const runCheckInternal = async (statement: string) => {- const request = create(CheckReleaseRequestSchema, {- parent: project.value.name,- release: {- type: Release_Type.VERSIONED,- files: [- {- // Use "0" for dummy version.- version: "0",- // Ghost directive (-- ghost = {...}) is embedded in the statement if enabled- statement: new TextEncoder().encode(statement),- },- ],- },- targets: [database.value.name],- });- const response = await releaseServiceClientConnect.checkRelease(request);- return response;-};--const handleButtonClick = async () => {- await runChecks();-- if (hasError.value) {- const d = defer<boolean>();- d.promise.finally(onPanelClose);- showDetailPanel.value = true;- return d.promise;- }-};--const runChecks = async () => {- if (statementErrors.value.length > 0) {- return;- }-- const handleErrors = (errors: string[]) => {- // Mock the pre-check errors to advices.- checkResult.value = create(CheckReleaseResponseSchema, {- results: [- {- advices: errors.map((err) =>- create(AdviceSchema, {- title: "Pre check",- status: ProtoESAdvice_Level.WARNING,- content: err,- })- ),- },- ],- });- isRunning.value = false;- };-- isRunning.value = true;- if (new Blob([sheetStatement.value]).size > STATEMENT_SKIP_CHECK_THRESHOLD) {- return handleErrors([t("issue.sql-check.statement-is-too-large")]);- }- try {- checkResult.value = await runCheckInternal(sheetStatement.value);- // Upsert the result to the map.- for (const r of checkResult.value.results || []) {- // target is the database name.- upsertResult(r.target, r);- }- } finally {- isRunning.value = false;- }-};--const onPanelClose = () => {- showDetailPanel.value = false;- confirmDialog.value = undefined;-};--const hasError = computed(() => {- return advices.value?.some(- (advice) =>- advice.status === Advice_Level.ERROR ||- advice.status === Advice_Level.WARNING- );-});-</script>diff --git a/frontend/src/components/Plan/components/SQLCheckSection/SQLCheckSection.vue b/frontend/src/components/Plan/components/SQLCheckSection/SQLCheckSection.vuedeleted file mode 100644index 27489420bd..0000000000--- a/frontend/src/components/Plan/components/SQLCheckSection/SQLCheckSection.vue+++ /dev/null@@ -1,56 +0,0 @@-<template>- <div class="w-full flex items-center gap-x-4 px-4 py-2">- <div class="textlabel h-6.5 inline-flex items-center">- {{ $t("issue.sql-check.sql-checks") }}- </div>- <div- v-if="isValidDatabaseName(database.name)"- class="grow flex flex-row items-center justify-between gap-2"- >- <span v-if="checkResult === undefined" class="textinfolabel">- {{ $t("issue.sql-check.not-executed-yet") }}- </span>- <div v-else class="flex flex-row justify-start items-center gap-2">- <SQLCheckBadge :advices="checkResult.advices" />- <NTooltip- v-if="checkResult.affectedRows > 0"- style="max-width: 20rem"- >- <template #trigger>- <NTag round>- <span class="opacity-80"- >{{ $t("task.check-type.affected-rows.self") }}:- </span>- <span>{{ checkResult.affectedRows }}</span>- </NTag>- </template>- {{ $t("task.check-type.affected-rows.description") }}- </NTooltip>- </div>-- <SQLCheckButton- :key="database.name"- button-style="--n-padding: 0 8px 0 6px; --n-icon-margin: 3px;"- :show-code-location="true"- />- </div>- </div>-</template>--<script lang="ts" setup>-import { NTag, NTooltip } from "naive-ui";-import { computed } from "vue";-import { isValidDatabaseName } from "@/types";-import { usePlanSQLCheckContext } from "./context";-import SQLCheckBadge from "./SQLCheckBadge.vue";-import SQLCheckButton from "./SQLCheckButton.vue";--const { database, resultMap } = usePlanSQLCheckContext();--const checkResult = computed(() => {- const result = resultMap.value[database.value.name] || undefined;- if (!result) return undefined;-- return result;-});-</script>diff --git a/frontend/src/components/Plan/components/SQLCheckSection/context.ts b/frontend/src/components/Plan/components/SQLCheckSection/context.tsdeleted file mode 100644index 9383b0c8a1..0000000000--- a/frontend/src/components/Plan/components/SQLCheckSection/context.ts+++ /dev/null@@ -1,54 +0,0 @@-import type { InjectionKey, Ref } from "vue";-import { computed, inject, provide, ref } from "vue";-import { unknownDatabase } from "@/types";-import type { Plan, Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";-import type { Project } from "@/types/proto-es/v1/project_service_pb";-import type { CheckReleaseResponse_CheckResult } from "@/types/proto-es/v1/release_service_pb";-import type { Task } from "@/types/proto-es/v1/rollout_service_pb";-import { databaseForTask } from "@/utils";-import { databaseForSpec } from "../../logic";--export const KEY = Symbol(- "bb.plan.context.sql-checks"-) as InjectionKey<SQLCheckContext>;--export const usePlanSQLCheckContext = () => {- return inject(KEY)!;-};--export const providePlanSQLCheckContext = (refs: {- project: Ref<Project>;- plan: Ref<Plan>;- selectedSpec: Ref<Plan_Spec>;- selectedTask?: Ref<Task | undefined>;-}) => {- const resultMap = ref<Record<string, CheckReleaseResponse_CheckResult>>({});- const { project, plan, selectedSpec, selectedTask } = refs;-- const database = computed(() => {- if (selectedTask?.value) {- return databaseForTask(project.value, selectedTask.value);- } else if (selectedSpec.value) {- // TODO(steven): handle db group as target in spec.- return databaseForSpec(project.value, selectedSpec.value);- }- return unknownDatabase();- });-- const context = {- project,- plan,- database,- selectedSpec,- resultMap,- upsertResult: (key: string, result: CheckReleaseResponse_CheckResult) => {- resultMap.value[key] = result;- },- };-- provide(KEY, context);-- return context;-};--type SQLCheckContext = ReturnType<typeof providePlanSQLCheckContext>;diff --git a/frontend/src/components/Plan/components/SQLCheckSection/index.ts b/frontend/src/components/Plan/components/SQLCheckSection/index.tsdeleted file mode 100644index cbb34091bb..0000000000--- a/frontend/src/components/Plan/components/SQLCheckSection/index.ts+++ /dev/null@@ -1,6 +0,0 @@-import SQLCheckSection from "./SQLCheckSection.vue";-import { providePlanSQLCheckContext } from "./context";--export default SQLCheckSection;--export { providePlanSQLCheckContext };diff --git a/frontend/src/components/Plan/components/SQLCheckV1Section/SQLCheckV1Section.vue b/frontend/src/components/Plan/components/SQLCheckV1Section/SQLCheckV1Section.vuedeleted file mode 100644index cbe7a86414..0000000000--- a/frontend/src/components/Plan/components/SQLCheckV1Section/SQLCheckV1Section.vue+++ /dev/null@@ -1,330 +0,0 @@-<template>- <div v-if="show" class="flex flex-col gap-y-2">- <!-- Row 1: Title + Run button -->- <div class="flex items-center justify-between gap-2">- <div class="flex flex-row items-center gap-2">- <h3 class="textlabel uppercase">{{ $t("plan.checks.self") }}</h3>- </div>- <NButton- size="tiny"- :loading="isRunningChecks"- :disabled="statement.length === 0"- @click="runChecks"- >- <template #icon>- <PlayIcon class="w-4 h-4" />- </template>- {{ $t("plan.run") }}- </NButton>- </div>-- <!-- Row 2: Status badges -->- <div class="flex items-center flex-wrap gap-3 text-sm min-w-0">- <button- v-if="summary.error > 0"- class="flex items-center gap-1 hover:opacity-80"- @click="openDrawer('ERROR')"- >- <XCircleIcon class="w-4 h-4 text-error" />- <span class="text-error">{{ $t("common.error") }}</span>- <span class="text-error font-medium">{{ summary.error }}</span>- </button>- <button- v-if="summary.warning > 0"- class="flex items-center gap-1 hover:opacity-80"- @click="openDrawer('WARNING')"- >- <AlertCircleIcon class="w-4 h-4 text-warning" />- <span class="text-warning">{{ $t("common.warning") }}</span>- <span class="text-warning font-medium">{{ summary.warning }}</span>- </button>- <span- v-if="- !isNullOrUndefined(checkResults) &&- summary.error === 0 &&- summary.warning === 0- "- class="flex items-center gap-1"- >- <CheckCircleIcon class="w-4 h-4 text-success" />- <span class="text-success">{{ $t("common.success") }}</span>- </span>-- <NTooltip- v-if="checkResults && affectedRows > 0"- style="max-width: 20rem"- >- <template #trigger>- <NTag round :bordered="false">- <div class="flex items-center gap-1">- <span class="text-sm text-control-light">{{- $t("task.check-type.affected-rows.self")- }}</span>- <span class="text-sm">- {{ affectedRows }}- </span>- <CircleQuestionMarkIcon- class="size-3.5 text-control-light opacity-80"- />- </div>- </NTag>- </template>- {{ $t("task.check-type.affected-rows.description") }}- </NTooltip>- </div>-- <!-- Checks Drawer -->- <Drawer v-model:show="drawerVisible">- <DrawerContent- :title="$t('plan.navigator.checks')"- class="w-[40rem] max-w-[100vw] relative"- >- <ChecksView- :default-status="getDefaultStatus()"- :plan-check-runs="formattedCheckRuns"- :is-loading="isRunningChecks"- />- </DrawerContent>- </Drawer>- </div>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import {- AlertCircleIcon,- CheckCircleIcon,- CircleQuestionMarkIcon,- PlayIcon,- XCircleIcon,-} from "lucide-vue-next";-import { NButton, NTag, NTooltip } from "naive-ui";-import { computed, ref, watch } from "vue";-import { getLocalSheetByName } from "@/components/Plan";-import Drawer from "@/components/v2/Container/Drawer.vue";-import DrawerContent from "@/components/v2/Container/DrawerContent.vue";-import { releaseServiceClientConnect } from "@/connect";-import { projectNamePrefix } from "@/store";-import {- type PlanCheckRun,- type PlanCheckRun_Result,- PlanCheckRun_Result_Type,- PlanCheckRun_ResultSchema,- PlanCheckRun_Status,- PlanCheckRunSchema,-} from "@/types/proto-es/v1/plan_service_pb";-import {- CheckReleaseRequestSchema,- type CheckReleaseResponse_CheckResult,- Release_Type,-} from "@/types/proto-es/v1/release_service_pb";-import { type Advice, Advice_Level } from "@/types/proto-es/v1/sql_service_pb";-import {- extractProjectResourceName,- getSheetStatement,- isNullOrUndefined,-} from "@/utils";-import { usePlanContext } from "../../logic/context";-import { targetsForSpec } from "../../logic/plan";-import ChecksView from "../ChecksView/ChecksView.vue";-import { useSelectedSpec } from "../SpecDetailView/context";--const { plan } = usePlanContext();-const { selectedSpec } = useSelectedSpec();--const isRunningChecks = ref(false);-const drawerVisible = ref(false);-const selectedStatus = ref<"ERROR" | "WARNING" | "SUCCESS">("ERROR");-const checkResults = ref<CheckReleaseResponse_CheckResult[] | undefined>(- undefined-);--const statement = computed(() => {- if (!selectedSpec.value) return "";- const config =- selectedSpec.value.config?.case === "changeDatabaseConfig"- ? selectedSpec.value.config.value- : undefined;- if (!config) return "";- const sheet = getLocalSheetByName(config.sheet);- return getSheetStatement(sheet);-});--const show = computed(() => {- if (!selectedSpec.value) {- return false;- }- // Show for change database configs- return selectedSpec.value.config?.case === "changeDatabaseConfig";-});--// Enhanced advice type with target information-type AdviceWithTarget = Advice & {- target: string;-};--const allAdvices = computed(() => {- if (!checkResults.value) {- return [];- }- const advices: AdviceWithTarget[] = [];- for (const result of checkResults.value) {- for (const advice of result.advices) {- advices.push({- ...advice,- target: result.target,- });- }- }- return advices;-});--const summary = computed(() => {- const result = { success: 0, warning: 0, error: 0 };-- for (const advice of allAdvices.value) {- if (advice.status === Advice_Level.ERROR) {- result.error++;- } else if (advice.status === Advice_Level.WARNING) {- result.warning++;- } else if (advice.status === Advice_Level.SUCCESS) {- result.success++;- }- }-- return result;-});--const runChecks = async () => {- if (!plan.value.name || !selectedSpec.value) return;-- const config =- selectedSpec.value.config?.case === "changeDatabaseConfig"- ? selectedSpec.value.config.value- : undefined;- if (!config) return;-- isRunningChecks.value = true;- try {- // Get the statement from the sheet- const sheetName = config.sheet;- const sheet = getLocalSheetByName(sheetName);- const statement = getSheetStatement(sheet);-- // Get targets- const targets = targetsForSpec(selectedSpec.value);-- // Run check for all targets- // Ghost directive (-- ghost = {...}) is embedded in the statement if enabled- const request = create(CheckReleaseRequestSchema, {- parent: `${projectNamePrefix}${extractProjectResourceName(plan.value.name)}`,- release: {- type: Release_Type.VERSIONED,- files: [- {- // Use "0" for dummy version.- version: "0",- statement: new TextEncoder().encode(statement),- },- ],- },- targets,- });- const response = await releaseServiceClientConnect.checkRelease(request);- checkResults.value = response.results || [];- } finally {- isRunningChecks.value = false;- }-};--const affectedRows = computed(() => {- if (!checkResults.value) return 0n;- return checkResults.value.reduce((acc, result) => {- return acc + result.affectedRows;- }, 0n);-});--const openDrawer = (status: "ERROR" | "WARNING" | "SUCCESS") => {- selectedStatus.value = status;- drawerVisible.value = true;-};--// Convert string status to Advice_Level-const getDefaultStatus = (): Advice_Level | undefined => {- switch (selectedStatus.value) {- case "ERROR":- return Advice_Level.ERROR;- case "WARNING":- return Advice_Level.WARNING;- case "SUCCESS":- return Advice_Level.SUCCESS;- default:- return undefined;- }-};--watch(- () => selectedSpec.value.id,- () => {- // Reset drawer and results when spec changes.- drawerVisible.value = false;- checkResults.value = undefined;- },- {- immediate: true,- }-);--// Transform CheckReleaseResponse_CheckResult[] to PlanCheckRun[] format-// With consolidated model, we create a single PlanCheckRun with all results-const transformToFormattedCheckRuns = (- results: CheckReleaseResponse_CheckResult[]-): PlanCheckRun[] => {- const allResults: PlanCheckRun_Result[] = [];-- for (const result of results) {- for (const advice of result.advices) {- allResults.push(- create(PlanCheckRun_ResultSchema, {- status:- advice.status === Advice_Level.ERROR- ? Advice_Level.ERROR- : advice.status === Advice_Level.WARNING- ? Advice_Level.WARNING- : Advice_Level.SUCCESS,- title: advice.title,- content: advice.content,- code: advice.code,- target: result.target,- type: PlanCheckRun_Result_Type.STATEMENT_ADVISE,- report: {- case: "sqlReviewReport",- value: {- startPosition: advice.startPosition,- },- },- })- );- }- }-- if (allResults.length === 0) {- return [];- }-- return [- create(PlanCheckRunSchema, {- name: "check-run-0",- status: PlanCheckRun_Status.DONE,- results: allResults,- createTime: { seconds: BigInt(Math.floor(Date.now() / 1000)), nanos: 0 },- }),- ];-};--// Format check runs for ChecksView component-const formattedCheckRuns = computed(() => {- if (!checkResults.value) return [];- return transformToFormattedCheckRuns(checkResults.value);-});-</script>diff --git a/frontend/src/components/Plan/components/SQLCheckV1Section/index.ts b/frontend/src/components/Plan/components/SQLCheckV1Section/index.tsdeleted file mode 100644index 428fdd998a..0000000000--- a/frontend/src/components/Plan/components/SQLCheckV1Section/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import SQLCheckV1Section from "./SQLCheckV1Section.vue";--export default SQLCheckV1Section;diff --git a/frontend/src/components/Plan/components/SpecDetailView/AllTargetsDrawer.vue b/frontend/src/components/Plan/components/SpecDetailView/AllTargetsDrawer.vuedeleted file mode 100644index c0575739fb..0000000000--- a/frontend/src/components/Plan/components/SpecDetailView/AllTargetsDrawer.vue+++ /dev/null@@ -1,168 +0,0 @@-<template>- <Drawer :show="show" width="auto" @update:show="$emit('update:show', $event)">- <DrawerContent- :title="`${$t('plan.targets.title')} (${targets.length})`"- :closable="true"- class="w-200 max-w-[100vw] relative"- >- <template #default>- <div class="w-full h-full flex flex-col gap-y-4">- <!-- Search bar -->- <div class="px-4">- <SearchBox- v-model:value="state.searchText"- :placeholder="$t('common.search')"- />- </div>-- <!-- Targets list -->- <div class="flex-1 px-4 pb-4 overflow-hidden">- <div- v-if="state.isLoading"- class="flex items-center justify-center h-full"- >- <BBSpin />- </div>- <div- v-else-if="filteredTargets.length > 0"- class="h-full overflow-y-auto"- >- <div class="flex flex-wrap gap-2">- <div- v-for="target in filteredTargets"- :key="target"- class="inline-flex items-center gap-x-1 px-2 py-1 border rounded-lg transition-all cursor-default"- >- <template v-if="isValidDatabaseName(target)">- <DatabaseDisplay :database="target" show-environment />- </template>- <template v-else-if="isValidDatabaseGroupName(target)">- <DatabaseGroupTargetDisplay :target="target" />- </template>- <template v-else>- <!-- Unknown resource -->- <span class="text-sm">{{ target }}</span>- </template>- </div>- </div>- </div>- <div- v-else- class="flex items-center justify-center h-full text-control-light"- >- {{ $t("common.no-data") }}- </div>- </div>- </div>- </template>- </DrawerContent>- </Drawer>-</template>--<script setup lang="ts">-import { computed, reactive, watch } from "vue";-import { BBSpin } from "@/bbkit";-import { Drawer, DrawerContent, SearchBox } from "@/components/v2";-import { useDatabaseV1Store, useDBGroupStore } from "@/store";-import { isValidDatabaseGroupName, isValidDatabaseName } from "@/types";-import { extractDatabaseResourceName } from "@/utils";-import DatabaseDisplay from "../common/DatabaseDisplay.vue";-import { useSelectedSpec } from "./context";-import DatabaseGroupTargetDisplay from "./DatabaseGroupTargetDisplay.vue";--interface Props {- show: boolean;- targets: string[];-}--interface LocalState {- searchText: string;- isLoading: boolean;-}--const props = defineProps<Props>();-defineEmits<{- "update:show": [show: boolean];-}>();--const databaseStore = useDatabaseV1Store();-const dbGroupStore = useDBGroupStore();-const { getDatabaseTargets } = useSelectedSpec();--const state = reactive<LocalState>({- searchText: "",- isLoading: false,-});--const filteredTargets = computed(() => {- if (!state.searchText) {- return props.targets;- }-- const searchText = state.searchText.toLowerCase();- return props.targets.filter((target: string) => {- if (isValidDatabaseName(target)) {- const db = databaseStore.getDatabaseByName(target);- return extractDatabaseResourceName(db.name)- .databaseName.toLowerCase()- .includes(searchText);- }- return (target as string).toLocaleLowerCase().includes(searchText);- });-});--const loadAllTargets = async () => {- if (props.targets.length === 0) {- return;- }-- state.isLoading = true;-- try {- // Separate different types of targets for optimized fetching- const { databaseTargets, dbGroupTargets } = await getDatabaseTargets(- props.targets- );-- // Batch fetch all targets- const fetchPromises: Promise<unknown>[] = [];-- if (databaseTargets.length > 0) {- fetchPromises.push(- databaseStore.batchGetOrFetchDatabases(databaseTargets)- );- }-- const dbGroupPromises = dbGroupTargets.map((target) =>- dbGroupStore.getOrFetchDBGroupByName(target)- );- fetchPromises.push(...dbGroupPromises);-- await Promise.allSettled(fetchPromises);- } catch (error) {- console.error("Failed to load targets:", error);- } finally {- state.isLoading = false;- }-};--watch(- () => props.show,- async (show) => {- if (show) {- state.searchText = "";- }- }-);--// Load all targets when drawer opens-watch(- () => props.show,- async (show) => {- if (show) {- await loadAllTargets();- }- },- { once: true }-);-</script>diff --git a/frontend/src/components/Plan/components/SpecDetailView/DataExportOptionsSection.vue b/frontend/src/components/Plan/components/SpecDetailView/DataExportOptionsSection.vuedeleted file mode 100644index 5614462f55..0000000000--- a/frontend/src/components/Plan/components/SpecDetailView/DataExportOptionsSection.vue+++ /dev/null@@ -1,68 +0,0 @@-<template>- <div class="w-full flex flex-col gap-y-4">- <LimitsSection />- <div class="w-full">- <div class="flex items-center justify-between mb-2">- <span class="text-base">{{ $t("issue.data-export.options") }}</span>- </div>-- <div class="flex flex-col gap-y-3">- <!-- Export Format -->- <div class="flex items-center gap-4">- <span class="text-sm">{{ $t("export-data.export-format") }}</span>- <ExportFormatSelector- v-model:format="exportFormat"- :editable="isCreating"- />- </div>-- <!-- Password Protection -->- <ExportPasswordInputer- v-model:password="exportPassword"- :editable="isCreating"- />- </div>- </div>- </div>-</template>--<script setup lang="ts">-import { computed } from "vue";-import LimitsSection from "@/components/Plan/components/IssueReviewView/DatabaseExportView/LimitsSection.vue";-import { ExportFormat } from "@/types/proto-es/v1/common_pb";-import { usePlanContext } from "../../logic/context";-import ExportFormatSelector from "../ExportOption/ExportFormatSelector.vue";-import ExportPasswordInputer from "../ExportOption/ExportPasswordInputer.vue";-import { useSelectedSpec } from "./context";--const { isCreating } = usePlanContext();-const { selectedSpec } = useSelectedSpec();--const exportFormat = computed({- get() {- if (selectedSpec.value.config.case === "exportDataConfig") {- return selectedSpec.value.config.value.format || ExportFormat.JSON;- }- return ExportFormat.JSON;- },- set(value) {- if (selectedSpec.value.config.case === "exportDataConfig") {- selectedSpec.value.config.value.format = value;- }- },-});--const exportPassword = computed({- get() {- if (selectedSpec.value.config.case === "exportDataConfig") {- return selectedSpec.value.config.value.password || "";- }- return "";- },- set(value) {- if (selectedSpec.value.config.case === "exportDataConfig") {- selectedSpec.value.config.value.password = value || undefined;- }- },-});-</script>diff --git a/frontend/src/components/Plan/components/SpecDetailView/DatabaseGroupTargetDisplay.vue b/frontend/src/components/Plan/components/SpecDetailView/DatabaseGroupTargetDisplay.vuedeleted file mode 100644index f00f9cf925..0000000000--- a/frontend/src/components/Plan/components/SpecDetailView/DatabaseGroupTargetDisplay.vue+++ /dev/null@@ -1,146 +0,0 @@-<template>- <div class="flex flex-col gap-2 w-full">- <!-- Database group header -->- <div class="flex items-center gap-x-2">- <DatabaseGroupIcon class="w-5 h-5 text-control shrink-0" />- <NTag size="small" round>- {{ $t("common.database-group") }}- </NTag>- <DatabaseGroupName- :database-group="dbGroupStore.getDBGroupByName(target)"- :link="false"- :plain="true"- />- <!-- Only show external link if the database group still exists -->- <div- v-if="showExternalLink && isValidDatabaseGroupName(dbGroupStore.getDBGroupByName(target).name)"- class="flex items-center cursor-pointer opacity-60 hover:opacity-100"- @click="gotoDatabaseGroupDetailPage"- >- <ExternalLinkIcon class="w-4 h-auto" />- </div>- </div>- <!-- Database children - flat layout -->- <div- v-if="databases.length > 0"- class="flex flex-wrap items-center gap-2 pl-7"- >- <div- v-for="db in databases.slice(0, MAX_INLINE_DATABASES)"- :key="db"- class="inline-flex items-center gap-x-1 px-2 py-1 border rounded-lg transition-all cursor-default bg-gray-50"- >- <DatabaseDisplay :database="db" size="small" show-environment />- </div>- <NPopover- v-if="databases.length > MAX_INLINE_DATABASES"- placement="bottom"- >- <template #trigger>- <span class="text-xs text-accent cursor-pointer">- {{ $t("common.n-more", { n: databases.length - MAX_INLINE_DATABASES }) }}- </span>- </template>- <NVirtualList- class="max-h-64"- :item-size="24"- :items="extraDatabaseItems"- :key-field="'key'"- >- <template #default="{ item }">- <div class="py-1">- <DatabaseDisplay- :database="item.value"- size="small"- show-environment- />- </div>- </template>- </NVirtualList>- </NPopover>- </div>- </div>-</template>--<script setup lang="ts">-import { ExternalLinkIcon } from "lucide-vue-next";-import { NPopover, NTag, NVirtualList } from "naive-ui";-import { computed, ref, watchEffect } from "vue";-import { useRouter } from "vue-router";-import DatabaseGroupIcon from "@/components/DatabaseGroupIcon.vue";-import DatabaseGroupName from "@/components/v2/Model/DatabaseGroupName.vue";-import { PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL } from "@/router/dashboard/projectV1";-import {- getProjectNameAndDatabaseGroupName,- useDatabaseV1Store,- useDBGroupStore,-} from "@/store";-import { isValidDatabaseGroupName } from "@/types";-import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";-import DatabaseDisplay from "../common/DatabaseDisplay.vue";--const MAX_INLINE_DATABASES = 5;--const props = withDefaults(- defineProps<{- target: string;- showExternalLink?: boolean;- }>(),- {- showExternalLink: true,- }-);--const router = useRouter();-const dbGroupStore = useDBGroupStore();-const dbStore = useDatabaseV1Store();--const databases = ref<string[]>([]);--// Fetch database group and populate databases-watchEffect(async () => {- const cached = dbGroupStore.getDBGroupByName(props.target);- if (!isValidDatabaseGroupName(cached.name)) {- databases.value = [];- return;- }-- try {- const dbGroup = await dbGroupStore.getOrFetchDBGroupByName(props.target, {- view: DatabaseGroupView.FULL,- silent: true,- });- const matchedDatabases =- dbGroup.matchedDatabases?.map((db) => db.name) ?? [];- databases.value = matchedDatabases;-- // Fetch matched databases so DatabaseDisplay can show environment- if (matchedDatabases.length > 0) {- await dbStore.batchGetOrFetchDatabases(matchedDatabases);- }- } catch {- databases.value = [];- }-});--const extraDatabaseItems = computed(() => {- return databases.value.slice(MAX_INLINE_DATABASES).map((db) => ({- key: db,- value: db,- }));-});--const gotoDatabaseGroupDetailPage = () => {- const [projectId, databaseGroupName] = getProjectNameAndDatabaseGroupName(- props.target- );- const url = router.resolve({- name: PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,- params: {- projectId,- databaseGroupName,- },- }).fullPath;- window.open(url, "_blank");-};-</script>diff --git a/frontend/src/components/Plan/components/SpecDetailView/FailedTaskRunsSection.vue b/frontend/src/components/Plan/components/SpecDetailView/FailedTaskRunsSection.vuedeleted file mode 100644index a0d3174f52..0000000000--- a/frontend/src/components/Plan/components/SpecDetailView/FailedTaskRunsSection.vue+++ /dev/null@@ -1,280 +0,0 @@-<template>- <div v-if="shouldShowSection" class="w-full flex flex-col gap-y-2 py-3">- <div class="text-sm text-control">- {{ $t("task-run.failed-runs") }}- </div>- <div v-if="isLoading" class="flex items-center justify-center py-4">- <div class="text-sm text-control-light">Loading task runs...</div>- </div>- <NDataTable- v-else-if="taskRunList.length > 0"- size="small"- :row-key="rowKey"- :columns="columnList"- :data="taskRunList"- :max-height="400"- :row-props="rowProps"- :pagination="- taskRunList.length > DEFAULT_TASK_RUNS_PER_PAGE- ? {- page: currentPage,- pageSize: DEFAULT_TASK_RUNS_PER_PAGE,- showSizePicker: false,- itemCount: taskRunList.length,- simple: false,- size: 'small',- onUpdatePage: (page: number) => {- currentPage = page;- },- }- : false- "- />- <div v-else class="text-sm text-control-light py-4">- No task runs found.- </div>- <Drawer v-model:show="taskRunDetailContext.show">- <DrawerContent- :title="$t('common.detail')"- class="max-w-[calc(100vw-2rem)]"- >- <TaskRunDetail- v-if="taskRunDetailContext.taskRun && selectedDatabase"- :key="taskRunDetailContext.taskRun.name"- :task-run="taskRunDetailContext.taskRun"- :database="selectedDatabase"- />- </DrawerContent>- </Drawer>- </div>-</template>--<script lang="tsx" setup>-import { ExternalLinkIcon } from "lucide-vue-next";-import { type DataTableColumn, NButton, NDataTable } from "naive-ui";-import { computed, reactive, ref, watchEffect } from "vue";-import { useI18n } from "vue-i18n";-import { useRouter } from "vue-router";-import HumanizeDate from "@/components/misc/HumanizeDate.vue";-import TaskRunComment from "@/components/RolloutV1/components/TaskRun/TaskRunComment.vue";-import TaskRunDetail from "@/components/RolloutV1/components/TaskRun/TaskRunDetail.vue";-import TaskRunStatusIcon from "@/components/RolloutV1/components/TaskRun/TaskRunStatusIcon.vue";-import { Drawer, DrawerContent } from "@/components/v2";-import { buildTaskDetailRoute } from "@/router/dashboard/projectV1RouteHelpers";-import { useDatabaseV1Store } from "@/store";-import { useTaskRunLogStore } from "@/store/modules/v1/taskRunLog";-import { getDateForPbTimestampProtoEs } from "@/types";-import {- Task_Status,- type TaskRun,- TaskRun_Status,-} from "@/types/proto-es/v1/rollout_service_pb";-import { extractTaskUID, flattenTaskV1List } from "@/utils";-import { usePlanContextWithRollout } from "../../logic";-import DatabaseDisplay from "../common/DatabaseDisplay.vue";-import { useSelectedSpec } from "./context";--const DEFAULT_TASK_RUNS_PER_PAGE = 5;--const { t } = useI18n();-const router = useRouter();-const { rollout, taskRuns } = usePlanContextWithRollout();-const { selectedSpec } = useSelectedSpec();-const databaseStore = useDatabaseV1Store();-const taskRunLogStore = useTaskRunLogStore();--// Pagination state-const currentPage = ref(1);--const taskRunDetailContext = reactive<{- show: boolean;- taskRun?: TaskRun;-}>({- show: false,-});--const failedSpecTasks = computed(() => {- const tasks = flattenTaskV1List(rollout.value);- return tasks.filter(- (task) =>- task.specId === selectedSpec.value.id &&- task.status === Task_Status.FAILED- );-});--const taskRunList = computed(() => {- if (failedSpecTasks.value.length === 0) {- return [];- }-- const latestFailedTaskRuns: TaskRun[] = [];-- // For each failed task, find its latest task run- for (const failedTask of failedSpecTasks.value) {- const taskUID = extractTaskUID(failedTask.name);-- // Get all task runs for this failed task- const taskRunsForTask = taskRuns.value.filter(- (taskRun) => extractTaskUID(taskRun.name) === taskUID- ) as TaskRun[];-- if (taskRunsForTask.length > 0) {- // Sort by creation time to get the latest first- const sortedTaskRuns = taskRunsForTask.sort((a, b) => {- const aTime = a.createTime ? Number(a.createTime.seconds) : 0;- const bTime = b.createTime ? Number(b.createTime.seconds) : 0;- return bTime - aTime; // Latest first- });-- // Get the latest task run (first after sorting)- const latestTaskRun = sortedTaskRuns[0];- latestFailedTaskRuns.push(latestTaskRun);- }- }-- return latestFailedTaskRuns;-});--// Determine if the section should be shown at all-const shouldShowSection = computed(() => {- return failedSpecTasks.value.length > 0 && taskRuns.value.length > 0;-});--// Helper function to get the task for a task run-const getTaskForTaskRun = (taskRun: TaskRun) => {- const taskUID = extractTaskUID(taskRun.name);- return failedSpecTasks.value.find(- (task) => extractTaskUID(task.name) === taskUID- );-};--// Determine if we're in a loading state-const isLoading = computed(() => {- // We're loading if we have failed tasks, rollout exists, but no task runs loaded yet- const hasFailedTasks = failedSpecTasks.value.length > 0;- return (- hasFailedTasks && rollout.value !== undefined && taskRuns.value.length === 0- );-});--watchEffect(async () => {- for (const taskRun of taskRunList.value) {- if (taskRun.status === TaskRun_Status.RUNNING) {- await taskRunLogStore.fetchTaskRunLog(taskRun.name);- }- }-});--const rowKey = (taskRun: TaskRun) => {- return taskRun.name;-};--const rowProps = (taskRun: TaskRun) => {- return {- style: "cursor: pointer;",- onClick: () => {- if (shouldShowDetailButton(taskRun)) {- showDetail(taskRun);- }- },- };-};--const columnList = computed((): DataTableColumn<TaskRun>[] => {- return [- {- key: "status",- title: "",- width: "30px",- render: (taskRun: TaskRun) => (- <TaskRunStatusIcon status={taskRun.status} />- ),- },- {- key: "database",- title: t("common.database"),- width: "256px",- resizable: true,- render: (taskRun: TaskRun) => {- const task = getTaskForTaskRun(taskRun);- return task?.target ? (- <DatabaseDisplay showEnvironment database={task.target} />- ) : (- "-"- );- },- },- {- key: "comment",- title: t("task.comment"),- resizable: true,- render: (taskRun: TaskRun) => (- <div class="flex flex-row justify-start items-center">- <TaskRunComment- taskRun={taskRun}- expandTrigger={false}- lineClamp={1}- />- </div>- ),- },- {- key: "startTime",- title: t("task.started"),- width: "100px",- render: (taskRun: TaskRun) => (- <HumanizeDate date={getDateForPbTimestampProtoEs(taskRun.startTime)} />- ),- },- {- key: "actions",- title: "",- width: "100px",- render: (taskRun: TaskRun) =>- shouldShowDetailButton(taskRun) ? (- <NButton- size="tiny"- onClick={() => navigateToTaskDetail(taskRun)}- iconPlacement="right"- >- {{- default: () => t("common.detail"),- icon: () => <ExternalLinkIcon class="w-3 h-3" />,- }}- </NButton>- ) : null,- },- ];-});--const shouldShowDetailButton = (taskRun: TaskRun) => {- return [- TaskRun_Status.RUNNING,- TaskRun_Status.DONE,- TaskRun_Status.FAILED,- TaskRun_Status.CANCELED,- ].includes(taskRun.status);-};--// Get database for selected task run-const selectedDatabase = computed(() => {- if (!taskRunDetailContext.taskRun) return undefined;- const task = getTaskForTaskRun(taskRunDetailContext.taskRun);- if (!task?.target) return undefined;- return databaseStore.getDatabaseByName(task.target);-});--// Navigate to task detail page-const navigateToTaskDetail = (taskRun: TaskRun) => {- const task = getTaskForTaskRun(taskRun);- if (task) {- router.push(buildTaskDetailRoute(task.name));- }-};--// Show task run detail in drawer-const showDetail = (taskRun: TaskRun) => {- taskRunDetailContext.taskRun = taskRun;- taskRunDetailContext.show = true;-};-</script>diff --git a/frontend/src/components/Plan/components/SpecDetailView/SpecDetailView.vue b/frontend/src/components/Plan/components/SpecDetailView/SpecDetailView.vuedeleted file mode 100644index 980e5c0e06..0000000000--- a/frontend/src/components/Plan/components/SpecDetailView/SpecDetailView.vue+++ /dev/null@@ -1,52 +0,0 @@-<template>- <div class="w-full flex-1 flex flex-col">- <SpecListSection />- <div class="w-full flex-1 flex flex-col px-4 gap-y-4 py-4 overflow-y-auto">- <TargetListSection />-- <!-- Statement -->- <StatementSection />-- <!-- Checks + Configuration -->- <template v-if="!specHasRelease">- <SQLCheckV1Section v-if="isCreating" />- <PlanCheckSection v-else />- </template>- <Configuration />- </div>- </div>-</template>--<script setup lang="ts">-import { computed, type Ref } from "vue";-import { useCurrentProjectV1 } from "@/store";-import { isValidReleaseName } from "@/types";-import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";-import { usePlanContext } from "../../logic/context";-import Configuration from "../Configuration";-import PlanCheckSection from "../PlanCheckSection";-import { providePlanSQLCheckContext } from "../SQLCheckSection";-import SQLCheckV1Section from "../SQLCheckV1Section";-import StatementSection from "../StatementSection";-import { useSelectedSpec } from "./context";-import SpecListSection from "./SpecListSection.vue";-import TargetListSection from "./TargetListSection.vue";--const { project } = useCurrentProjectV1();-const { isCreating, plan } = usePlanContext();--const { selectedSpec } = useSelectedSpec();--providePlanSQLCheckContext({- project,- plan,- selectedSpec: selectedSpec as Ref<Plan_Spec>,-});--const specHasRelease = computed(() => {- return (- selectedSpec.value.config.case === "changeDatabaseConfig" &&- isValidReleaseName(selectedSpec.value.config.value.release)- );-});-</script>diff --git a/frontend/src/components/Plan/components/SpecDetailView/SpecListSection.vue b/frontend/src/components/Plan/components/SpecDetailView/SpecListSection.vuedeleted file mode 100644index dc2eb50b6c..0000000000--- a/frontend/src/components/Plan/components/SpecDetailView/SpecListSection.vue+++ /dev/null@@ -1,281 +0,0 @@-<template>- <div class="flex items-center pt-2">- <NTabs- :key="`${plan.specs.length}-${selectedSpec.id}`"- :value="selectedSpec.id"- type="line"- size="small"- class="flex-1"- @update:value="handleTabChange"- >- <template #prefix>- <div />- </template>- <NTab v-for="(spec, index) in plan.specs" :key="spec.id" :name="spec.id">- <div class="flex items-center gap-1">- <span v-if="plan.specs.length > 1" class="opacity-80"- >#{{ index + 1 }}</span- >- {{ getSpecTitle(spec) }}- <NTooltip v-if="isSpecEmpty(spec)">- <template #trigger>- <span class="text-error">*</span>- </template>- {{ $t("plan.navigator.statement-empty") }}- </NTooltip>- <NDropdown- v-if="canModifySpecs && plan.specs.length > 1"- :options="getDropdownOptions(spec)"- trigger="click"- placement="bottom-end"- :size="'small'"- @select="(key) => handleDropdownSelect(key, spec)"- >- <NButton @click.stop text size="tiny">- <template #icon>- <MoreVerticalIcon :size="14" class="text-control-light" />- </template>- </NButton>- </NDropdown>- </div>- </NTab>-- <template #suffix>- <div class="pr-4">- <NButton- v-if="canModifySpecs"- type="default"- size="tiny"- @click="showAddSpecDrawer = true"- >- {{ $t("plan.add-spec") }}- </NButton>- </div>- </template>- </NTabs>- </div>-- <AddSpecDrawer- v-model:show="showAddSpecDrawer"- @created="handleSpecCreated"- />--</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { MoreVerticalIcon, TrashIcon } from "lucide-vue-next";-import type { DropdownOption } from "naive-ui";-import { NButton, NDropdown, NTab, NTabs, NTooltip, useDialog } from "naive-ui";-import { computed, h, inject, nextTick, ref } from "vue";-import { useI18n } from "vue-i18n";-import { useRouter } from "vue-router";-import { planServiceClientConnect } from "@/connect";-import { buildSpecDetailRouteForCurrentPage } from "@/router/dashboard/projectV1RouteHelpers";-import {- pushNotification,- useCurrentProjectV1,- useSheetV1Store,-} from "@/store";-import { State } from "@/types/proto-es/v1/common_pb";-import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";-import { UpdatePlanRequestSchema } from "@/types/proto-es/v1/plan_service_pb";-import { extractSheetUID } from "@/utils";-import { getLocalSheetByName } from "../../logic";-import { usePlanContext } from "../../logic/context";-import { useEditorState } from "../../logic/useEditorState";-import { getSpecTitle } from "../../logic/utils";-import AddSpecDrawer from "../AddSpecDrawer.vue";-import { useSpecsValidation } from "../common";-import { SELECTED_SPEC_ID_SETTER_KEY, useSelectedSpec } from "./context";--// Check if spec selection is managed via injection (PlanDetailPage)-const specIdSetter = inject(SELECTED_SPEC_ID_SETTER_KEY, null);--const router = useRouter();-const dialog = useDialog();-const { t } = useI18n();-const { plan, isCreating, allowEdit } = usePlanContext();-const sheetStore = useSheetV1Store();-const { selectedSpec } = useSelectedSpec();-const { project } = useCurrentProjectV1();-const { isSpecEmpty } = useSpecsValidation(computed(() => plan.value.specs));-const { setEditingState } = useEditorState();--const showAddSpecDrawer = ref(false);--// Allow adding/removing specs when:-// 1. Plan is not closed (state !== DELETED), AND-// 2. Plan is being created (isCreating = true), OR plan has no rollout-const canModifySpecs = computed(() => {- if (plan.value.state === State.DELETED) return false;- if (isCreating.value) {- return true;- }- return allowEdit.value && !plan.value.hasRollout;-});--const handleTabChange = (specId: string) => {- if (selectedSpec.value.id !== specId) {- gotoSpec(specId);- }-};--const handleSpecCreated = async (spec: Plan_Spec) => {- // Add the new spec to the plan.-- // If the plan is not being created (already exists), call UpdatePlan API- if (!isCreating.value) {- // If the spec references a sheet that is pending creation (UID starts with "-"),- // we need to create the sheet first.- if (- spec.config.case === "changeDatabaseConfig" ||- spec.config.case === "exportDataConfig"- ) {- const uid = extractSheetUID(spec.config.value.sheet);- if (uid.startsWith("-")) {- // The sheet is pending create.- const sheetToCreate = getLocalSheetByName(spec.config.value.sheet);- const createdSheet = await sheetStore.createSheet(- project.value.name,- sheetToCreate- );- spec.config.value.sheet = createdSheet.name;- }- }- plan.value.specs.push(spec);- try {- const request = create(UpdatePlanRequestSchema, {- plan: plan.value,- updateMask: { paths: ["specs"] },- });- const response = await planServiceClientConnect.updatePlan(request);- Object.assign(plan.value, response);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });- } catch (error) {- // If the API call fails, remove the spec from local state- const specIndex = plan.value.specs.findIndex((s) => s.id === spec.id);- if (specIndex >= 0) {- plan.value.specs.splice(specIndex, 1);- }- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.error"),- description: `Failed to add spec: ${error}`,- });- return;- }- } else {- plan.value.specs.push(spec);- }-- const enableEditing = !isCreating.value;- gotoSpec(spec.id, enableEditing);-};--const gotoSpec = (specId: string, enableEditing = false) => {- const currentRoute = router.currentRoute.value;- const nextRoute = buildSpecDetailRouteForCurrentPage(currentRoute, specId);-- // When spec selection is managed via injection (PlanDetailPage),- // keep the local selection responsive while still syncing the URL.- if (specIdSetter) {- specIdSetter(specId);- void router.push(nextRoute);- if (enableEditing) {- nextTick(() => setEditingState(true));- }- return;- }-- router.push(nextRoute).then(() => {- // Enable editing mode if requested (for newly created specs)- if (enableEditing) {- // Use nextTick to ensure the route navigation completes first- nextTick(() => {- setEditingState(true);- });- }- });-};--const getDropdownOptions = (_spec: Plan_Spec): DropdownOption[] => {- const options: DropdownOption[] = [];- if (plan.value.specs.length > 1) {- options.push({- key: "delete",- label: t("common.delete"),- icon: () => h(TrashIcon, { size: 16 }),- });- }- return options;-};--const handleDropdownSelect = (key: string, spec: Plan_Spec) => {- if (key === "delete") {- handleDeleteSpec(spec);- }-};--const handleDeleteSpec = (spec: Plan_Spec) => {- dialog.warning({- title: t("plan.spec.delete-change.title"),- content: t("plan.spec.delete-change.content"),- positiveText: t("common.delete"),- negativeText: t("common.cancel"),- onPositiveClick: async () => {- if (plan.value.specs.length <= 1) {- pushNotification({- module: "bytebase",- style: "WARN",- title: "Cannot delete last spec",- });- return;- }-- const specIndex = plan.value.specs.findIndex((s) => s.id === spec.id);- if (specIndex < 0) return;-- // Remove the spec from local state- const removedSpec = plan.value.specs.splice(specIndex, 1)[0];-- // If the plan is not being created (already exists), call UpdatePlan API- if (!isCreating.value) {- try {- const request = create(UpdatePlanRequestSchema, {- plan: plan.value,- updateMask: { paths: ["specs"] },- });- const response = await planServiceClientConnect.updatePlan(request);- Object.assign(plan.value, response);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });- } catch (error) {- // If the API call fails, restore the spec to local state- plan.value.specs.splice(specIndex, 0, removedSpec);- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.error"),- description: `Failed to delete spec: ${error}`,- });- return;- }- }-- // If we deleted the currently selected spec, navigate to the first remaining spec- if (selectedSpec.value.id === spec.id && plan.value.specs.length > 0) {- gotoSpec(plan.value.specs[0].id);- }- },- });-};-</script>diff --git a/frontend/src/components/Plan/components/SpecDetailView/TargetListSection.vue b/frontend/src/components/Plan/components/SpecDetailView/TargetListSection.vuedeleted file mode 100644index bcdcf76bde..0000000000--- a/frontend/src/components/Plan/components/SpecDetailView/TargetListSection.vue+++ /dev/null@@ -1,233 +0,0 @@-<template>- <div class="flex flex-col gap-y-1">- <div class="flex items-center justify-between">- <div class="flex items-center gap-1">- <span class="textlabel uppercase">{{ $t("plan.targets.title") }}</span>- <span class="textlabel text-control-light" v-if="targets.length > 1"- >({{ targets.length }})</span- >- </div>- <NButton- v-if="allowEdit"- size="tiny"- @click="showTargetsSelector = true"- >- {{ $t("common.edit") }}- </NButton>- </div>-- <NAlert v-if="!isLoadingTargets && nonEnvDatabaseNames.length > 0" type="warning">- {{ $t("plan.targets.non-env-warning", { count: nonEnvDatabaseNames.length }) }}- <div class="flex flex-col gap-1 text-sm mt-1">- <div v-for="name in nonEnvDatabaseNames" :key="name" class="flex items-center gap-2">- <span class="w-1 h-1 rounded-full bg-current shrink-0" />- <DatabaseDisplay :database="name" />- </div>- </div>- </NAlert>-- <div v-if="isLoadingTargets" class="flex items-center justify-center py-2">- <BBSpin />- </div>- <div v-else-if="targets.length > 0" class="flex flex-wrap items-center gap-2">- <div- v-for="target in visibleTargets"- :key="target"- class="inline-flex items-center gap-x-1 px-2 py-1 border rounded-lg cursor-default"- >- <DatabaseDisplay- v-if="isValidDatabaseName(target)"- :database="target"- size="medium"- show-environment- />- <DatabaseGroupTargetDisplay- v-else-if="isValidDatabaseGroupName(target)"- :target="target"- class="py-1"- />- <span v-else class="text-sm text-control-placeholder">{{ target }}</span>- </div>- <NButton- v-if="targets.length > DEFAULT_VISIBLE_TARGETS"- size="tiny"- quaternary- @click="showAllTargetsDrawer = true"- >- {{ $t("plan.targets.view-all", { count: targets.length }) }}- </NButton>- </div>- <div v-else class="text-sm text-control-light py-1">- {{ $t("plan.targets.no-targets-found") }}- </div>-- <TargetsSelectorDrawer- v-if="project"- v-model:show="showTargetsSelector"- :current-targets="targets"- @confirm="handleUpdateTargets"- />-- <AllTargetsDrawer v-model:show="showAllTargetsDrawer" :targets="targets" />- </div>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { isEqual } from "lodash-es";-import { NAlert, NButton } from "naive-ui";-import { computed, ref, watch } from "vue";-import { useI18n } from "vue-i18n";-import { BBSpin } from "@/bbkit";-import { planServiceClientConnect } from "@/connect";-import {- projectNamePrefix,- pushNotification,- useDatabaseV1Store,- useDBGroupStore,- useProjectV1Store,-} from "@/store";-import { isValidDatabaseGroupName, isValidDatabaseName } from "@/types";-import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";-import { UpdatePlanRequestSchema } from "@/types/proto-es/v1/plan_service_pb";-import { extractProjectResourceName } from "@/utils";-import { usePlanContext } from "../../logic/context";-import DatabaseDisplay from "../common/DatabaseDisplay.vue";-import AllTargetsDrawer from "./AllTargetsDrawer.vue";-import {- DEFAULT_VISIBLE_TARGETS,- useForceReadonly,- useSelectedSpec,-} from "./context";-import DatabaseGroupTargetDisplay from "./DatabaseGroupTargetDisplay.vue";-import TargetsSelectorDrawer from "./TargetsSelectorDrawer.vue";--const { t } = useI18n();-const {- plan,- isCreating,- readonly,- allowEdit: hasPermission,-} = usePlanContext();-const { selectedSpec, targets, getDatabaseTargets } = useSelectedSpec();-const dbGroupStore = useDBGroupStore();-const projectStore = useProjectV1Store();-const dbStore = useDatabaseV1Store();--const isLoadingTargets = ref(false);-const showTargetsSelector = ref(false);-const showAllTargetsDrawer = ref(false);--const project = computed(() => {- if (!plan.value?.name) return undefined;- const projectName = `${projectNamePrefix}${extractProjectResourceName(plan.value.name)}`;- return projectStore.getProjectByName(projectName);-});--// Only allow editing in creation mode or if the plan is editable and not readonly.-// An empty string for `plan.value.hasRollout` indicates that the plan is in a draft or uninitialized state,-// which allows edits to be made.-const forceReadonly = useForceReadonly();--const allowEdit = computed(() => {- if (forceReadonly || readonly.value) {- return false;- }- if (!hasPermission.value) {- return false;- }- return (isCreating.value || !plan.value.hasRollout) && selectedSpec.value;-});--const getDatabaseNamesForTarget = (target: string): string[] => {- if (!isValidDatabaseGroupName(target)) return [target];- const dbGroup = dbGroupStore.getDBGroupByName(target);- return dbGroup?.matchedDatabases?.map((m) => m.name) ?? [];-};--const hasNoEnvironment = (name: string): boolean => {- return !dbStore.getDatabaseByName(name).effectiveEnvironment;-};--const nonEnvDatabaseNames = computed(() => {- if (isLoadingTargets.value) return [];- return targets.value- .flatMap(getDatabaseNamesForTarget)- .filter(hasNoEnvironment);-});--// Separate targets by type-const visibleTargets = computed(() => {- return targets.value.slice(- 0,- Math.min(DEFAULT_VISIBLE_TARGETS, targets.value.length)- );-});--const handleUpdateTargets = async (targets: string[]) => {- if (!selectedSpec.value) return;-- // Update the targets in the spec.- if (selectedSpec.value.config?.case === "changeDatabaseConfig") {- selectedSpec.value.config.value.targets = targets;- } else if (selectedSpec.value.config?.case === "exportDataConfig") {- selectedSpec.value.config.value.targets = targets;- }-- if (!isCreating.value) {- const request = create(UpdatePlanRequestSchema, {- plan: plan.value,- updateMask: { paths: ["specs"] },- });- const response = await planServiceClientConnect.updatePlan(request);- Object.assign(plan.value, response);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });- }-};--// Load target data when targets change-const loadTargetData = async () => {- if (targets.value.length === 0) {- return;- }-- isLoadingTargets.value = true;-- try {- // Fetch data for visible targets only- const { databaseTargets, dbGroupTargets } = await getDatabaseTargets(- visibleTargets.value- );-- await dbStore.batchGetOrFetchDatabases(databaseTargets);- await Promise.allSettled(- dbGroupTargets.map((target) =>- dbGroupStore.getOrFetchDBGroupByName(target, {- view: DatabaseGroupView.FULL,- })- )- );- } catch {- // Ignore errors- } finally {- isLoadingTargets.value = false;- }-};--// Watch for target changes and load data-watch(- targets,- (newTargets, oldTargets) => {- // Only reload if targets actually changed- if (isEqual(newTargets, oldTargets)) {- return;- }- loadTargetData();- },- { immediate: true }-);-</script>diff --git a/frontend/src/components/Plan/components/SpecDetailView/TargetsSelectorDrawer.vue b/frontend/src/components/Plan/components/SpecDetailView/TargetsSelectorDrawer.vuedeleted file mode 100644index 2d6633c990..0000000000--- a/frontend/src/components/Plan/components/SpecDetailView/TargetsSelectorDrawer.vue+++ /dev/null@@ -1,108 +0,0 @@-<template>- <Drawer- v-model:show="show"- :mask-closable="true"- placement="right"- class="w-screen! sm:w-[80vw]!"- >- <DrawerContent :title="$t('plan.select-targets')" closable>- <div class="flex flex-col gap-y-4">- <div class="flex-1 overflow-hidden">- <DatabaseAndGroupSelector- :project="project"- :value="databaseSelectState"- @update:value="handleUpdateSelection"- />- </div>- </div>- <template #footer>- <div class="flex items-center justify-end gap-x-3">- <NButton @click="show = false" quaternary>- {{ $t("common.cancel") }}- </NButton>- <NButton- type="primary"- :disabled="!hasSelection"- @click="handleConfirm"- >- {{ $t("common.confirm") }}- </NButton>- </div>- </template>- </DrawerContent>- </Drawer>-</template>--<script setup lang="ts">-import { NButton } from "naive-ui";-import { computed, reactive, watch } from "vue";-import type { DatabaseSelectState } from "@/components/DatabaseAndGroupSelector";-import DatabaseAndGroupSelector from "@/components/DatabaseAndGroupSelector";-import { Drawer, DrawerContent } from "@/components/v2";-import { useCurrentProjectV1 } from "@/store";--const props = defineProps<{- currentTargets: string[];-}>();--const emit = defineEmits<{- (event: "confirm", targets: string[]): void;-}>();--const { project } = useCurrentProjectV1();-const show = defineModel<boolean>("show", { default: false });--const databaseSelectState = reactive<DatabaseSelectState>({- changeSource: "DATABASE",- selectedDatabaseNameList: [],-});--const hasSelection = computed(() => {- if (databaseSelectState.changeSource === "DATABASE") {- return databaseSelectState.selectedDatabaseNameList.length > 0;- } else {- return !!databaseSelectState.selectedDatabaseGroup;- }-});--// Initialize selection when drawer opens-watch(show, (newVal) => {- if (newVal && props.currentTargets.length > 0) {- // Check if current targets are database group or databases- const firstTarget = props.currentTargets[0];- if (firstTarget.includes("/databaseGroups/")) {- // It's a database group- databaseSelectState.changeSource = "GROUP";- databaseSelectState.selectedDatabaseGroup = firstTarget;- databaseSelectState.selectedDatabaseNameList = [];- } else {- // It's database(s)- databaseSelectState.changeSource = "DATABASE";- databaseSelectState.selectedDatabaseNameList = [...props.currentTargets];- databaseSelectState.selectedDatabaseGroup = undefined;- }- } else if (newVal) {- // Reset to default state if no current targets- databaseSelectState.changeSource = "DATABASE";- databaseSelectState.selectedDatabaseNameList = [];- databaseSelectState.selectedDatabaseGroup = undefined;- }-});--const handleUpdateSelection = (newState: DatabaseSelectState) => {- Object.assign(databaseSelectState, newState);-};--const handleConfirm = () => {- const targets: string[] = [];-- if (databaseSelectState.changeSource === "DATABASE") {- targets.push(...databaseSelectState.selectedDatabaseNameList);- } else if (databaseSelectState.selectedDatabaseGroup) {- targets.push(databaseSelectState.selectedDatabaseGroup);- }-- emit("confirm", targets);- show.value = false;-};-</script>diff --git a/frontend/src/components/Plan/components/SpecDetailView/context.ts b/frontend/src/components/Plan/components/SpecDetailView/context.tsdeleted file mode 100644index 2bb748fa86..0000000000--- a/frontend/src/components/Plan/components/SpecDetailView/context.ts+++ /dev/null@@ -1,110 +0,0 @@-import { head, uniq } from "lodash-es";-import { computed, type InjectionKey, inject, provide, type Ref } from "vue";-import { useRoute } from "vue-router";-import { useDBGroupStore } from "@/store";-import { isValidDatabaseGroupName } from "@/types";-import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";-import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";-import { usePlanContext } from "../../logic";--export const DEFAULT_VISIBLE_TARGETS = 20;--// When provided as `true`, children should hide edit controls-export const FORCE_READONLY_KEY: InjectionKey<boolean> =- Symbol("force-readonly");--export const useForceReadonly = (): boolean => {- return inject(FORCE_READONLY_KEY, false);-};--export const SELECTED_SPEC_INJECTION_KEY: InjectionKey<Ref<Plan_Spec>> =- Symbol("selected-spec");--export const SELECTED_SPEC_ID_SETTER_KEY: InjectionKey<- (specId: string) => void-> = Symbol("selected-spec-id-setter");--export const provideSelectedSpec = (- spec: Ref<Plan_Spec>,- setSpecId?: (specId: string) => void-) => {- provide(SELECTED_SPEC_INJECTION_KEY, spec);- if (setSpecId) {- provide(SELECTED_SPEC_ID_SETTER_KEY, setSpecId);- }-};--export const useSelectedSpec = () => {- const route = useRoute();- const { plan } = usePlanContext();- const dbGroupStore = useDBGroupStore();-- const injectedSpec = inject(SELECTED_SPEC_INJECTION_KEY, null);-- const selectedSpec = computed(() => {- if (injectedSpec?.value) {- return injectedSpec.value;- }-- if (plan.value.specs.length === 0) {- throw new Error("No specs found in the plan.");- }-- const specId = route.params.specId as string | undefined;- if (!specId) {- // For export plans without specId in route, use first spec- if (plan.value.specs.every((s) => s.config.case === "exportDataConfig")) {- return plan.value.specs[0];- }- throw new Error("Spec ID is required in the route parameters.");- }-- const foundSpec =- plan.value.specs.find((s) => s.id === specId) ?? head(plan.value.specs);- if (!foundSpec) {- throw new Error(`Spec with ID ${specId} not found in the plan.`);- }- return foundSpec;- });-- const targets = computed(() => {- const config = selectedSpec.value?.config;- if (- config?.case === "changeDatabaseConfig" ||- config?.case === "exportDataConfig"- ) {- return config.value.targets;- }- return [];- });-- const getDatabaseTargets = async (- targetList: string[]- ): Promise<{ databaseTargets: string[]; dbGroupTargets: string[] }> => {- const databaseTargets: string[] = [];- const dbGroupTargets: string[] = [];-- for (const target of targetList) {- if (isValidDatabaseGroupName(target)) {- dbGroupTargets.push(target);- try {- const dbGroup = await dbGroupStore.getOrFetchDBGroupByName(target, {- view: DatabaseGroupView.FULL,- silent: true,- });- databaseTargets.push(- ...(dbGroup.matchedDatabases?.map((db) => db.name) ?? [])- );- } catch {- // Ignore errors fetching database group- }- } else {- databaseTargets.push(target);- }- }-- return { databaseTargets: uniq(databaseTargets), dbGroupTargets };- };-- return { selectedSpec, targets, getDatabaseTargets };-};diff --git a/frontend/src/components/Plan/components/SpecDetailView/index.ts b/frontend/src/components/Plan/components/SpecDetailView/index.tsdeleted file mode 100644index e7869607e3..0000000000--- a/frontend/src/components/Plan/components/SpecDetailView/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import SpecDetailView from "./SpecDetailView.vue";--export default SpecDetailView;diff --git a/frontend/src/components/Plan/components/StatementSection/EditorView/EditorView.vue b/frontend/src/components/Plan/components/StatementSection/EditorView/EditorView.vuedeleted file mode 100644index f71377b8c2..0000000000--- a/frontend/src/components/Plan/components/StatementSection/EditorView/EditorView.vue+++ /dev/null@@ -1,590 +0,0 @@-<template>- <div class="flex flex-col gap-y-1">- <div class="flex items-center justify-between">- <div class="flex items-center gap-x-1">- <span- :class="titleClass"- >- {{ statementTitle }}- </span>- <RequiredStar v-if="isEmpty(state.statement)" />- </div>- <div class="flex items-center justify-end gap-x-2">- <template v-if="isCreating">- <SQLUploadButton- :size="actionButtonSize"- :loading="state.isUploadingFile"- @update:sql="handleUpdateStatement"- >- {{ $t("issue.upload-sql") }}- </SQLUploadButton>- <NButton- v-if="shouldShowSchemaEditorButton && targetDatabaseNames.length > 0"- :size="actionButtonSize"- @click="handleOpenSchemaEditor"- >- <template #icon>- <TableIcon />- </template>- {{ $t("schema-editor.self") }}- </NButton>- </template>-- <template v-else>- <template v-if="!editorState.isEditing.value">- <template v-if="shouldShowEditButton">- <!-- for small size sheets, show full featured UI editing button group -->- <NTooltip :disabled="denyEditStatementReasons.length === 0">- <template #trigger>- <NButton- v-if="!isSheetOversize"- :size="actionButtonSize"- tag="div"- :disabled="denyEditStatementReasons.length > 0"- @click.prevent="beginEdit"- >- {{ $t("common.edit") }}- </NButton>- <!-- for oversized sheets, only allow to upload and overwrite the sheet -->- <SQLUploadButton- v-else- :size="actionButtonSize"- :loading="state.isUploadingFile"- @update:sql="handleUpdateStatementAndOverwrite"- >- {{ $t("issue.upload-sql") }}- </SQLUploadButton>- </template>- <template #default>- <ErrorList :errors="denyEditStatementReasons" />- </template>- </NTooltip>- </template>- </template>- <template v-else>- <SQLUploadButton- :size="actionButtonSize"- :loading="state.isUploadingFile"- @update:sql="handleUpdateStatement"- >- {{ $t("issue.upload-sql") }}- </SQLUploadButton>- <NButton- v-if="shouldShowSchemaEditorButton"- :size="actionButtonSize"- @click="handleOpenSchemaEditor"- >- <template #icon>- <TableIcon />- </template>- {{ $t("schema-editor.self") }}- </NButton>- <NButton- v-if="editorState.isEditing.value"- :size="actionButtonSize"- :disabled="!allowSaveSQL"- @click.prevent="saveEdit"- >- {{ $t("common.save") }}- </NButton>- <NButton- v-if="editorState.isEditing.value"- :size="actionButtonSize"- quaternary- @click.prevent="cancelEdit"- >- {{ $t("common.cancel") }}- </NButton>- </template>- </template>- </div>- </div>-- <BBAttention- v-if="isSheetOversize"- type="warning"- :description="$t('issue.statement-from-sheet-warning')"- >- <template #action>- <DownloadSheetButton v-if="sheetName" :sheet="sheetName" size="tiny" />- </template>- </BBAttention>-- <div class="relative h-64">- <MonacoEditor- class="w-full h-full border rounded-sm overflow-hidden"- :filename="filename"- :content="state.statement"- :language="language"- :auto-focus="false"- :readonly="isEditorReadonly"- :dialect="dialect"- :advices="isEditorReadonly || isCreating ? markers : []"- :auto-complete-context="{- instance: extractDatabaseResourceName(database.name).instance,- database: database.name,- scene: 'all',- }"- @update:content="handleStatementChange"- />- <div v-if="!readonly" class="absolute bottom-1 right-4">- <NButton- size="tiny"- :quaternary="true"- @click="state.showEditorModal = true"- >- <template #icon>- <ExpandIcon class="w-4 h-4" />- </template>- </NButton>- </div>- </div>- </div>-- <BBModal- v-model:show="state.showEditorModal"- :title="statementTitle"- :trap-focus="true"- header-class="border-b-0!"- container-class="pt-0! overflow-hidden!"- >- <div- id="modal-editor-container"- style="- width: calc(100vw - 10rem);- height: calc(100vh - 10rem);- overflow: hidden;- position: relative;- "- class="border rounded-[3px]"- >- <MonacoEditor- v-if="state.showEditorModal"- class="w-full h-full"- :filename="filename"- :content="state.statement"- :language="language"- :auto-focus="false"- :readonly="isEditorReadonly"- :dialect="dialect"- :advices="isEditorReadonly || isCreating ? markers : []"- :auto-complete-context="{- instance: extractDatabaseResourceName(database.name).instance,- database: database.name,- scene: 'all',- }"- @update:content="handleStatementChange"- />- </div>- </BBModal>-- <SchemaEditorDrawer- v-if="shouldShowSchemaEditorButton"- v-model:show="state.showSchemaEditorDrawer"- :databaseNames="targetDatabaseNames"- :project="project"- @insert="handleInsertSQL"- />-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { cloneDeep, isEmpty } from "lodash-es";-import { ExpandIcon, TableIcon } from "lucide-vue-next";-import { NButton, NTooltip, useDialog } from "naive-ui";-import { v1 as uuidv1 } from "uuid";-import { computed, reactive, ref, watch, watchEffect } from "vue";-import { useI18n } from "vue-i18n";-import { BBAttention, BBModal } from "@/bbkit";-import { MonacoEditor } from "@/components/MonacoEditor";-import { extensionNameOfLanguage } from "@/components/MonacoEditor/utils";-import SQLUploadButton from "@/components/misc/SQLUploadButton.vue";-import { ErrorList } from "@/components/Plan/components/common";-import {- createEmptyLocalSheet,- databaseForSpec,- planCheckRunListForSpec,- usePlanContext,-} from "@/components/Plan/logic";-import { useEditorState } from "@/components/Plan/logic/useEditorState";-import RequiredStar from "@/components/RequiredStar.vue";-import DownloadSheetButton from "@/components/Sheet/DownloadSheetButton.vue";-import { planServiceClientConnect } from "@/connect";-import {- pushNotification,- useCurrentProjectV1,- useDatabaseV1Store,- useSheetV1Store,-} from "@/store";-import type { SQLDialect } from "@/types";-import { dialectOfEngineV1, isValidDatabaseGroupName } from "@/types";-import { UpdatePlanRequestSchema } from "@/types/proto-es/v1/plan_service_pb";-import { SheetSchema } from "@/types/proto-es/v1/sheet_service_pb";-import {- extractDatabaseResourceName,- getInstanceResource,- setSheetStatement,- useInstanceV1EditorLanguage,-} from "@/utils";-import { engineSupportsSchemaEditor } from "@/utils/schemaEditor";-import {- useForceReadonly,- useSelectedSpec,-} from "../../SpecDetailView/context";-import { isGhostEnabled } from "../directiveUtils";-import SchemaEditorDrawer from "../SchemaEditorDrawer.vue";-import { useSpecSheet } from "../useSpecSheet";-import { useSQLAdviceMarkers } from "../useSQLAdviceMarkers";--type LocalState = {- statement: string;- showEditorModal: boolean;- isUploadingFile: boolean;- showSchemaEditorDrawer: boolean;-};--const props = withDefaults(- defineProps<{- headerVariant?: "editor" | "section";- }>(),- {- headerVariant: "editor",- }-);--const { t } = useI18n();-const dialog = useDialog();-const { project } = useCurrentProjectV1();-const { isCreating, plan, planCheckRuns, events, readonly, allowEdit } =- usePlanContext();-const { selectedSpec, getDatabaseTargets, targets } = useSelectedSpec();-const editorState = useEditorState();--const state = reactive<LocalState>({- statement: "",- showEditorModal: false,- isUploadingFile: false,- showSchemaEditorDrawer: false,-});--const database = computed(() => {- return databaseForSpec(project.value, selectedSpec.value);-});--const instanceResource = computed(() => getInstanceResource(database.value));--const language = useInstanceV1EditorLanguage(instanceResource);-const filename = computed(() => {- const name = uuidv1();- const ext = extensionNameOfLanguage(language.value);- return `${name}.${ext}`;-});-const dialect = computed((): SQLDialect => {- return dialectOfEngineV1(instanceResource.value.engine);-});-const statementTitle = computed(() => {- return language.value === "sql" ? t("common.sql") : t("common.statement");-});-const titleClass = computed(() => {- if (props.headerVariant === "section") {- return [- "text-base font-medium",- isEmpty(state.statement) ? "text-red-600!" : "",- ];- }- return [- "textlabel uppercase",- isEmpty(state.statement) ? "text-red-600!" : "",- ];-});-const actionButtonSize = computed(() => {- return props.headerVariant === "section" ? "small" : "tiny";-});-const planCheckRunsForSelectedSpec = computed(() =>- planCheckRunListForSpec(planCheckRuns.value, selectedSpec.value)-);-const { markers } = useSQLAdviceMarkers(- isCreating,- planCheckRunsForSelectedSpec-);--/**- * to set the MonacoEditor as readonly- * This happens when- * - Not in edit mode- * - Disallowed to edit statement- */-const forceReadonly = useForceReadonly();--const isEditorReadonly = computed(() => {- if (forceReadonly || readonly.value) {- return true;- }- if (isCreating.value) {- return false;- }- return !editorState.isEditing.value || isSheetOversize.value || false;-});--const {- sheet,- sheetName,- sheetReady,- sheetStatement,- isSheetOversize: isSheetOversizeRaw,-} = useSpecSheet(selectedSpec);--// Wrap the raw oversized check with UI-specific conditions:-// - When creating, sheets are local and never truncated in practice-// - When editing, the user has already entered edit mode (only possible for non-oversized sheets)-const isSheetOversize = computed(() => {- if (isCreating.value) return false;- if (editorState.isEditing.value) return false;- return isSheetOversizeRaw.value;-});--const denyEditStatementReasons = computed(() => {- const reasons: string[] = [];-- // Check if the plan has been rolled out.- if (plan.value.hasRollout) {- reasons.push(t("issue.error.statement-cannot-be-modified"));- }-- return reasons;-});--const shouldShowEditButton = computed(() => {- // Not allowed to edit if readonly or forced readonly (Issue page).- if (forceReadonly || readonly.value) {- return false;- }- // Need not to show "Edit" while the plan is still pending create.- if (isCreating.value) {- return false;- }- // Will show another button group as [Upload][Cancel][Save]- // while editing- if (editorState.isEditing.value) {- return false;- }- // Hide edit button for plans that have a rollout.- if (plan.value.hasRollout) {- return false;- }- return allowEdit.value;-});--const allowSaveSQL = computed((): boolean => {- if (state.statement === "") {- // Not allowed if the statement is empty.- return false;- }- if (!sheetReady.value) {- return false;- }- if (state.statement === sheetStatement.value) {- // Not allowed if the statement is not modified.- return false;- }-- // Allowed to save otherwise- return true;-});--const shouldShowSchemaEditorButton = computed(() => {- const spec = selectedSpec.value;-- // Check config exists and is the right type- if (!spec?.config || spec.config.case !== "changeDatabaseConfig") {- return false;- }-- // Only for regular DDL (not gh-ost) schema changes- // Check if ghost is enabled via sheet directive- if (isGhostEnabled(sheetStatement.value)) {- return false;- }-- // Only if at least one database engine supports schema editor- const targets = spec.config.value.targets || [];- if (targets.length === 0) {- return false;- }-- // Check if at least one target database supports schema editor- const databaseStore = useDatabaseV1Store();- return targets.some((targetName) => {- if (isValidDatabaseGroupName(targetName)) {- return false;- }- const db = databaseStore.getDatabaseByName(targetName);- return engineSupportsSchemaEditor(getInstanceResource(db).engine);- });-});--const targetDatabaseNames = ref<string[]>([]);--watchEffect(async () => {- const result = await getDatabaseTargets(targets.value);- targetDatabaseNames.value = result.databaseTargets;-});--const beginEdit = () => {- editorState.setEditingState(true);-};--const saveEdit = async () => {- try {- await updateStatement(state.statement);- } finally {- editorState.setEditingState(false);- }-};--const cancelEdit = () => {- state.statement = sheetStatement.value;- editorState.setEditingState(false);-};--const handleOpenSchemaEditor = () => {- state.showSchemaEditorDrawer = true;-};--const handleInsertSQL = (sql: string) => {- // Append generated SQL to existing content- const currentSQL = state.statement;- const newSQL = currentSQL ? `${currentSQL}\n\n${sql}` : sql;- handleStatementChange(newSQL);- state.showSchemaEditorDrawer = false;-};--const showOverwriteConfirmDialog = () => {- return new Promise((resolve, reject) => {- // Show a confirm dialog before replacing if the editing statement is not empty.- dialog.create({- positiveText: t("common.confirm"),- negativeText: t("common.cancel"),- title: t("issue.overwrite-current-statement"),- autoFocus: false,- closable: false,- maskClosable: false,- closeOnEsc: false,- onNegativeClick: () => {- reject();- },- onPositiveClick: () => {- resolve(undefined);- },- });- });-};--const handleUpdateStatementAndOverwrite = async (- statement: string,- filename: string-) => {- try {- await showOverwriteConfirmDialog();- } catch {- return;- }-- editorState.setEditingState(true);- state.statement = statement;- await handleUpdateStatement(statement, filename);-};--const handleUpdateStatement = async (statement: string, _filename: string) => {- try {- state.isUploadingFile = true;- handleStatementChange(statement);- } finally {- state.isUploadingFile = false;- }-};--const updateStatement = async (statement: string) => {- const planPatch = cloneDeep(plan.value);- const specToPatch = planPatch.specs.find(- (spec) => spec.id === selectedSpec.value.id- );- if (!specToPatch) {- throw new Error(- `Cannot find spec to patch for plan update ${JSON.stringify(- selectedSpec.value- )}`- );- }- if (- specToPatch.config.case !== "changeDatabaseConfig" &&- specToPatch.config.case !== "exportDataConfig"- ) {- throw new Error(- `Unsupported spec type for plan update ${JSON.stringify(specToPatch)}`- );- }- const sheet = create(SheetSchema, {- ...createEmptyLocalSheet(),- });- setSheetStatement(sheet, statement);- const createdSheet = await useSheetV1Store().createSheet(- project.value.name,- sheet- );- specToPatch.config.value.sheet = createdSheet.name;- const request = create(UpdatePlanRequestSchema, {- plan: planPatch,- updateMask: { paths: ["specs"] },- });- await planServiceClientConnect.updatePlan(request);- events.emit("status-changed", {- eager: true,- });- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.updated"),- });-};--const handleStatementChange = (statement: string) => {- if (isEditorReadonly.value) {- return;- }-- state.statement = statement;- if (isCreating.value) {- // When creating an plan, update the local sheet directly.- if (!sheet.value) return;- setSheetStatement(sheet.value, statement);- }-};--watch(- sheetStatement,- (statement, oldStatement) => {- // Don't overwrite user's edits if they're currently in edit mode- if (editorState.isEditing.value) {- return;- }-- // Don't overwrite if the user has made local changes since the last- // sheet update (i.e., current state doesn't match the old sheet statement)- if (oldStatement !== undefined && state.statement !== oldStatement) {- return;- }-- // Safe to update: not editing and no divergence from previous sheet state- state.statement = statement;- },- { immediate: true }-);--watch(isCreating, (curr, prev) => {- // Reset the edit state after creating the plan.- if (!curr && prev) {- editorState.setEditingState(false);- }-});-</script>diff --git a/frontend/src/components/Plan/components/StatementSection/EditorView/index.ts b/frontend/src/components/Plan/components/StatementSection/EditorView/index.tsdeleted file mode 100644index 8a654810d1..0000000000--- a/frontend/src/components/Plan/components/StatementSection/EditorView/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import EditorView from "./EditorView.vue";--export default EditorView;diff --git a/frontend/src/components/Plan/components/StatementSection/ReleaseView/ReleaseView.vue b/frontend/src/components/Plan/components/StatementSection/ReleaseView/ReleaseView.vuedeleted file mode 100644index b7f1931dae..0000000000--- a/frontend/src/components/Plan/components/StatementSection/ReleaseView/ReleaseView.vue+++ /dev/null@@ -1,225 +0,0 @@-<template>- <div class="flex flex-col gap-y-2">- <NAlert type="info" :bordered="false">- <template #icon>- <heroicons-outline:information-circle class="w-5 h-5" />- </template>- <div class="text-sm">- {{ $t("release.change-tip") }}- </div>- </NAlert>-- <div class="flex items-center justify-between">- <div class="flex items-center gap-x-4">- <div class="flex items-center gap-x-1 text-sm font-medium">- <PackageIcon class="w-4 h-4" />- <span class="text-base font-medium">- {{ releaseTitle }}- </span>- </div>- </div>- <div class="flex items-center justify-end gap-x-2">- <NButton- v-if="release && isValidReleaseName(release.name)"- size="small"- tag="a"- text- :href="`/${release.name}`"- target="_blank"- icon-placement="right"- >- {{ $t("common.view") }}- <template #icon>- <ExternalLinkIcon class="w-4 h-4" />- </template>- </NButton>- </div>- </div>-- <div v-if="release" class="border rounded-md px-4 py-3 bg-gray-50">- <div class="flex flex-col gap-y-3">- <div class="flex items-start justify-between">- <div>- <h3 class="text-sm font-medium text-gray-900">- {{ releaseTitle }}- </h3>- <p v-if="release.name" class="text-xs text-gray-500 mt-1">- {{ release.name }}- </p>- </div>- </div>-- <div- v-if="release.files && release.files.length > 0"- class="flex flex-col gap-y-2"- >- <div class="flex items-center justify-between">- <h4 class="text-sm font-medium text-gray-700">- {{ $t("release.files") }} ({{ release.files.length }})- </h4>- <NButton- v-if="release.files.length > maxDisplayedFiles"- size="small"- quaternary- tag="a"- :href="`/${release.name}`"- target="_blank"- >- {{ $t("release.view-all-files") }}- </NButton>- </div>- <div- class="w-full grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-2"- >- <div- v-for="file in displayedFiles"- :key="file.path"- class="w-full flex items-center justify-between text-xs bg-white rounded-sm p-2"- >- <div class="flex-1 min-w-0 mr-2">- <div class="font-medium truncate">{{ file.path }}</div>- <div class="text-gray-500">{{ file.version }}</div>- </div>- <div- v-if="release.type"- :class="[- 'inline-flex items-center px-1.5 py-0.5 rounded-sm text-xs shrink-0',- 'bg-blue-100 text-blue-800 ',- ]"- >- {{ getReleaseFileTypeText(release.type) }}- </div>- </div>- <div- v-if="release.files.length > maxDisplayedFiles"- class="text-xs text-gray-500 text-center py-1"- >- {{- $t("release.and-n-more-files", {- count: release.files.length - maxDisplayedFiles,- })- }}- </div>- </div>- </div>-- <div v-if="release.vcsSource" class="flex flex-col gap-y-1">- <h4 class="text-sm font-medium text-gray-700">- {{ $t("release.vcs-source") }}- </h4>- <div class="text-xs">- <span class="text-gray-500"- >{{ getVCSTypeText(release.vcsSource.vcsType) }}:</span- >- <a- v-if="release.vcsSource.url"- :href="release.vcsSource.url"- target="_blank"- class="ml-1 text-blue-600 hover:text-blue-800"- >- {{ release.vcsSource.url }}- </a>- </div>- </div>-- <div class="text-xs text-gray-500">- {{- dayjs(getDateForPbTimestampProtoEs(release.createTime)).format(- "YYYY-MM-DD HH:mm:ss"- )- }}- </div>- </div>- </div>-- <div v-else-if="loading" class="border rounded-md p-4 bg-gray-50">- <div class="flex items-center gap-x-2">- <BBSpin />- <span class="text-sm text-gray-600">- {{ $t("common.loading") }}- </span>- </div>- </div>-- <div v-else class="border rounded-md p-4 bg-red-50 /20">- <div class="text-sm text-red-600">- {{ $t("release.not-found") }}- </div>- </div>- </div>-</template>--<script setup lang="ts">-import dayjs from "dayjs";-import { ExternalLinkIcon, PackageIcon } from "lucide-vue-next";-import { NAlert, NButton } from "naive-ui";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import { BBSpin } from "@/bbkit";-import { useReleaseByName } from "@/store";-import { getDateForPbTimestampProtoEs, isValidReleaseName } from "@/types";-import { VCSType } from "@/types/proto-es/v1/common_pb";-import { Release_Type } from "@/types/proto-es/v1/release_service_pb";-import { useSelectedSpec } from "../../SpecDetailView/context";--const { t } = useI18n();-const { selectedSpec } = useSelectedSpec();--const releaseName = computed(() => {- if (selectedSpec.value?.config?.case === "changeDatabaseConfig") {- return selectedSpec.value.config.value.release || "";- }- return "";-});--const { release, ready: loading } = useReleaseByName(releaseName);--const maxDisplayedFiles = 4;--const releaseTitle = computed(() => {- if (release.value && release.value.name) {- const parts = release.value.name.split("/");- return parts[parts.length - 1] || release.value.name;- }- if (releaseName.value) {- // Extract release name from the full resource name- const parts = releaseName.value.split("/");- return parts[parts.length - 1] || releaseName.value;- }- return t("release.title");-});--const displayedFiles = computed(() => {- if (!release.value?.files) return [];- return release.value.files.slice(0, maxDisplayedFiles);-});--const getReleaseFileTypeText = (fileType: Release_Type) => {- switch (fileType) {- case Release_Type.VERSIONED:- return t("release.file-type.versioned");- case Release_Type.DECLARATIVE:- return t("release.file-type.declarative");- case Release_Type.TYPE_UNSPECIFIED:- return t("release.file-type.unspecified");- default:- fileType satisfies never;- return t("release.file-type.unspecified");- }-};--const getVCSTypeText = (vcsType: VCSType) => {- switch (vcsType) {- case VCSType.GITHUB:- return "GitHub";- case VCSType.GITLAB:- return "GitLab";- case VCSType.BITBUCKET:- return "Bitbucket";- case VCSType.AZURE_DEVOPS:- return "Azure DevOps";- default:- return t("release.vcs-type.unspecified");- }-};-</script>diff --git a/frontend/src/components/Plan/components/StatementSection/ReleaseView/index.ts b/frontend/src/components/Plan/components/StatementSection/ReleaseView/index.tsdeleted file mode 100644index c92ede339b..0000000000--- a/frontend/src/components/Plan/components/StatementSection/ReleaseView/index.ts+++ /dev/null@@ -1 +0,0 @@-export { default } from "./ReleaseView.vue";diff --git a/frontend/src/components/Plan/components/StatementSection/SchemaEditorDrawer.vue b/frontend/src/components/Plan/components/StatementSection/SchemaEditorDrawer.vuedeleted file mode 100644index fdb5ea3b2b..0000000000--- a/frontend/src/components/Plan/components/StatementSection/SchemaEditorDrawer.vue+++ /dev/null@@ -1,227 +0,0 @@-<template>- <Drawer v-model:show="show" placement="right" :resizable="true">- <DrawerContent- :title="$t('schema-editor.self')"- class="w-[70vw] min-w-4xl max-w-[100vw]"- >- <div class="flex flex-col gap-y-4 h-full">- <!-- Database selector for multi-database scenarios -->- <div v-if="databaseNames.length > 1" class="flex items-center gap-x-2">- <span class="text-sm text-control-light">- {{ $t("schema-editor.template-database") }}:- </span>- <NSelect- v-model:show="showSelect"- :value="state.selectedDatabaseName"- :options="databaseOptions"- :disabled="state.isPreparingMetadata"- class="w-64"- @update:value="handleDatabaseChange"- >- <template #action>- <NButton- v-if="DEFAULT_VISIBLE_TARGETS * (state.databaseSelectorPageIndex + 1) < databaseNames.length"- class="w-full!"- quaternary- :loading="state.isLoadingNextPage"- @click="onNextPage">- {{ $t("common.load-more") }}- </NButton>- </template>- </NSelect>- </div>-- <SchemaEditorLite- ref="schemaEditorRef"- :project="project"- :targets="editTargets"- :loading="state.isPreparingMetadata"- class="flex-1"- />- </div>-- <template #footer>- <div class="flex items-center justify-end gap-x-2">- <NButton @click="handleCancel">- {{ $t("common.cancel") }}- </NButton>- <NButton- type="primary"- :disabled="!hasPendingChanges"- @click="handleInsertSQL"- >- {{ $t("schema-editor.insert-sql") }}- </NButton>- </div>- </template>- </DrawerContent>- </Drawer>-</template>--<script lang="ts" setup>-import { watchDebounced } from "@vueuse/core";-import { cloneDeep } from "lodash-es";-import { NButton, NSelect } from "naive-ui";-import { computed, nextTick, reactive, ref, watch } from "vue";-import SchemaEditorLite, {- type EditTarget,- generateDiffDDL,-} from "@/components/SchemaEditorLite";-import { Drawer, DrawerContent } from "@/components/v2";-import { useDatabaseV1Store, useDBSchemaV1Store } from "@/store";-import { DEBOUNCE_SEARCH_DELAY } from "@/types";-import type { Project } from "@/types/proto-es/v1/project_service_pb";-import { extractDatabaseResourceName, getInstanceResource } from "@/utils";-import { engineSupportsSchemaEditor } from "@/utils/schemaEditor";-import { DEFAULT_VISIBLE_TARGETS } from "../SpecDetailView/context";--const props = defineProps<{- show: boolean;- databaseNames: string[];- project: Project;-}>();--const emit = defineEmits<{- (event: "update:show", show: boolean): void;- (event: "insert", sql: string): void;-}>();--const show = computed({- get: () => props.show,- set: (value) => emit("update:show", value),-});--const schemaEditorRef = ref<InstanceType<typeof SchemaEditorLite>>();-const dbSchemaStore = useDBSchemaV1Store();-const databaseStore = useDatabaseV1Store();-const showSelect = ref(false);--const state = reactive({- isPreparingMetadata: false,- isLoadingNextPage: false,- targets: [] as EditTarget[],- selectedDatabaseName: "",- databaseSelectorPageIndex: 0,-});--const onNextPage = () => {- state.isLoadingNextPage = true;- state.databaseSelectorPageIndex++;- nextTick(() => (showSelect.value = true));-};--watchDebounced(- () => state.databaseSelectorPageIndex,- async (index) => {- try {- await databaseStore.batchGetOrFetchDatabases(- props.databaseNames.slice(- DEFAULT_VISIBLE_TARGETS * index,- DEFAULT_VISIBLE_TARGETS * (index + 1)- )- );- } finally {- state.isLoadingNextPage = false;- }- },- { immediate: true, debounce: DEBOUNCE_SEARCH_DELAY }-);--const databaseOptions = computed(() => {- const pageIndex = Math.max(- 0,- state.isLoadingNextPage- ? state.databaseSelectorPageIndex - 1- : state.databaseSelectorPageIndex- );- return props.databaseNames- .slice(0, DEFAULT_VISIBLE_TARGETS * (pageIndex + 1))- .map((dbName) => {- const db = databaseStore.getDatabaseByName(dbName);- const instanceResource = getInstanceResource(db);- return {- label: `${extractDatabaseResourceName(db.name).databaseName} (${instanceResource.title})`,- value: db.name,- disabled: !engineSupportsSchemaEditor(instanceResource.engine),- };- });-});--const editTargets = computed(() => state.targets);--const hasPendingChanges = computed(() => {- return schemaEditorRef.value?.isDirty ?? false;-});--const prepareDatabaseMetadata = async (databaseName: string) => {- if (!databaseName) return;-- state.isPreparingMetadata = true;- state.targets = [];-- const [metadata, database] = await Promise.all([- dbSchemaStore.getOrFetchDatabaseMetadata({- database: databaseName,- skipCache: true,- limit: 200,- }),- databaseStore.getOrFetchDatabaseByName(databaseName),- ]);-- state.targets = [- {- database: database,- metadata: cloneDeep(metadata),- baselineMetadata: metadata,- },- ];-- state.isPreparingMetadata = false;-};--const handleDatabaseChange = async (selectedDatabaseName: string) => {- if (selectedDatabaseName) {- await prepareDatabaseMetadata(selectedDatabaseName);- }- state.selectedDatabaseName = selectedDatabaseName;-};--watch(- () => props.show,- (show) => {- if (show && props.databaseNames.length > 0) {- // Initialize with first database- handleDatabaseChange(props.databaseNames[0]);- }- },- { immediate: true }-);--const handleCancel = () => {- show.value = false;-};--const handleInsertSQL = async () => {- const applyMetadataEdit = schemaEditorRef.value?.applyMetadataEdit;- if (typeof applyMetadataEdit !== "function") {- return;- }-- const target = state.targets[0];- if (!target) return;-- const { database, baselineMetadata } = target;- const { metadata } = applyMetadataEdit(database, target.metadata);-- const result = await generateDiffDDL({- database,- sourceMetadata: baselineMetadata,- targetMetadata: metadata,- });-- if (result.statement) {- emit("insert", result.statement);- show.value = false;- }-};-</script>diff --git a/frontend/src/components/Plan/components/StatementSection/StatementSection.vue b/frontend/src/components/Plan/components/StatementSection/StatementSection.vuedeleted file mode 100644index ba0b29f914..0000000000--- a/frontend/src/components/Plan/components/StatementSection/StatementSection.vue+++ /dev/null@@ -1,47 +0,0 @@-<template>- <EditorView- v-if="viewMode === 'EDITOR'"- :key="editorViewKey"- :header-variant="headerVariant"- />- <ReleaseView v-else-if="viewMode === 'RELEASE'" />-</template>--<script setup lang="ts">-import { computed } from "vue";-import { sheetNameForSpec } from "../../logic";-import { useSelectedSpec } from "../SpecDetailView/context";-import EditorView from "./EditorView";-import ReleaseView from "./ReleaseView";--withDefaults(- defineProps<{- headerVariant?: "editor" | "section";- }>(),- {- headerVariant: "editor",- }-);--const { selectedSpec } = useSelectedSpec();--const viewMode = computed((): "NONE" | "EDITOR" | "RELEASE" => {- if (selectedSpec.value) {- const spec = selectedSpec.value;- // Check if this is a release-based spec first.- if (- spec.config?.case === "changeDatabaseConfig" &&- spec.config.value.release- ) {- return "RELEASE";- }- // Otherwise, it's a sheet-based spec.- return "EDITOR";- }- return "NONE";-});--const editorViewKey = computed(() => {- return `${selectedSpec.value.id}-${sheetNameForSpec(selectedSpec.value)}`;-});-</script>diff --git a/frontend/src/components/Plan/components/StatementSection/directiveUtils.ts b/frontend/src/components/Plan/components/StatementSection/directiveUtils.tsdeleted file mode 100644index 5c72da7ce7..0000000000--- a/frontend/src/components/Plan/components/StatementSection/directiveUtils.ts+++ /dev/null@@ -1,252 +0,0 @@-/**- * Utilities for managing SQL directives and special statements in the editor.- *- * Directives are special comments that must appear at specific positions:- * - Transaction mode directive: Must be on line 1- * - Isolation level directive: Must be on line 2 (if txn-mode is on line 1)- *- * Special statements are SQL statements that get special handling:- * - SET ROLE statement: Can appear anywhere but is handled specially by backend- */--// Transaction mode directive pattern-const TXN_MODE_REGEX = /^\s*--\s*txn-mode\s*=\s*(on|off)\s*$/i;--// Isolation level directive pattern-const TXN_ISOLATION_REGEX =- /^\s*--\s*txn-isolation\s*=\s*(READ\s+UNCOMMITTED|READ\s+COMMITTED|REPEATABLE\s+READ|SERIALIZABLE)\s*$/i;--// PostgreSQL role setter pattern-// Matches PostgreSQL identifier rules: starts with letter/underscore, up to 63 chars-const ROLE_SETTER_REGEX =- /\/\*\s*=== Bytebase Role Setter\. DO NOT EDIT\. === \*\/\s*SET ROLE ([a-zA-Z_][a-zA-Z0-9_]{0,62});/;--// Ghost configuration directive pattern-// Matches: -- gh-ost = {"key":"value",...} or -- gh-ost = {} /*comment*/-const GHOST_DIRECTIVE_REGEX =- /^\s*--\s*gh-ost\s*=\s*(\{[^}]*\})\s*(?:\/\*.*\*\/)?\s*$/i;--export type IsolationLevel =- | "READ_UNCOMMITTED"- | "READ_COMMITTED"- | "REPEATABLE_READ"- | "SERIALIZABLE";--export interface ParsedStatement {- // Line 1 directive (currently only transaction mode)- transactionMode?: "on" | "off";- // Line 2 directive (isolation level, only valid when txn-mode is on)- isolationLevel?: IsolationLevel;- // Ghost configuration (JSON object with gh-ost flags)- ghostConfig?: Record<string, string>;- // Role setter block if present- roleSetterBlock?: string;- // The main SQL content (everything except directives and role setter)- mainContent: string;-}--/**- * Parses a SQL statement into its components.- */-export function parseStatement(statement: string): ParsedStatement {- const lines = statement.split("\n");- const result: ParsedStatement = {- mainContent: "",- };-- const directiveLines = new Set<number>();-- // Scan lines from the top, stopping at first non-comment/non-empty line- for (let i = 0; i < lines.length; i++) {- const line = lines[i];- const trimmed = line.trim();-- // Skip empty lines- if (trimmed === "") {- continue;- }-- // If it's not a comment, stop scanning for directives- if (!trimmed.startsWith("--")) {- break;- }-- // Check for transaction mode directive- const txnModeMatch = line.match(TXN_MODE_REGEX);- if (txnModeMatch) {- result.transactionMode = txnModeMatch[1].toLowerCase() as "on" | "off";- directiveLines.add(i);- continue;- }-- // Check for isolation level directive- const isolationMatch = line.match(TXN_ISOLATION_REGEX);- if (isolationMatch) {- // Normalize the isolation level string- const isolation = isolationMatch[1].toUpperCase().replace(/\s+/g, "_");- result.isolationLevel = isolation as IsolationLevel;- directiveLines.add(i);- continue;- }-- // Check for ghost directive- const ghostMatch = line.match(GHOST_DIRECTIVE_REGEX);- if (ghostMatch) {- try {- result.ghostConfig = JSON.parse(ghostMatch[1]);- } catch {- // Invalid JSON, treat as regular comment- }- directiveLines.add(i);- continue;- }- }-- // Build remaining content without directive lines- const remainingLines = lines.filter((_, i) => !directiveLines.has(i));- const remainingContent = remainingLines.join("\n");-- // Check for role setter block (can be anywhere in the remaining content)- const roleSetterMatch = remainingContent.match(ROLE_SETTER_REGEX);-- if (roleSetterMatch) {- result.roleSetterBlock = roleSetterMatch[0];- // Remove the role setter block from the content- result.mainContent = remainingContent.replace(ROLE_SETTER_REGEX, "").trim();- } else {- result.mainContent = remainingContent.trim();- }-- return result;-}--/**- * Rebuilds a SQL statement from its components, ensuring proper ordering.- * Directives are placed at the top, followed by role setter, then main content.- */-export function buildStatement(components: ParsedStatement): string {- const parts: string[] = [];-- // Add directives at the top (they can be in any order)- // Transaction mode directive (if present)- if (components.transactionMode !== undefined) {- parts.push(`-- txn-mode = ${components.transactionMode}`);- }-- // Isolation level directive (if present and txn-mode is not explicitly off)- if (- components.isolationLevel !== undefined &&- components.transactionMode !== "off"- ) {- // Convert back from underscore to space format- const isolation = components.isolationLevel.replace(/_/g, " ");- parts.push(`-- txn-isolation = ${isolation}`);- }-- // Ghost directive- if (components.ghostConfig !== undefined) {- if (Object.keys(components.ghostConfig).length === 0) {- parts.push(`-- gh-ost = {} /* using default config */`);- } else {- parts.push(- `-- gh-ost = ${JSON.stringify(- components.ghostConfig- )} /* merges with default config */`- );- }- }-- // Role setter block (if present) - place it before main content- if (components.roleSetterBlock) {- parts.push(components.roleSetterBlock);- }-- // Main SQL content- if (components.mainContent) {- parts.push(components.mainContent);- }-- return parts.filter((part) => part.length > 0).join("\n");-}--/**- * Updates the transaction mode in a statement while preserving other components.- */-export function updateTransactionMode(- statement: string,- mode: "on" | "off"-): string {- const parsed = parseStatement(statement);- parsed.transactionMode = mode;- return buildStatement(parsed);-}--/**- * Updates the isolation level in a statement while preserving other components.- */-export function updateIsolationLevel(- statement: string,- isolationLevel: IsolationLevel | undefined-): string {- const parsed = parseStatement(statement);- parsed.isolationLevel = isolationLevel;- return buildStatement(parsed);-}--/**- * Updates the role setter in a statement while preserving other components.- */-export function updateRoleSetter(- statement: string,- roleName: string | undefined-): string {- const parsed = parseStatement(statement);-- if (roleName) {- parsed.roleSetterBlock = `/* === Bytebase Role Setter. DO NOT EDIT. === */\nSET ROLE ${roleName};`;- } else {- parsed.roleSetterBlock = undefined;- }-- return buildStatement(parsed);-}--/**- * Updates the ghost configuration in a statement while preserving other components.- * Pass undefined to remove ghost config, or an empty object {} to enable ghost with no flags.- */-export function updateGhostConfig(- statement: string,- config: Record<string, string> | undefined-): string {- const parsed = parseStatement(statement);- parsed.ghostConfig = config;- return buildStatement(parsed);-}--/**- * Gets the ghost configuration from a statement.- * Returns undefined if no ghost directive is present.- */-export function getGhostConfig(- statement: string-): Record<string, string> | undefined {- const parsed = parseStatement(statement);- return parsed.ghostConfig;-}--/**- * Checks if ghost is enabled for a statement (directive is present).- */-export function isGhostEnabled(statement: string): boolean {- const parsed = parseStatement(statement);- return parsed.ghostConfig !== undefined;-}--/**- * Returns the default ghost configuration.- * Empty object {} means "use default config" - will be rendered as -- gh-ost = {} /*default config*\/- */-export function getDefaultGhostConfig(): Record<string, string> {- return {};-}diff --git a/frontend/src/components/Plan/components/StatementSection/index.ts b/frontend/src/components/Plan/components/StatementSection/index.tsdeleted file mode 100644index 0335cdfd21..0000000000--- a/frontend/src/components/Plan/components/StatementSection/index.ts+++ /dev/null@@ -1,6 +0,0 @@-import StatementSection from "./StatementSection.vue";--export default StatementSection;--export { default as EditorView } from "./EditorView";-export { default as ReleaseView } from "./ReleaseView";diff --git a/frontend/src/components/Plan/components/StatementSection/useSQLAdviceMarkers.ts b/frontend/src/components/Plan/components/StatementSection/useSQLAdviceMarkers.tsdeleted file mode 100644index 671ce15068..0000000000--- a/frontend/src/components/Plan/components/StatementSection/useSQLAdviceMarkers.ts+++ /dev/null@@ -1,100 +0,0 @@-import { maxBy } from "lodash-es";-import { computed, type Ref } from "vue";-import type { AdviceOption } from "@/components/MonacoEditor";-import type { PlanCheckRun } from "@/types/proto-es/v1/plan_service_pb";-import { PlanCheckRun_Result_Type } from "@/types/proto-es/v1/plan_service_pb";-import { type Advice, Advice_Level } from "@/types/proto-es/v1/sql_service_pb";-import { extractPlanCheckRunUID } from "@/utils";--export const useSQLAdviceMarkers = (- isCreating: Ref<boolean>,- planCheckRuns?: Ref<PlanCheckRun[]>,- advices?: Ref<Advice[] | undefined>-) => {- const markers = computed(() => {- if (isCreating.value) {- if (!advices) return [];- if (!advices.value) return [];- return advices.value- .filter((advice) => {- // Filter out advices without valid position (line 0 means unknown)- const line = advice.startPosition?.line ?? 0;- return line > 0;- })- .map<AdviceOption>((advice) => {- const line = advice.startPosition!.line;- const column = advice.startPosition!.column || 1;- const code = advice.code;- return {- severity:- advice.status === Advice_Level.ERROR ? "ERROR" : "WARNING",- message: advice.content,- source: `${advice.title} (${code}) L${line}:C${column}`,- startLineNumber: line,- endLineNumber: line,- startColumn: column,- endColumn: column,- };- });- } else {- if (!planCheckRuns) return [];- if (!planCheckRuns.value) return [];- // With consolidated model, filter results by type instead of checkRuns- return getLatestAdviceOptions(- planCheckRuns.value,- PlanCheckRun_Result_Type.STATEMENT_ADVISE- );- }- });- return { markers };-};--const getLatestAdviceOptions = (- planCheckRuns: PlanCheckRun[],- resultType: PlanCheckRun_Result_Type-) => {- const latest = maxBy(planCheckRuns, (checkRun) =>- parseInt(extractPlanCheckRunUID(checkRun.name), 10)- );- if (!latest) {- return [];- }- // O(n) over this run's results (consolidated model: one run, possibly many rows).- const resultList = latest.results.filter(- (result) => result.type === resultType- );- return resultList- .filter(- (result) =>- result.status === Advice_Level.ERROR ||- result.status === Advice_Level.WARNING- )- .filter(- (result) =>- result.report.case === "sqlReviewReport" &&- result.report.value.startPosition !== undefined- )- .filter((result) => {- // Filter out results without valid position (line 0 means unknown)- const sqlReviewReport =- result.report.case === "sqlReviewReport" ? result.report.value : null;- const line = sqlReviewReport?.startPosition?.line ?? 0;- return line > 0;- })- .map<AdviceOption>((result) => {- const sqlReviewReport =- result.report.case === "sqlReviewReport" ? result.report.value : null;- const line = sqlReviewReport!.startPosition!.line;- const column = sqlReviewReport!.startPosition!.column || 1;- const code = result.code;- return {- severity: result.status === Advice_Level.ERROR ? "ERROR" : "WARNING",- message: result.content,- source: `${result.title} (${code}) L${line}:C${column}`,- startLineNumber: line,- endLineNumber: line,- startColumn: column,- endColumn: column,- };- });-};diff --git a/frontend/src/components/Plan/components/StatementSection/useSpecSheet.ts b/frontend/src/components/Plan/components/StatementSection/useSpecSheet.tsdeleted file mode 100644index 5183b3d24e..0000000000--- a/frontend/src/components/Plan/components/StatementSection/useSpecSheet.ts+++ /dev/null@@ -1,74 +0,0 @@-import { type ComputedRef, computed, ref, watch } from "vue";-import { getLocalSheetByName } from "@/components/Plan";-import { useSheetV1Store } from "@/store";-import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";-import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";-import {- extractSheetUID,- getSheetStatement,- getStatementSize,- setSheetStatement,- sheetNameOfSpec,-} from "@/utils";--export const useSpecSheet = (spec: ComputedRef<Plan_Spec>) => {- const sheetStore = useSheetV1Store();-- const isFetchingSheet = ref(false);- const sheet = ref<Sheet | undefined>(undefined);- const sheetName = computed(() => sheetNameOfSpec(spec.value));- const sheetReady = computed(() => {- return !isFetchingSheet.value;- });-- const fetchSheet = async () => {- const name = sheetName.value;- const uid = extractSheetUID(name);- isFetchingSheet.value = true;- try {- if (uid.startsWith("-")) {- sheet.value = getLocalSheetByName(name);- } else {- sheet.value = await sheetStore.getOrFetchSheetByName(name);- }- } finally {- isFetchingSheet.value = false;- }- };-- watch(sheetName, fetchSheet, { immediate: true });- const sheetStatement = computed({- get() {- if (!sheetReady.value || !sheet.value) return "";- return getSheetStatement(sheet.value);- },- set(statement) {- if (!sheetReady.value || !sheet.value) return;- setSheetStatement(sheet.value, statement);- },- });-- const updateSheetStatement = (statement: string) => {- sheetStatement.value = statement;- };-- // Check if the sheet content is truncated (oversized).- // When contentSize > actual fetched statement size, the sheet was truncated- // during fetch. Modifying directives on truncated sheets would cause data loss.- const isSheetOversize = computed(() => {- if (!sheetReady.value) return false;- if (!sheet.value) return false;- return (- getStatementSize(getSheetStatement(sheet.value)) < sheet.value.contentSize- );- });-- return {- sheet,- sheetName,- sheetReady,- sheetStatement,- updateSheetStatement,- isSheetOversize,- };-};diff --git a/frontend/src/components/Plan/components/common/CheckResultItem.vue b/frontend/src/components/Plan/components/common/CheckResultItem.vuedeleted file mode 100644index 788528aee2..0000000000--- a/frontend/src/components/Plan/components/common/CheckResultItem.vue+++ /dev/null@@ -1,144 +0,0 @@-<template>- <div class="flex items-start gap-3 px-3 py-2 border rounded-lg bg-gray-50">- <component :is="statusIcon" class="w-5 h-5 shrink-0" :class="statusColor" />-- <div class="flex-1 min-w-0 flex flex-col gap-y-1">- <div class="text-sm font-medium text-main">- {{ displayTitle }}- </div>- <div v-if="content" class="text-sm text-control">- {{ content }}- </div>- <div- v-if="position && (position.line > 0 || position.column > 0)"- class="text-sm mt-1 text-control-light"- >- <template v-if="position.line > 0">- {{ $t("common.line") }} {{ position.line }}- </template>- <template v-if="position.line > 0 && position.column > 0">, </template>- <template v-if="position.column > 0">- {{ $t("common.column") }} {{ position.column }}- </template>- </div>- <div- v-if="affectedRows !== undefined"- class="text-sm mt-1 flex items-center gap-1"- >- <NTag size="small" round>- {{ $t("task.check-type.affected-rows.self") }}- </NTag>- <span>{{ affectedRows }}</span>- <span class="text-control opacity-80"- >({{ $t("task.check-type.affected-rows.description") }})</span- >- </div>- </div>- </div>-</template>--<script setup lang="ts">-import { AlertCircleIcon, CheckCircleIcon, XCircleIcon } from "lucide-vue-next";-import { NTag } from "naive-ui";-import { computed } from "vue";-import {- getRuleLocalization,- ruleTemplateMapV2,- ruleTypeToString,-} from "@/types";-import { SQLReviewRule_Type } from "@/types/proto-es/v1/review_config_service_pb";--export interface CheckResultPosition {- line: number;- column: number;-}--const props = defineProps<{- status: "SUCCESS" | "WARNING" | "ERROR";- title: string;- content?: string;- position?: CheckResultPosition;- affectedRows?: bigint;- code?: number;- reportType?: "sqlReviewReport" | "sqlSummaryReport";-}>();--const statusIcon = computed(() => {- switch (props.status) {- case "ERROR":- return XCircleIcon;- case "WARNING":- return AlertCircleIcon;- case "SUCCESS":- return CheckCircleIcon;- default:- return CheckCircleIcon;- }-});--const statusColor = computed(() => {- switch (props.status) {- case "ERROR":- return "text-error";- case "WARNING":- return "text-warning";- case "SUCCESS":- return "text-success";- default:- return "text-control";- }-});--const getRuleTemplateByType = (type: string) => {- // Convert string to enum- const typeKey = type as keyof typeof SQLReviewRule_Type;- const typeEnum = SQLReviewRule_Type[typeKey];- if (typeEnum === undefined) {- return;- }-- for (const mapByType of ruleTemplateMapV2.values()) {- if (mapByType.has(typeEnum)) {- return mapByType.get(typeEnum);- }- }- return;-};--const messageWithCode = (message: string, code: number | undefined): string => {- if (code !== undefined && code !== 0) {- return `${message} #${code}`;- }- return message;-};--const displayTitle = computed(() => {- // Skip localization for certain titles- if (props.title === "OK" || props.title === "Syntax error") {- return messageWithCode(props.title, props.code);- }-- // Only apply SQL review localization if this is a SQL review report- if (props.reportType === "sqlReviewReport") {- const code = props.code;- if (!code) {- return props.title;- }-- const rule = getRuleTemplateByType(props.title);- if (rule) {- const ruleLocalization = getRuleLocalization(- ruleTypeToString(rule.type),- rule.engine- );- const title = messageWithCode(ruleLocalization.title, code);- return title;- } else if (props.title.startsWith("builtin.")) {- return messageWithCode(getRuleLocalization(props.title).title, code);- }- }-- // Add error code if present- return messageWithCode(props.title, props.code);-});-</script>diff --git a/frontend/src/components/Plan/components/common/DatabaseDisplay.vue b/frontend/src/components/Plan/components/common/DatabaseDisplay.vuedeleted file mode 100644index df2a05f555..0000000000--- a/frontend/src/components/Plan/components/common/DatabaseDisplay.vue+++ /dev/null@@ -1,133 +0,0 @@-<template>- <div :class="containerClass">- <InstanceV1EngineIcon- v-if="instanceResource"- class="inline-block mr-1"- :instance="instanceResource"- :size="props.size || 'small'"- />- <span v-if="showEnvironment" class="text-gray-400 mr-1">- <EnvironmentV1Name- :link="false"- :environment="environment"- />- </span>- <span :class="isInstanceMissing ? 'truncate text-control-light line-through' : 'truncate text-gray-600'">- {{ instanceDisplayName }}- </span>- <ChevronRightIcon :class="chevronClass" />- <span class="truncate text-gray-800">- {{ databaseDisplayName }}- </span>- <router-link- v-if="props.showExternalLink"- class="pl-1 opacity-60 hover:opacity-100"- :to="`/${database}`"- target="_blank"- @click.stop- >- <ExternalLinkIcon :size="14" />- </router-link>- </div>-</template>--<script setup lang="ts">-import { ChevronRightIcon, ExternalLinkIcon } from "lucide-vue-next";-import { computed } from "vue";-import { EnvironmentV1Name, InstanceV1EngineIcon } from "@/components/v2";-import {- useDatabaseV1Store,- useEnvironmentV1Store,- useInstanceV1Store,-} from "@/store";-import { isValidDatabaseName, unknownInstance } from "@/types";-import {- extractDatabaseResourceName,- extractInstanceResourceName,-} from "@/utils";--const props = withDefaults(- defineProps<{- database: string;- showEnvironment?: boolean;- showExternalLink?: boolean;- size?: "small" | "medium" | "large";- }>(),- {- showExternalLink: true,- }-);--const environmentStore = useEnvironmentV1Store();-const instanceStore = useInstanceV1Store();--const databaseEntity = computed(() =>- useDatabaseV1Store().getDatabaseByName(props.database)-);--const instanceResource = computed(() => {- if (isValidDatabaseName(databaseEntity.value.name)) {- return databaseEntity.value.instanceResource;- }- // Extract instance name from the database name (which is actually a target string)- const instanceName = extractInstanceResourceName(props.database);- if (instanceName) {- const instance = instanceStore.getInstanceByName(- `instances/${instanceName}`- );- if (instance.name !== unknownInstance().name) {- return instance;- }- }-- return null; // Don't show instance icon if we can't resolve it-});--const isInstanceMissing = computed(() => {- return (- instanceResource.value === null &&- !!extractInstanceResourceName(props.database)- );-});--const instanceDisplayName = computed(() => {- if (instanceResource.value) {- return instanceResource.value.title;- }- return extractInstanceResourceName(props.database) || "Unknown Instance";-});--const databaseDisplayName = computed(() => {- const { databaseName } = extractDatabaseResourceName(props.database);- return databaseName || "Unknown Database";-});--const environment = computed(() => {- const environmentName =- databaseEntity.value.effectiveEnvironment ??- instanceResource.value?.environment ??- "";-- return environmentStore.getEnvironmentByName(environmentName);-});--const containerClass = computed(() => {- const baseClass = "flex items-center truncate";- const sizeClasses = {- small: "text-xs",- medium: "text-sm",- large: "text-base",- };- return [baseClass, sizeClasses[props.size || "medium"]];-});--const chevronClass = computed(() => {- const baseClass = "inline opacity-60 text-gray-500 shrink-0";- const sizeClasses = {- small: "w-3 h-3",- medium: "w-4 h-4",- large: "w-5 h-5",- };- return [baseClass, sizeClasses[props.size || "medium"]];-});-</script>diff --git a/frontend/src/components/Plan/components/common/ErrorList.vue b/frontend/src/components/Plan/components/common/ErrorList.vuedeleted file mode 100644index da82a653fe..0000000000--- a/frontend/src/components/Plan/components/common/ErrorList.vue+++ /dev/null@@ -1,23 +0,0 @@-<template>- <ul- class="flex flex-col whitespace-nowrap"- :class="[errors.length > 1 && bullets && 'list-disc pl-4']"- >- <li v-for="(error, i) in errors" :key="i">- <slot name="prefix" />- {{ error }}- </li>- </ul>-</template>--<script setup lang="ts">-withDefaults(- defineProps<{- errors: string[];- bullets?: boolean;- }>(),- {- bullets: true,- }-);-</script>diff --git a/frontend/src/components/Plan/components/common/index.ts b/frontend/src/components/Plan/components/common/index.tsdeleted file mode 100644index 67a174ea46..0000000000--- a/frontend/src/components/Plan/components/common/index.ts+++ /dev/null@@ -1,4 +0,0 @@-import ErrorList from "./ErrorList.vue";--export { ErrorList };-export * from "./validateSpec";diff --git a/frontend/src/components/Plan/components/common/validateSpec.ts b/frontend/src/components/Plan/components/common/validateSpec.tsdeleted file mode 100644index 3bbd502a49..0000000000--- a/frontend/src/components/Plan/components/common/validateSpec.ts+++ /dev/null@@ -1,75 +0,0 @@-import { type Ref, ref, unref, watchEffect } from "vue";-import { getLocalSheetByName } from "@/components/Plan";-import { useSheetV1Store } from "@/store";-import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";-import { extractSheetUID, getSheetStatement, sheetNameOfSpec } from "@/utils";--// Hook to validate all specs in a plan-export const useSpecsValidation = (specs: Plan_Spec[] | Ref<Plan_Spec[]>) => {- const sheetStore = useSheetV1Store();- const validationMap = ref(new Map<string, boolean>());-- const checkSpecStatement = async (spec: Plan_Spec): Promise<boolean> => {- // Only changeDatabaseConfig and exportDataConfig specs have statements- if (- spec.config?.case !== "changeDatabaseConfig" &&- spec.config?.case !== "exportDataConfig"- ) {- return false;- }-- // Released specs are not editable- if (- spec.config?.case === "changeDatabaseConfig" &&- spec.config.value.release- ) {- return false;- }-- const sheetName = sheetNameOfSpec(spec);- // If there's no sheet reference, it's definitely empty- if (!sheetName) {- return true;- }-- try {- // Get sheet content- const uid = extractSheetUID(sheetName);- const sheet = uid.startsWith("-")- ? getLocalSheetByName(sheetName)- : await sheetStore.getOrFetchSheetByName(sheetName);-- if (!sheet) {- return true; // Consider empty if sheet not found- }-- const statement = getSheetStatement(sheet);- return !statement || statement.trim() === "";- } catch {- return false; // If error, don't show as empty- }- };-- watchEffect(async () => {- const currentSpecs = unref(specs);- const newMap = new Map<string, boolean>();-- // Check all specs- await Promise.all(- currentSpecs.map(async (spec) => {- const isEmpty = await checkSpecStatement(spec);- newMap.set(spec.id, isEmpty);- })- );-- validationMap.value = newMap;- });-- const isSpecEmpty = (spec: Plan_Spec): boolean => {- return validationMap.value.get(spec.id) ?? false;- };-- return {- isSpecEmpty,- };-};diff --git a/frontend/src/components/Plan/components/index.ts b/frontend/src/components/Plan/components/index.tsdeleted file mode 100644index 2d5cdf7558..0000000000--- a/frontend/src/components/Plan/components/index.ts+++ /dev/null@@ -1,15 +0,0 @@-import BannerSection from "./BannerSection";-import { ChecksView } from "./ChecksView";-import HeaderSection from "./HeaderSection";-import SQLCheckSection from "./SQLCheckSection";-import SpecDetailView from "./SpecDetailView";-import StatementSection from "./StatementSection";--export {- BannerSection,- ChecksView,- HeaderSection,- SpecDetailView,- SQLCheckSection,- StatementSection,-};diff --git a/frontend/src/components/Plan/index.ts b/frontend/src/components/Plan/index.tsindex 7f78438747..f1104893b6 100644--- a/frontend/src/components/Plan/index.ts+++ b/frontend/src/components/Plan/index.ts@@ -1,2 +1 @@export * from "./logic";-export { default as AddSpecDrawer } from "./components/AddSpecDrawer.vue";diff --git a/frontend/src/components/Plan/logic/context.ts b/frontend/src/components/Plan/logic/context.tsindex 907a5e66bc..bd36e72aea 100644--- a/frontend/src/components/Plan/logic/context.ts+++ b/frontend/src/components/Plan/logic/context.ts@@ -8,13 +8,12 @@ import type { Plan, PlanCheckRun } from "@/types/proto-es/v1/plan_service_pb";import { type Project } from "@/types/proto-es/v1/project_service_pb";import type { Rollout, TaskRun } from "@/types/proto-es/v1/rollout_service_pb";import { hasProjectPermissionV2 } from "@/utils";-import type {- IssueReviewAction,- IssueStatusAction,-} from "../components/HeaderSection/Actions/registry";export type RefreshMode = "normal" | "fast-follow";+type IssueReviewAction = string;+type IssueStatusAction = string;+export type PlanEvents = Emittery<{"status-changed": {eager: boolean;diff --git a/frontend/src/components/PlanCheckRun/PlanCheckResultDefinitionModal.vue b/frontend/src/components/PlanCheckRun/PlanCheckResultDefinitionModal.vuedeleted file mode 100644index f4d33a011d..0000000000--- a/frontend/src/components/PlanCheckRun/PlanCheckResultDefinitionModal.vue+++ /dev/null@@ -1,27 +0,0 @@-<template>- <BBModal :title="$t('sql-review.view-definition')" @close="emit('close')">- <div class="flex flex-col gap-y-4 w-[calc(100vw-5rem)] sm:w-[40rem] pb-1">- <div class="flex flex-col gap-y-1">- <div class="flex flex-col gap-x-2 whitespace-pre-wrap">- {{ definition }}- </div>- </div>- <div class="mt-4 pt-2 border-t flex justify-end">- <NButton @click.prevent="emit('close')">- {{ $t("common.close") }}- </NButton>- </div>- </div>- </BBModal>-</template>--<script lang="ts" setup>-import { NButton } from "naive-ui";-import { BBModal } from "@/bbkit";--defineProps<{ definition: string }>();--const emit = defineEmits<{- (event: "close"): void;-}>();-</script>diff --git a/frontend/src/components/PlanCheckRun/PlanCheckRunBadge.vue b/frontend/src/components/PlanCheckRun/PlanCheckRunBadge.vuedeleted file mode 100644index 25ee3d019a..0000000000--- a/frontend/src/components/PlanCheckRun/PlanCheckRunBadge.vue+++ /dev/null@@ -1,124 +0,0 @@-<template>- <NTag- :class="[selected && 'shadow-sm']"- :type="tagType"- round- :bordered="selected"- @click="clickable && $emit('click')"- >- <template #icon>- <template v-if="status === PlanCheckRun_Status.RUNNING">- <TaskSpinner class="h-4 w-4 text-info" />- </template>- <template v-else-if="status === PlanCheckRun_Status.DONE">- <CheckIcon- v-if="resultStatus === Advice_Level.SUCCESS"- class="text-success"- :size="16"- />- <TriangleAlertIcon- v-else-if="resultStatus === Advice_Level.WARNING"- :size="16"- />- <CircleAlertIcon- v-else-if="resultStatus === Advice_Level.ERROR"- :size="16"- />- </template>- <template v-else-if="status === PlanCheckRun_Status.FAILED">- <CircleAlertIcon :size="16" />- </template>- <template v-else-if="status === PlanCheckRun_Status.CANCELED">- <TriangleAlertIcon :size="16" />- </template>- </template>- <span>{{ title }}</span>- </NTag>-</template>--<script setup lang="ts">-import { maxBy } from "lodash-es";-import { CheckIcon, CircleAlertIcon, TriangleAlertIcon } from "lucide-vue-next";-import { NTag } from "naive-ui";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import TaskSpinner from "@/components/misc/TaskSpinner.vue";-import type { PlanCheckRun } from "@/types/proto-es/v1/plan_service_pb";-import {- PlanCheckRun_Result_Type,- PlanCheckRun_Status,-} from "@/types/proto-es/v1/plan_service_pb";-import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";-import { extractPlanCheckRunUID } from "@/utils";-import { planCheckRunResultStatus } from "./common";--const props = defineProps<{- planCheckRuns: PlanCheckRun[];- type: PlanCheckRun_Result_Type;- clickable?: boolean;- selected?: boolean;-}>();--defineEmits<{- (event: "click"): void;-}>();--const { t } = useI18n();--const latestPlanCheckRun = computed(() => {- // Get the latest PlanCheckRun by UID.- return maxBy(props.planCheckRuns, (check) =>- Number(extractPlanCheckRunUID(check.name))- )!;-});--const status = computed(() => {- return latestPlanCheckRun.value.status;-});--const tagType = computed(() => {- if (latestPlanCheckRun.value.status === PlanCheckRun_Status.FAILED) {- return "error";- }- if (latestPlanCheckRun.value.status === PlanCheckRun_Status.CANCELED) {- return "warning";- }- if (latestPlanCheckRun.value.status === PlanCheckRun_Status.RUNNING) {- return "info";- }- if (latestPlanCheckRun.value.status !== PlanCheckRun_Status.DONE) {- // Should not reach here.- return "default";- }-- switch (planCheckRunResultStatus(latestPlanCheckRun.value)) {- case Advice_Level.SUCCESS:- return "default";- case Advice_Level.WARNING:- return "warning";- case Advice_Level.ERROR:- return "error";- }- // Should not reach here.- return "default";-});--const resultStatus = computed(() => {- return planCheckRunResultStatus(latestPlanCheckRun.value);-});--const title = computed(() => {- // Use the type prop directly instead of getting from checkRun- switch (props.type) {- case PlanCheckRun_Result_Type.STATEMENT_ADVISE:- return t("task.check-type.sql-review.self");- case PlanCheckRun_Result_Type.GHOST_SYNC:- return t("task.check-type.ghost-sync");- case PlanCheckRun_Result_Type.STATEMENT_SUMMARY_REPORT:- return t("task.check-type.summary-report");- default:- console.assert(false, `Missing PlanCheckType name of "${props.type}"`);- return String(props.type);- }-});-</script>diff --git a/frontend/src/components/PlanCheckRun/PlanCheckRunBadgeBar.vue b/frontend/src/components/PlanCheckRun/PlanCheckRunBadgeBar.vuedeleted file mode 100644index 16e85af4ce..0000000000--- a/frontend/src/components/PlanCheckRun/PlanCheckRunBadgeBar.vue+++ /dev/null@@ -1,74 +0,0 @@-<template>- <div class="flex items-center flex-wrap sm:gap-2 gap-1 flex-1">- <PlanCheckRunBadge- v-for="group in planCheckRunsGroupByType"- :key="group.type"- :type="group.type"- :clickable="true"- :selected="group.type === selectedType"- :planCheckRuns="group.list"- @click="$emit('select-type', group.type)"- />- </div>-</template>--<script lang="ts" setup>-import { orderBy } from "lodash-es";-import { computed } from "vue";-import {- type PlanCheckRun,- PlanCheckRun_Result_Type,-} from "@/types/proto-es/v1/plan_service_pb";-import { HiddenPlanCheckTypes } from "./common";-import PlanCheckRunBadge from "./PlanCheckRunBadge.vue";--const props = defineProps<{- planCheckRunList: PlanCheckRun[];- selectedType?: PlanCheckRun_Result_Type;-}>();--defineEmits<{- (event: "select-type", type: PlanCheckRun_Result_Type): void;-}>();--const planCheckRunsGroupByType = computed(() => {- // With consolidated model, group by result type across all runs- const typeToRuns = new Map<PlanCheckRun_Result_Type, PlanCheckRun[]>();-- for (const run of props.planCheckRunList) {- for (const result of run.results) {- if (HiddenPlanCheckTypes.has(result.type)) {- continue;- }- if (!typeToRuns.has(result.type)) {- typeToRuns.set(result.type, []);- }- // Add the run if not already added for this type- const runs = typeToRuns.get(result.type)!;- if (!runs.includes(run)) {- runs.push(run);- }- }- }-- const list = Array.from(typeToRuns.entries()).map(([type, list]) => ({- type,- list,- }));-- // Sort by pre-defined orders- return orderBy(- list,- [(group) => PlanCheckTypeOrderDict.get(group.type) ?? 99999],- "asc"- );-});--const PlanCheckTypeOrderList: PlanCheckRun_Result_Type[] = [- PlanCheckRun_Result_Type.GHOST_SYNC,- PlanCheckRun_Result_Type.STATEMENT_ADVISE,-];-const PlanCheckTypeOrderDict = new Map<PlanCheckRun_Result_Type, number>(- PlanCheckTypeOrderList.map((type, order) => [type, order])-);-</script>diff --git a/frontend/src/components/PlanCheckRun/PlanCheckRunBar.vue b/frontend/src/components/PlanCheckRun/PlanCheckRunBar.vuedeleted file mode 100644index e2c5dd2040..0000000000--- a/frontend/src/components/PlanCheckRun/PlanCheckRunBar.vue+++ /dev/null@@ -1,77 +0,0 @@-<template>- <div class="w-full flex items-start gap-x-4 flex-wrap">- <div- class="text-base font-medium inline-flex items-center"- :class="labelClass"- >- {{ $t("task.task-checks") }}- </div>-- <div class="flex-1">- <PlanCheckRunBadgeBar- :plan-check-run-list="planCheckRunList"- @select-type="selectedType = $event"- />- </div>-- <div class="flex justify-end items-center shrink-0">- <PlanCheckRunButton- v-if="allowRunChecks"- :plan-check-run-list="planCheckRunList"- @run-checks="runChecks"- />- </div>-- <PlanCheckRunModal- v-if="planCheckRunList.length > 0 && selectedType"- :selected-type="selectedType"- :plan-check-run-list="planCheckRunList"- :database="database"- @close="selectedType = undefined"- />- </div>-</template>--<script lang="ts" setup>-import { create } from "@bufbuild/protobuf";-import { ref } from "vue";-import { planServiceClientConnect } from "@/connect";-import type { Database } from "@/types/proto-es/v1/database_service_pb";-import type { PlanCheckRun } from "@/types/proto-es/v1/plan_service_pb";-import {- PlanCheckRun_Result_Type,- RunPlanChecksRequestSchema,-} from "@/types/proto-es/v1/plan_service_pb";-import type { VueClass } from "@/utils";-import { usePlanCheckRunContext } from "./context";-import PlanCheckRunBadgeBar from "./PlanCheckRunBadgeBar.vue";-import PlanCheckRunButton from "./PlanCheckRunButton.vue";-import PlanCheckRunModal from "./PlanCheckRunModal.vue";--const props = withDefaults(- defineProps<{- allowRunChecks?: boolean;- labelClass?: VueClass;- planName: string;- planCheckRunList?: PlanCheckRun[];- database: Database;- }>(),- {- allowRunChecks: true,- labelClass: "",- planCheckRunList: () => [],- }-);--const { events } = usePlanCheckRunContext();--const selectedType = ref<PlanCheckRun_Result_Type>();--const runChecks = async () => {- const request = create(RunPlanChecksRequestSchema, {- name: props.planName,- });- await planServiceClientConnect.runPlanChecks(request);- events.emit("status-changed");-};-</script>diff --git a/frontend/src/components/PlanCheckRun/PlanCheckRunButton.vue b/frontend/src/components/PlanCheckRun/PlanCheckRunButton.vuedeleted file mode 100644index 8ef8ca7b30..0000000000--- a/frontend/src/components/PlanCheckRun/PlanCheckRunButton.vue+++ /dev/null@@ -1,35 +0,0 @@-<template>- <NButton size="small" :loading="hasRunningPlanCheck" @click="handleRunChecks">- <template #icon>- <PlayIcon />- </template>- {{ hasRunningPlanCheck ? $t("task.checking") : $t("task.run-checks") }}- </NButton>-</template>--<script setup lang="ts">-import { PlayIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { computed } from "vue";-import type { PlanCheckRun } from "@/types/proto-es/v1/plan_service_pb";-import { PlanCheckRun_Status } from "@/types/proto-es/v1/plan_service_pb";--const props = defineProps<{- planCheckRunList: PlanCheckRun[];-}>();--const emit = defineEmits<{- (event: "run-checks"): void;-}>();--const hasRunningPlanCheck = computed((): boolean => {- return props.planCheckRunList.some(- (checkRun) => checkRun.status === PlanCheckRun_Status.RUNNING- );-});--const handleRunChecks = () => {- if (hasRunningPlanCheck.value) return;- emit("run-checks");-};-</script>diff --git a/frontend/src/components/PlanCheckRun/PlanCheckRunModal.vue b/frontend/src/components/PlanCheckRun/PlanCheckRunModal.vuedeleted file mode 100644index a75183bb4f..0000000000--- a/frontend/src/components/PlanCheckRun/PlanCheckRunModal.vue+++ /dev/null@@ -1,34 +0,0 @@-<template>- <BBModal- :title="$t('task.check-result.title-general')"- class="w-4xl!"- header-class="whitespace-pre-wrap break-all gap-x-1"- :mask-closable="true"- @close="$emit('close')"- >- <PlanCheckRunPanel- :plan-check-run-list="planCheckRunList"- :selected-type="selectedType"- :database="database"- @close="$emit('close')"- />- </BBModal>-</template>--<script setup lang="ts">-import { BBModal } from "@/bbkit";-import type { Database } from "@/types/proto-es/v1/database_service_pb";-import type { PlanCheckRun } from "@/types/proto-es/v1/plan_service_pb";-import { PlanCheckRun_Result_Type } from "@/types/proto-es/v1/plan_service_pb";-import PlanCheckRunPanel from "./PlanCheckRunPanel.vue";--defineProps<{- planCheckRunList: PlanCheckRun[];- selectedType: PlanCheckRun_Result_Type;- database: Database;-}>();--defineEmits<{- (event: "close"): void;-}>();-</script>diff --git a/frontend/src/components/PlanCheckRun/PlanCheckRunPanel.vue b/frontend/src/components/PlanCheckRun/PlanCheckRunPanel.vuedeleted file mode 100644index 3b85f1ee9e..0000000000--- a/frontend/src/components/PlanCheckRun/PlanCheckRunPanel.vue+++ /dev/null@@ -1,137 +0,0 @@-<template>- <div class="flex flex-col gap-y-2">- <TabFilter- v-if="selectedPlanCheckRunName && tabItemList.length > 1"- v-model:value="selectedPlanCheckRunName"- :items="tabItemList"- />-- <PlanCheckRunBadgeBar- :plan-check-run-list="planCheckRunList"- :selected-type="selectedTypeRef"- @select-type="handlePlanCheckRunTypeChange"- />-- <PlanCheckRunDetail- v-if="selectedPlanCheckRun"- :plan-check-run="selectedPlanCheckRun"- :selected-type="selectedTypeRef"- :database="database"- :show-code-location="isLatestPlanCheckRun"- />- </div>-</template>--<script setup lang="ts">-import { first, orderBy } from "lodash-es";-import { computed, ref } from "vue";-import { useI18n } from "vue-i18n";-import type { TabFilterItem } from "@/components/v2";-import { TabFilter } from "@/components/v2";-import { getDateForPbTimestampProtoEs } from "@/types";-import type { Database } from "@/types/proto-es/v1/database_service_pb";-import {- type PlanCheckRun,- PlanCheckRun_Result_Type,-} from "@/types/proto-es/v1/plan_service_pb";-import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";-import { extractPlanCheckRunUID, humanizeDate } from "@/utils";-import { HiddenPlanCheckTypes } from "./common";-import PlanCheckRunBadgeBar from "./PlanCheckRunBadgeBar.vue";-import PlanCheckRunDetail from "./PlanCheckRunDetail.vue";--const props = defineProps<{- planCheckRunList: PlanCheckRun[];- database: Database;- selectedType?: PlanCheckRun_Result_Type;-}>();--const getInitialSelectedType = () => {- if (props.selectedType) {- return props.selectedType;- }-- // Find the first result type with error or warning- for (const run of props.planCheckRunList) {- for (const result of run.results) {- if (HiddenPlanCheckTypes.has(result.type)) {- continue;- }- if (- result.status === Advice_Level.ERROR ||- result.status === Advice_Level.WARNING- ) {- return result.type;- }- }- }-- // Fall back to first non-hidden result type- for (const run of props.planCheckRunList) {- for (const result of run.results) {- if (!HiddenPlanCheckTypes.has(result.type)) {- return result.type;- }- }- }-- return PlanCheckRun_Result_Type.TYPE_UNSPECIFIED;-};--const { t } = useI18n();-const selectedTypeRef = ref<PlanCheckRun_Result_Type>(getInitialSelectedType());--const selectedPlanCheckRunList = computed(() => {- // With consolidated model, return runs that have results of the selected type- return orderBy(- props.planCheckRunList.filter((run) =>- run.results.some((result) => result.type === selectedTypeRef.value)- ),- (checkRun) => parseInt(extractPlanCheckRunUID(checkRun.name), 10),- "desc"- );-});--const selectedPlanCheckRunName = ref(- first(selectedPlanCheckRunList.value)?.name-);--const selectedPlanCheckRun = computed(() => {- const name = selectedPlanCheckRunName.value;- if (!name) return undefined;- return selectedPlanCheckRunList.value.find(- (checkRun) => checkRun.name === name- );-});--const isLatestPlanCheckRun = computed(() => {- return (- selectedPlanCheckRunName.value ===- first(selectedPlanCheckRunList.value)?.name- );-});--const tabItemList = computed(() => {- return selectedPlanCheckRunList.value.map<TabFilterItem<string>>(- (planCheckRun, i) => {- const label =- i === 0- ? t("common.latest")- : planCheckRun.createTime- ? humanizeDate(- getDateForPbTimestampProtoEs(planCheckRun.createTime)- )- : `UID(${extractPlanCheckRunUID(planCheckRun.name)})`;- return {- label,- value: planCheckRun.name,- };- }- );-});--const handlePlanCheckRunTypeChange = (type: PlanCheckRun_Result_Type) => {- selectedTypeRef.value = type;- selectedPlanCheckRunName.value = first(selectedPlanCheckRunList.value)?.name;-};-</script>diff --git a/frontend/src/components/Revision/CreateRevisionDrawer.vue b/frontend/src/components/Revision/CreateRevisionDrawer.vuedeleted file mode 100644index e426cea00a..0000000000--- a/frontend/src/components/Revision/CreateRevisionDrawer.vue+++ /dev/null@@ -1,875 +0,0 @@-<template>- <Drawer- v-model:show="show"- :mask-closable="true"- placement="right"- :default-width="1024"- :resizable="true"- :width="undefined"- class="max-w-[90vw]!"- >- <DrawerContent :title="$t('database.revision.import-revision')" closable>- <div class="flex flex-col gap-y-4">- <!-- Steps indicator -->- <NSteps :current="currentStep">- <NStep :title="$t('database.revision.select-source')" />- <NStep- v-if="selectedSource === 'release'"- :title="$t('database.revision.select-release')"- />- <NStep- v-if="selectedSource === 'release'"- :title="$t('database.revision.select-files')"- />- <NStep- v-if="selectedSource === 'local'"- :title="$t('database.revision.upload-files')"- />- </NSteps>-- <!-- Step content -->- <div class="flex-1">- <!-- Step 1: Select Source -->- <template v-if="currentStep === Step.SELECT_SOURCE">- <NRadioGroup- v-model:value="selectedSource"- size="large"- class="flex flex-col gap-y-4 w-full"- >- <div- class="border border-gray-200 rounded-lg p-4 hover:border-gray-300 transition-colors mb-4"- :class="{- 'border-blue-500 bg-blue-50': selectedSource === 'release',- }"- >- <NRadio value="release" class="w-full">- <div class="flex items-start gap-x-3 w-full">- <PackageIcon- class="w-6 h-6 mt-1 shrink-0"- :stroke-width="1.5"- />- <div class="flex-1">- <div class="flex items-center gap-x-2">- <span class="text-lg font-medium text-gray-900">- {{ $t("database.revision.from-release") }}- </span>- </div>- <p class="text-sm text-gray-600 mt-1">- {{ $t("database.revision.from-release-description") }}- </p>- </div>- </div>- </NRadio>- </div>- <div- class="border border-gray-200 rounded-lg p-4 hover:border-gray-300 transition-colors"- :class="{- 'border-blue-500 bg-blue-50': selectedSource === 'local',- }"- >- <NRadio value="local" class="w-full">- <div class="flex items-start gap-x-3 w-full">- <FolderOpenIcon- class="w-6 h-6 mt-1 shrink-0"- :stroke-width="1.5"- />- <div class="flex-1">- <div class="flex items-center gap-x-2">- <span class="text-lg font-medium text-gray-900">- {{ $t("database.revision.from-local-files") }}- </span>- </div>- <p class="text-sm text-gray-600 mt-1">- {{- $t("database.revision.from-local-files-description")- }}- </p>- </div>- </div>- </NRadio>- </div>- </NRadioGroup>- </template>-- <!-- Step 2: Upload Local Files (for local source) -->- <template- v-else-if="- currentStep === Step.UPLOAD_FILES && selectedSource === 'local'- "- >- <div class="flex flex-col gap-y-4">- <div class="text-sm text-gray-600">- {{ $t("database.revision.upload-files-description") }}- </div>-- <!-- File upload area (only show when no files selected) -->- <div- v-if="localFiles.length === 0"- class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-gray-400 transition-colors cursor-pointer"- @click="triggerFileInput"- @dragover.prevent- @drop.prevent="handleFileDrop"- >- <input- ref="fileInput"- type="file"- multiple- accept=".sql,.txt,.md,text/plain,text/markdown,text/x-sql"- class="hidden"- @change="handleFileSelect"- />- <FolderOpenIcon class="w-12 h-12 mx-auto text-gray-400 mb-3" />- <p class="text-sm text-gray-600">- {{ $t("database.revision.drag-drop-or-click") }}- </p>- <p class="text-xs text-gray-500 mt-1">- {{ $t("database.revision.supported-formats") }}- </p>- </div>-- <!-- Hidden file input for when files are already selected -->- <input- v-else- ref="fileInput"- type="file"- multiple- accept=".sql,.txt,.md,text/plain,text/markdown,text/x-sql"- class="hidden"- @change="handleFileSelect"- />-- <!-- Uploaded files list -->- <div v-if="localFiles.length > 0" class="flex flex-col gap-y-3">- <div class="flex items-center justify-between">- <h4 class="font-medium text-control">- {{ $t("database.revision.uploaded-files") }}- <span- v-if="localFiles.length > 1"- class="text-control-light"- >- ({{ localFiles.length }})- </span>- </h4>- <NButton size="small" @click="triggerFileInput">- <template #icon>- <PlusIcon class="w-4 h-4" />- </template>- {{ $t("database.revision.add-more-files") }}- </NButton>- </div>- <div- v-for="(file, index) in localFiles"- :key="index"- class="border border-gray-200 rounded-lg p-4 flex flex-col gap-y-3"- >- <div class="flex items-start justify-between">- <div class="flex-1 flex flex-col gap-y-3">- <div class="flex items-center gap-2">- <FileIcon class="w-4 h-4 text-gray-500" />- <span class="text-sm font-medium">{{ file.name }}</span>- <span class="text-xs text-gray-500"- >({{ formatFileSize(file.size) }})</span- >- </div>-- <!-- Version and Type inputs -->- <div class="grid grid-cols-4 gap-3">- <div class="col-span-3">- <label class="block text-xs text-gray-500 mb-1">- {{ $t("common.version") }} *- </label>- <NInput- v-model:value="file.version"- size="small"- placeholder="e.g., 1.0.0"- :status="getVersionStatus(file.version)"- />- <p- v-if="- file.version && !validateVersion(file.version)- "- class="text-xs text-red-600 mt-1"- >- {{ $t("database.revision.invalid-version-format") }}- </p>- <p- v-else-if="- file.version && isVersionDuplicate(file.version)- "- class="text-xs text-red-600 mt-1"- >- {{ $t("database.revision.version-already-exists") }}- </p>- </div>- <div class="col-span-1">- <label class="block text-xs text-gray-500 mb-1">- {{ $t("database.revision.revision-type") }}- </label>- <NSelect- v-model:value="file.type"- size="small"- :options="revisionTypeOptions"- />- </div>- </div>-- <!-- File content preview -->- <div v-if="file.content" class="mt-2">- <label class="block text-xs text-gray-500 mb-1">- {{ $t("database.revision.content-preview") }}- </label>- <div- class="bg-gray-50 rounded-sm p-2 text-xs font-mono text-gray-700 max-h-32 overflow-auto"- >- <pre- >{{ file.content.substring(0, 500)- }}{{ file.content.length > 500 ? "..." : "" }}</pre- >- </div>- </div>- </div>- <NButton- quaternary- size="tiny"- @click="removeLocalFile(index)"- >- <XIcon class="w-4 h-4" />- </NButton>- </div>- </div>- </div>- </div>- </template>-- <!-- Step 2: Select Release (for release source) -->- <template- v-else-if="- currentStep === Step.SELECT_RELEASE &&- selectedSource === 'release'- "- >- <div class="flex flex-col gap-y-4">- <div class="text-sm text-gray-600">- {{ $t("database.revision.select-release-description") }}- </div>- <ReleaseDataTable- v-if="releaseList.length > 0"- :release-list="releaseList"- :show-selection="true"- :single-select="true"- :loading="isLoadingReleases"- :selected-row-keys="- selectedRelease ? [selectedRelease.name] : []- "- bordered- @update:checked-row-keys="handleReleaseSelection"- />- <div v-else-if="!isLoadingReleases" class="text-center py-8">- <PackageIcon class="w-12 h-12 mx-auto text-gray-400 mb-4" />- <p class="text-gray-500">- {{ $t("database.revision.no-releases-found") }}- </p>- </div>- </div>- </template>-- <!-- Step 3: Select Files -->- <template v-else-if="currentStep === Step.SELECT_FILES">- <div class="flex flex-col gap-y-4">- <div class="text-sm text-gray-600">- {{ $t("database.revision.select-files-description") }}- </div>-- <!-- Selectable files section -->- <div- v-if="selectableFiles.length > 0"- class="flex flex-col gap-y-4"- >- <div>- <h4 class="font-medium text-control">- {{ $t("database.revision.available-files") }}- <span v-if="selectableFiles.length > 1">- ({{ selectableFiles.length }})- </span>- </h4>- <p class="text-sm text-control-light mt-1">- {{ $t("database.revision.available-files-description") }}- </p>- </div>- <ReleaseFileTable- :files="selectableFiles"- :release-type="selectedRelease!.type"- :show-selection="true"- :selected-files="selectedFiles"- @update:selected-files="handleFileSelection"- />- </div>-- <!-- Files with existing versions section -->- <div- v-if="filesWithExistingVersions.length > 0"- class="flex flex-col gap-y-4 mt-6"- >- <div>- <h4 class="text font-medium text-control">- {{ $t("database.revision.files-already-imported") }}- <span- v-if="filesWithExistingVersions.length > 1"- class="text-control-light"- >({{ filesWithExistingVersions.length }})</span- >- </h4>- <p class="text-sm text-control-light mt-1">- {{- $t("database.revision.files-already-imported-description")- }}- </p>- </div>- <ReleaseFileTable- :files="filesWithExistingVersions"- :release-type="selectedRelease!.type"- :show-selection="false"- :row-clickable="false"- />- </div>-- <!-- No files message -->- <div- v-if="!selectedRelease || selectedRelease.files.length === 0"- class="text-center py-8"- >- <PackageIcon class="w-12 h-12 mx-auto text-gray-400 mb-4" />- <p class="text-gray-500">- {{ $t("database.revision.no-files-found") }}- </p>- </div>- </div>- </template>- </div>- </div>- <template #footer>- <div class="w-full flex items-center justify-between">- <div></div>- <div class="flex items-center gap-x-3">- <NButton- quaternary- v-if="currentStep === Step.SELECT_SOURCE"- @click="handleCancel"- >- {{ $t("common.close") }}- </NButton>- <NButton- v-if="currentStep > Step.SELECT_SOURCE"- quaternary- @click="handlePrevStep"- >- {{ $t("common.back") }}- </NButton>- <NButton- v-if="!isLastStep"- type="primary"- :disabled="!canProceedToNextStep"- @click="handleNextStep"- >- {{ $t("common.next") }}- </NButton>- <NButton- v-else- type="primary"- :disabled="!canSubmit"- :loading="isCreating"- @click="handleConfirm"- >- {{ $t("common.confirm") }}- </NButton>- </div>- </div>- </template>- </DrawerContent>- </Drawer>-</template>--<script setup lang="ts">-import { create as createProto } from "@bufbuild/protobuf";-import {- FileIcon,- FolderOpenIcon,- PackageIcon,- PlusIcon,- XIcon,-} from "lucide-vue-next";-import {- NButton,- NInput,- NRadio,- NRadioGroup,- NSelect,- NStep,- NSteps,-} from "naive-ui";-import type { Ref } from "vue";-import { computed, ref, watch } from "vue";-import { useI18n } from "vue-i18n";-import ReleaseDataTable from "@/components/Release/ReleaseDataTable.vue";-import ReleaseFileTable from "@/components/Release/ReleaseDetail/ReleaseFileTable/ReleaseFileTable.vue";-import { Drawer, DrawerContent } from "@/components/v2";-import { revisionServiceClientConnect } from "@/connect";-import {- pushNotification,- useCurrentProjectV1,- useReleaseStore,- useRevisionStore,- useSheetV1Store,-} from "@/store";-import {- type Release,- type Release_File,- Release_Type,-} from "@/types/proto-es/v1/release_service_pb";-import {- BatchCreateRevisionsRequestSchema,- type CreateRevisionRequest,- CreateRevisionRequestSchema,- type Revision,- Revision_Type,-} from "@/types/proto-es/v1/revision_service_pb";--const props = defineProps<{- database: string;-}>();--const emit = defineEmits<{- (event: "created", revisions: Revision[]): void;-}>();--enum Step {- SELECT_SOURCE = 1,- SELECT_RELEASE = 2,- SELECT_FILES = 3,- UPLOAD_FILES = 4, // Alternative step 2 for local files path-}--interface LocalFile {- name: string;- size: number;- content: string;- version: string;- type: Revision_Type;-}--const { project } = useCurrentProjectV1();-const { t } = useI18n();-const releaseStore = useReleaseStore();-const revisionStore = useRevisionStore();-const sheetStore = useSheetV1Store();-const show = defineModel<boolean>("show", { default: false });--const selectedSource: Ref<"release" | "local"> = ref("release");-const isCreating = ref(false);-const currentStep = ref(Step.SELECT_SOURCE);-const isLoadingReleases = ref(false);-const releaseList = ref<Release[]>([]);-const selectedRelease = ref<Release | null>(null);-const selectedFiles = ref<Release_File[]>([]);-const existingRevisionVersions = ref<Set<string>>(new Set());--// Local files state-const fileInput = ref<HTMLInputElement>();-const localFiles = ref<LocalFile[]>([]);--const revisionTypeOptions = [- {- label: t("database.revision.type-versioned"),- value: Revision_Type.VERSIONED,- },- {- label: t("database.revision.type-declarative"),- value: Revision_Type.DECLARATIVE,- },-];--const canProceedToNextStep = computed(() => {- if (currentStep.value === Step.SELECT_SOURCE) {- return !!selectedSource.value;- }- if (currentStep.value === Step.SELECT_RELEASE) {- return !!selectedRelease.value;- }- return false;-});--const isLastStep = computed(() => {- if (selectedSource.value === "local") {- return currentStep.value === Step.UPLOAD_FILES;- }- return currentStep.value === Step.SELECT_FILES;-});--const canSubmit = computed(() => {- if (selectedSource.value === "local") {- return (- localFiles.value.length > 0 &&- localFiles.value.every(- (f) =>- validateVersion(f.version) &&- !isVersionDuplicate(f.version) &&- f.content- )- );- }- return selectedFiles.value.length > 0;-});--// Split files into selectable and non-selectable groups-const selectableFiles = computed(() => {- if (!selectedRelease.value) return [];- return selectedRelease.value.files.filter((file) => isFileSelectable(file));-});--const filesWithExistingVersions = computed(() => {- if (!selectedRelease.value) return [];- return selectedRelease.value.files.filter((file) => !isFileSelectable(file));-});--// Load releases when entering step 2-const loadReleases = async () => {- isLoadingReleases.value = true;- try {- await releaseStore.fetchReleasesByProject(project.value.name, {- pageSize: 100,- });- releaseList.value = releaseStore.getReleasesByProject(project.value.name);- } catch {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.error"),- description: "Failed to load releases",- });- } finally {- isLoadingReleases.value = false;- }-};--// Load existing revisions to check for duplicates-const loadExistingRevisions = async () => {- try {- const revisions = await revisionStore.fetchAllRevisionsByDatabase(- props.database,- { pageSize: 1000 }- );- const versions = new Set<string>();- revisions.forEach((revision) => {- if (revision.version) {- versions.add(revision.version);- }- });- existingRevisionVersions.value = versions;- } catch (error) {- console.error("Failed to load existing revisions:", error);- }-};--// Check if a file can be selected (no existing revision with same version)-const isFileSelectable = (file: Release_File): boolean => {- return !existingRevisionVersions.value.has(file.version);-};--// Check if a version already exists (for local files)-const isVersionDuplicate = (version: string): boolean => {- return existingRevisionVersions.value.has(version);-};--// Map release type to revision type-const mapReleaseTypeToRevisionType = (- releaseType: Release_Type-): Revision_Type => {- switch (releaseType) {- case Release_Type.VERSIONED:- return Revision_Type.VERSIONED;- case Release_Type.DECLARATIVE:- return Revision_Type.DECLARATIVE;- default:- return Revision_Type.TYPE_UNSPECIFIED;- }-};--// Version validation - must match backend format (numeric parts separated by dots)-const validateVersion = (version: string): boolean => {- if (!version) return false;- // Version must be numeric parts separated by dots (e.g., "1", "1.0", "1.0.0")- const versionRegex = /^(\d+)(\.(\d+))*$/;- return versionRegex.test(version);-};--// Get version input status for validation display-const getVersionStatus = (version: string): "error" | undefined => {- if (!version) return "error";- if (!validateVersion(version)) return "error";- if (isVersionDuplicate(version)) return "error";- return undefined;-};--// File handling functions-const formatFileSize = (bytes: number): string => {- if (bytes < 1024) return bytes + " B";- const kb = bytes / 1024;- if (kb < 1024) return kb.toFixed(1) + " KB";- const mb = kb / 1024;- return mb.toFixed(1) + " MB";-};--const triggerFileInput = () => {- fileInput.value?.click();-};--const readFileContent = (file: File): Promise<string> => {- return new Promise((resolve, reject) => {- const reader = new FileReader();- reader.onload = (e) => resolve(e.target?.result as string);- reader.onerror = reject;- reader.readAsText(file);- });-};--const handleFileSelect = async (event: Event) => {- const input = event.target as HTMLInputElement;- if (input.files) {- await processFiles(Array.from(input.files));- }- input.value = ""; // Reset input-};--const handleFileDrop = async (event: DragEvent) => {- if (event.dataTransfer?.files) {- await processFiles(Array.from(event.dataTransfer.files));- }-};--const processFiles = async (files: File[]) => {- for (const file of files) {- // Check if file is acceptable- const extension = file.name.split(".").pop()?.toLowerCase();- if (!["sql", "txt", "md"].includes(extension || "")) {- pushNotification({- module: "bytebase",- style: "WARN",- title: `Unsupported file type ${extension} for ${file.name}`,- });- continue;- }-- // Check for duplicates- if (localFiles.value.some((f) => f.name === file.name)) {- continue;- }-- try {- const content = await readFileContent(file);-- // Auto-generate version from filename if possible- let version = "";-- // Try different patterns to extract version- // Priority order: most specific to least specific- const patterns = [- // Match semantic versioning: v1.0.0, V1.2.3, 1.0.0- /[Vv]?(\d+\.\d+\.\d+)/,- // Match two-part version: v1.0, V2.1, 1.0- /[Vv]?(\d+\.\d+)/,- // Match version with underscores: v1_0_0, V2_1_3- /[Vv]?(\d+)[_](\d+)(?:[_](\d+))?/,- // Match simple numeric version: v001, V123, 001, 123- /[Vv]?(\d{3,})/,- // Match any number sequence: v1, V2, 1, 2- /[Vv]?(\d+)/,- ];-- for (const pattern of patterns) {- const match = file.name.match(pattern);- if (match) {- if (pattern.source.includes("_")) {- // Handle underscore-separated versions- const parts = [match[1], match[2], match[3]].filter(Boolean);- version = parts.join(".");- } else {- // For other patterns, use the first captured group- version = match[1];- }- break;- }- }-- // If we found a 3-digit number like 001, format it as 0.0.1- if (version && /^\d{3}$/.test(version)) {- version = version.split("").join(".");- }-- localFiles.value.push({- name: file.name,- size: file.size,- content,- version,- type: Revision_Type.VERSIONED,- });- } catch {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: `Failed to read file ${file.name}`,- });- }- }-};--const removeLocalFile = (index: number) => {- localFiles.value.splice(index, 1);-};--// Reset state when drawer opens-watch(show, async (newVal) => {- if (newVal) {- currentStep.value = Step.SELECT_SOURCE;- selectedSource.value = "release";- isCreating.value = false;- releaseList.value = [];- selectedRelease.value = null;- selectedFiles.value = [];- existingRevisionVersions.value = new Set();- localFiles.value = [];- // Load existing revisions to check for duplicates- await loadExistingRevisions();- }-});--const handleReleaseSelection = (selectedKeys: string[]) => {- if (selectedKeys.length > 0) {- const releaseName = selectedKeys[0];- selectedRelease.value =- releaseList.value.find((r) => r.name === releaseName) || null;- } else {- selectedRelease.value = null;- }-};--const handleFileSelection = (files: Release_File[]) => {- selectedFiles.value = files;-};--const handleCancel = () => {- show.value = false;-};--const handleNextStep = async () => {- if (currentStep.value === Step.SELECT_SOURCE) {- if (selectedSource.value === "local") {- currentStep.value = Step.UPLOAD_FILES;- } else {- currentStep.value = Step.SELECT_RELEASE;- await loadReleases();- }- } else if (- currentStep.value === Step.SELECT_RELEASE &&- selectedRelease.value- ) {- currentStep.value = Step.SELECT_FILES;- // Reset file selection when moving to file selection step- selectedFiles.value = [];- }-};--const handlePrevStep = () => {- if (- currentStep.value === Step.SELECT_RELEASE ||- currentStep.value === Step.UPLOAD_FILES- ) {- currentStep.value = Step.SELECT_SOURCE;- } else if (currentStep.value === Step.SELECT_FILES) {- currentStep.value = Step.SELECT_RELEASE;- }-};--const handleConfirm = async () => {- if (!canSubmit.value) return;-- isCreating.value = true;- try {- let requests: CreateRevisionRequest[] = [];-- if (selectedSource.value === "local") {- // For local files, create sheets first- for (const file of localFiles.value) {- try {- // Create a sheet for each file- const sheet = await sheetStore.createSheet(project.value.name, {- content: new TextEncoder().encode(file.content),- });-- // Create revision request with the new sheet- requests.push(- createProto(CreateRevisionRequestSchema, {- parent: props.database,- revision: {- version: file.version,- sheet: sheet.name,- type: file.type,- },- })- );- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: `Failed to create sheet for ${file.name}`,- });- throw error;- }- }- } else if (selectedRelease.value) {- // Create revision requests using the existing sheet from release files- requests = selectedFiles.value.map((file) =>- createProto(CreateRevisionRequestSchema, {- parent: props.database,- revision: {- release: selectedRelease.value!.name,- version: file.version,- file: `${selectedRelease.value!.name}/files/${encodeURIComponent(file.path)}`,- sheet: file.sheet,- type: mapReleaseTypeToRevisionType(selectedRelease.value!.type),- },- })- );- }- if (requests.length === 0) {- return;- }-- const batchRequest = createProto(BatchCreateRevisionsRequestSchema, {- parent: props.database,- requests,- });-- const response =- await revisionServiceClientConnect.batchCreateRevisions(batchRequest);-- emit("created", response.revisions);-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: "Revisions Created",- });-- show.value = false;- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.error"),- description: error instanceof Error ? error.message : String(error),- });- } finally {- isCreating.value = false;- }-};-</script>diff --git a/frontend/src/components/RolloutV1/components/Rollout/CommonDrawer.vue b/frontend/src/components/RolloutV1/components/Rollout/CommonDrawer.vuedeleted file mode 100644index 1591e5eb66..0000000000--- a/frontend/src/components/RolloutV1/components/Rollout/CommonDrawer.vue+++ /dev/null@@ -1,51 +0,0 @@-<template>- <Drawer :show="show" :mask-closable="true" @close="$emit('close')">- <DrawerContent- :title="title"- class="relative overflow-hidden w-128 max-w-[calc(100vw-2rem)]"- >- <template #default>- <slot />-- <div- v-if="loading"- v-zindexable="{ enabled: true }"- class="absolute inset-0 flex items-center justify-center bg-white/50"- >- <BBSpin />- </div>- </template>-- <template v-if="$slots.footer" #footer>- <slot name="footer" />- </template>- </DrawerContent>- </Drawer>-</template>--<script setup lang="ts">-import { zindexable as vZindexable } from "vdirs";-import { watch } from "vue";-import { BBSpin } from "@/bbkit";-import { Drawer, DrawerContent } from "@/components/v2";--const props = defineProps<{- title: string;- show: boolean;- loading: boolean;-}>();--const emit = defineEmits<{- (event: "show"): void;- (event: "close"): void;-}>();--watch(- () => props.show,- (newShow, oldShow) => {- if (newShow && !oldShow) {- emit("show");- }- }-);-</script>diff --git a/frontend/src/components/RolloutV1/components/Rollout/ErrorList.vue b/frontend/src/components/RolloutV1/components/Rollout/ErrorList.vuedeleted file mode 100644index da82a653fe..0000000000--- a/frontend/src/components/RolloutV1/components/Rollout/ErrorList.vue+++ /dev/null@@ -1,23 +0,0 @@-<template>- <ul- class="flex flex-col whitespace-nowrap"- :class="[errors.length > 1 && bullets && 'list-disc pl-4']"- >- <li v-for="(error, i) in errors" :key="i">- <slot name="prefix" />- {{ error }}- </li>- </ul>-</template>--<script setup lang="ts">-withDefaults(- defineProps<{- errors: string[];- bullets?: boolean;- }>(),- {- bullets: true,- }-);-</script>diff --git a/frontend/src/components/RolloutV1/components/Rollout/ReleaseInfoCard.vue b/frontend/src/components/RolloutV1/components/Rollout/ReleaseInfoCard.vuedeleted file mode 100644index a8c3eb062d..0000000000--- a/frontend/src/components/RolloutV1/components/Rollout/ReleaseInfoCard.vue+++ /dev/null@@ -1,212 +0,0 @@-<template>- <div class="flex flex-col gap-y-2">- <div class="flex items-center justify-between">- <div class="flex items-center gap-x-2 text-sm font-medium">- <PackageIcon class="w-4 h-4" />- <span :class="[compact ? '' : 'text-base', isDeleted && 'text-control-light line-through']">{{ releaseTitle }}</span>- </div>- <NButton- v-if="release && isValidReleaseName(release.name)"- size="tiny"- tag="a"- text- :href="`/${release.name}`"- target="_blank"- icon-placement="right"- >- {{ $t("common.view") }}- <template #icon>- <ExternalLinkIcon class="w-3 h-3" />- </template>- </NButton>- </div>-- <div- v-if="release && isValidReleaseName(release.name)"- class="border rounded-md bg-gray-50"- :class="compact ? 'px-3 py-2' : 'px-4 py-3'"- >- <div class="flex flex-col" :class="compact ? 'gap-y-2' : 'gap-y-3'">- <div class="flex items-start justify-between">- <div>- <h3 class="text-sm font-medium text-gray-900">- {{ releaseTitle }}- </h3>- </div>- </div>-- <div- v-if="release.files && release.files.length > 0"- class="flex flex-col gap-y-1"- >- <div class="flex items-center justify-between">- <h4 class="text-xs font-medium text-gray-700">- {{ $t("release.files") }} ({{ release.files.length }})- </h4>- <NButton- v-if="release.files.length > maxDisplayedFiles"- size="tiny"- quaternary- tag="a"- :href="`/${release.name}`"- target="_blank"- >- {{ $t("release.view-all-files") }}- </NButton>- </div>- <div- class="w-full grid gap-1"- :class="compact ? 'grid-cols-1 sm:grid-cols-2' : 'grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-2'"- >- <div- v-for="file in displayedFiles"- :key="file.path"- class="w-full flex items-center justify-between text-xs bg-white rounded-sm"- :class="compact ? 'p-1.5' : 'p-2'"- >- <div class="flex-1 min-w-0 mr-2">- <div class="font-medium truncate">{{ file.path }}</div>- <div class="text-gray-500">{{ file.version }}</div>- </div>- <div- v-if="release.type"- class="inline-flex items-center rounded-sm text-xs shrink-0 bg-blue-100 text-blue-800"- :class="compact ? 'px-1 py-0.5' : 'px-1.5 py-0.5'"- >- {{ getReleaseFileTypeText(release.type) }}- </div>- </div>- <div- v-if="release.files.length > maxDisplayedFiles"- class="text-xs text-gray-500 text-center py-1"- >- {{- $t("release.and-n-more-files", {- count: release.files.length - maxDisplayedFiles,- })- }}- </div>- </div>- </div>-- <div v-if="release.vcsSource" class="flex flex-col gap-y-0.5">- <h4 class="text-xs font-medium text-gray-700">- {{ $t("release.vcs-source") }}- </h4>- <div class="text-xs">- <span class="text-gray-500">{{ getVCSTypeText(release.vcsSource.vcsType) }}:</span>- <a- v-if="release.vcsSource.url"- :href="release.vcsSource.url"- target="_blank"- class="ml-1 text-blue-600 hover:text-blue-800"- >- {{ release.vcsSource.url }}- </a>- </div>- </div>-- <div class="text-xs text-gray-500">- {{- dayjs(getDateForPbTimestampProtoEs(release.createTime)).format(- "YYYY-MM-DD HH:mm:ss"- )- }}- </div>- </div>- </div>-- <div v-else-if="!releaseReady" class="border rounded-md p-2 bg-gray-50">- <div class="flex items-center gap-x-2">- <BBSpin />- <span class="text-xs text-gray-600">- {{ $t("common.loading") }}- </span>- </div>- </div>-- <div v-else class="border rounded-md p-2 bg-red-50">- <div class="text-xs text-red-600">- {{ $t("release.not-found") }}- </div>- </div>- </div>-</template>--<script setup lang="ts">-import dayjs from "dayjs";-import { ExternalLinkIcon, PackageIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import { BBSpin } from "@/bbkit";-import { useReleaseByName } from "@/store";-import { getDateForPbTimestampProtoEs, isValidReleaseName } from "@/types";-import { State, VCSType } from "@/types/proto-es/v1/common_pb";-import { Release_Type } from "@/types/proto-es/v1/release_service_pb";--const props = withDefaults(- defineProps<{- releaseName: string;- compact?: boolean;- }>(),- {- compact: false,- }-);--const { t } = useI18n();-const { release, ready: releaseReady } = useReleaseByName(- computed(() => props.releaseName)-);--const isDeleted = computed(() => release.value?.state === State.DELETED);--const maxDisplayedFiles = computed(() => (props.compact ? 4 : 6));--const releaseTitle = computed(() => {- if (release.value && release.value.name) {- const parts = release.value.name.split("/");- return parts[parts.length - 1] || release.value.name;- }- if (props.releaseName) {- const parts = props.releaseName.split("/");- return parts[parts.length - 1] || props.releaseName;- }- return t("release.title");-});--const displayedFiles = computed(() => {- if (!release.value?.files) return [];- return release.value.files.slice(0, maxDisplayedFiles.value);-});--const getReleaseFileTypeText = (fileType: Release_Type) => {- switch (fileType) {- case Release_Type.VERSIONED:- return t("release.file-type.versioned");- case Release_Type.DECLARATIVE:- return t("release.file-type.declarative");- case Release_Type.TYPE_UNSPECIFIED:- return t("release.file-type.unspecified");- default:- fileType satisfies never;- return t("release.file-type.unspecified");- }-};--const getVCSTypeText = (vcsType: VCSType) => {- switch (vcsType) {- case VCSType.GITHUB:- return "GitHub";- case VCSType.GITLAB:- return "GitLab";- case VCSType.BITBUCKET:- return "Bitbucket";- case VCSType.AZURE_DEVOPS:- return "Azure DevOps";- default:- return t("release.vcs-type.unspecified");- }-};-</script>diff --git a/frontend/src/components/RolloutV1/components/Stage/StageContentSidebar.vue b/frontend/src/components/RolloutV1/components/Stage/StageContentSidebar.vuedeleted file mode 100644index 0acb4aac26..0000000000--- a/frontend/src/components/RolloutV1/components/Stage/StageContentSidebar.vue+++ /dev/null@@ -1,21 +0,0 @@-<template>- <div class="w-full px-4 py-2">- <StageTaskRunsRollback class="pb-2" :stage="stage" />- <StageTimeline- :stage="stage"- :task-runs="taskRuns"- mode="inline"- />- </div>-</template>--<script lang="ts" setup>-import type { Stage, TaskRun } from "@/types/proto-es/v1/rollout_service_pb";-import StageTaskRunsRollback from "./StageTaskRunsRollback.vue";-import StageTimeline from "./StageTimeline.vue";--defineProps<{- stage: Stage | null | undefined;- taskRuns: TaskRun[];-}>();-</script>diff --git a/frontend/src/components/RolloutV1/components/Stage/StageContentView.vue b/frontend/src/components/RolloutV1/components/Stage/StageContentView.vuedeleted file mode 100644index c5302973d6..0000000000--- a/frontend/src/components/RolloutV1/components/Stage/StageContentView.vue+++ /dev/null@@ -1,144 +0,0 @@-<template>- <div v-if="selectedStage" class="w-full">- <!-- Stage header -->- <div class="px-4">- <div class="w-full flex flex-row items-center justify-between py-4 gap-2">- <!-- Left: Stage info and filters -->- <div class="flex flex-row items-center gap-3">- <TaskFilter- v-if="isStageCreated(selectedStage)"- :stage="selectedStage"- :selected-statuses="filterStatuses"- @update:selected-statuses="handleFilterStatusesChange"- />- </div>-- <!-- Right: Stage actions -->- <div class="flex items-center gap-x-2 shrink-0">- <NButton- v-if="isStageCreated(selectedStage)"- type="primary"- :disabled="!canRunStage"- :size="'small'"- @click="$emit('run-stage', selectedStage)"- >- <template #icon>- <PlayIcon :size="16" />- </template>- {{ $t("rollout.stage.run-stage") }}- </NButton>- <NPopconfirm- v-else- @positive-click="$emit('create-stage', selectedStage)"- >- <template #trigger>- <NButton type="primary" :size="'small'">- <template #icon>- <PlusIcon :size="16" />- </template>- {{ $t("common.create") }}- </NButton>- </template>- {{ $t("rollout.stage.confirm-create") }}- </NPopconfirm>- </div>- </div>- </div>-- <!-- Main content area -->- <div class="flex flex-col">- <TaskList- :stage="selectedStage"- :rollout="rollout"- :filter-statuses="filterStatuses"- :readonly="!isStageCreated(selectedStage)"- />-- <StageContentSidebar- v-if="isStageCreated(selectedStage)"- :stage="selectedStage"- :task-runs="taskRuns"- />- </div>- </div>-- <div v-else class="flex items-center justify-center py-12">- <p class="text-gray-500">- {{ $t("rollout.no-stages") }}- </p>- </div>-</template>--<script lang="ts" setup>-import { PlayIcon, PlusIcon } from "lucide-vue-next";-import { NButton, NPopconfirm } from "naive-ui";-import { computed, ref, watch } from "vue";-import { usePlanContextWithRollout } from "@/components/Plan/logic";-import { RUNNABLE_TASK_STATUSES } from "@/components/RolloutV1/constants/task";-import type { Rollout, Stage } from "@/types/proto-es/v1/rollout_service_pb";-import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";-import TaskFilter from "../Task/TaskFilter.vue";-import TaskList from "../Task/TaskList.vue";-import {- canRolloutTasks,- preloadRolloutPermissionContext,-} from "../Task/taskPermissions";-import StageContentSidebar from "./StageContentSidebar.vue";--const props = defineProps<{- selectedStage: Stage | null | undefined;- rollout: Rollout;- isStageCreated: (stage: Stage) => boolean;-}>();--defineEmits<{- (event: "run-stage", stage: Stage): void;- (event: "create-stage", stage: Stage): void;-}>();--const filterStatuses = ref<Task_Status[]>([]);-const rolloutPermissionReady = ref(false);--const { issue, taskRuns } = usePlanContextWithRollout();--watch(- () => props.selectedStage?.tasks.map((task) => task.name) ?? [],- async () => {- if (!props.selectedStage || !props.isStageCreated(props.selectedStage)) {- rolloutPermissionReady.value = true;- return;- }- rolloutPermissionReady.value = false;- await preloadRolloutPermissionContext(- props.selectedStage.tasks,- props.selectedStage.environment- );- rolloutPermissionReady.value = true;- },- { immediate: true }-);--const canRunStage = computed(() => {- if (- !rolloutPermissionReady.value ||- !props.selectedStage ||- !props.isStageCreated(props.selectedStage)- ) {- return false;- }- return (- props.selectedStage.tasks.some((task) =>- RUNNABLE_TASK_STATUSES.includes(task.status)- ) &&- canRolloutTasks(- props.selectedStage.tasks,- issue.value,- props.selectedStage.environment- )- );-});--const handleFilterStatusesChange = (statuses: Task_Status[]) => {- filterStatuses.value = statuses;-};-</script>diff --git a/frontend/src/components/RolloutV1/components/Stage/StageNavigationBar.vue b/frontend/src/components/RolloutV1/components/Stage/StageNavigationBar.vuedeleted file mode 100644index 1e476aa112..0000000000--- a/frontend/src/components/RolloutV1/components/Stage/StageNavigationBar.vue+++ /dev/null@@ -1,54 +0,0 @@-<template>- <div class="relative bg-white pt-3">- <div class="absolute w-full bottom-0 leading-0 border-b border-b-gray-200" />- <div class="flex items-center justify-between gap-x-4">- <div class="flex items-center overflow-x-auto px-4">- <template v-for="(stage, index) in rollout.stages" :key="stage.name">- <div- class="relative px-4 py-2 transition-all border rounded-t-lg cursor-pointer"- :class="[- selectedStageId === stage.name- ? 'bg-white border-gray-200 border-b-transparent'- : 'hover:bg-gray-50 border-transparent border-b-gray-200',- ]"- @click="$emit('select-stage', stage)"- >- <StageProgressCard :stage="stage" />- </div>- <ArrowRightIcon- v-if="index < rollout.stages.length - 1"- :size="16"- class="text-gray-400 shrink-0 mx-2"- />- </template>- </div>-- <div v-if="hasPendingTasks" class="flex items-center px-4 shrink-0">- <NButton size="small" @click="$emit('open-preview')">- <template #icon>- <EyeIcon class="w-4 h-4" />- </template>- {{ $t("rollout.pending-tasks-preview.action") }}- </NButton>- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import { ArrowRightIcon, EyeIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import type { Rollout, Stage } from "@/types/proto-es/v1/rollout_service_pb";-import StageProgressCard from "./StageProgressCard.vue";--defineProps<{- selectedStageId?: string;- rollout: Rollout;- hasPendingTasks: boolean;-}>();--defineEmits<{- (event: "select-stage", stage: Stage): void;- (event: "open-preview"): void;-}>();-</script>diff --git a/frontend/src/components/RolloutV1/components/Stage/StageProgressCard.vue b/frontend/src/components/RolloutV1/components/Stage/StageProgressCard.vuedeleted file mode 100644index c69611b976..0000000000--- a/frontend/src/components/RolloutV1/components/Stage/StageProgressCard.vue+++ /dev/null@@ -1,36 +0,0 @@-<template>- <div class="flex items-center gap-2">- <TaskStatus :status="stageStatus" size="small" />- <span class="whitespace-nowrap">- <EnvironmentV1Name :environment="environment" :link="false" />- </span>- </div>-</template>--<script lang="ts" setup>-import { computed } from "vue";-import EnvironmentV1Name from "@/components/v2/Model/EnvironmentV1Name.vue";-import { useEnvironmentV1Store } from "@/store";-import type { Stage } from "@/types/proto-es/v1/rollout_service_pb";-import TaskStatus from "../Task/TaskStatus.vue";-import { useStageStatus } from "./useStageStatus";--const props = withDefaults(- defineProps<{- stage: Stage;- isCreated?: boolean;- }>(),- {- isCreated: true,- }-);--const environmentStore = useEnvironmentV1Store();--const environment = computed(() => {- return environmentStore.getEnvironmentByName(props.stage.environment);-});--const stageComputed = computed(() => props.stage);-const { stageStatus } = useStageStatus(stageComputed, props.isCreated);-</script>diff --git a/frontend/src/components/RolloutV1/components/Stage/StageTaskRunsRollback.vue b/frontend/src/components/RolloutV1/components/Stage/StageTaskRunsRollback.vuedeleted file mode 100644index 20be336826..0000000000--- a/frontend/src/components/RolloutV1/components/Stage/StageTaskRunsRollback.vue+++ /dev/null@@ -1,37 +0,0 @@-<template>- <div v-if="rollbackableTaskRuns.length > 0">- <NButton size="small" text @click="showRollbackDrawer = true">- <template #icon>- <DatabaseBackupIcon :size="16" />- </template>- {{ $t("task-run.rollback.available", rollbackableTaskRuns.length) }}- </NButton>-- <TaskRunRollbackDrawer- v-model:show="showRollbackDrawer"- :rollout="rollout"- :rollbackable-task-runs="rollbackableTaskRuns"- @close="showRollbackDrawer = false"- />- </div>-</template>--<script lang="ts" setup>-import { DatabaseBackupIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { ref, toRef } from "vue";-import { usePlanContextWithRollout } from "@/components/Plan/logic";-import type { Stage } from "@/types/proto-es/v1/rollout_service_pb";-import TaskRunRollbackDrawer from "../TaskRun/TaskRunRollbackDrawer.vue";-import { useRollbackableTasks } from "../TaskRun/useRollbackableTasks";--const props = defineProps<{- stage: Stage | null | undefined;-}>();--const { rollout, taskRuns } = usePlanContextWithRollout();-const stageRef = toRef(props, "stage");-const { rollbackableTaskRuns } = useRollbackableTasks(stageRef, taskRuns);--const showRollbackDrawer = ref(false);-</script>diff --git a/frontend/src/components/RolloutV1/components/Stage/StageTimeline.vue b/frontend/src/components/RolloutV1/components/Stage/StageTimeline.vuedeleted file mode 100644index d4cc2d33e9..0000000000--- a/frontend/src/components/RolloutV1/components/Stage/StageTimeline.vue+++ /dev/null@@ -1,417 +0,0 @@-<template>- <div>- <!-- Header -->- <div- class="flex items-center justify-between"- :class="isSidebarMode ? 'px-3 py-2' : 'pb-2'"- >- <div class="flex items-center gap-2">- <span class="text-sm font-medium text-gray-700">- {{ $t("task.run-history") }}- </span>- </div>- </div>-- <!-- Inline mode: flat single-line rows -->- <template v-if="isInlineMode">- <div v-if="isLoading" class="py-4 flex justify-center">- <BBSpin />- </div>- <div- v-else-if="stageTaskRuns.length === 0"- class="py-2 text-sm text-gray-500"- >- {{ $t("common.no-data") }}- </div>- <div v-else class="flex flex-col">- <div- v-for="taskRun in displayedTaskRuns"- :key="taskRun.name"- class="flex items-center gap-2 py-1.5 text-sm cursor-pointer hover:bg-gray-50 rounded"- @click="handleClickTarget(taskRun)"- >- <TaskStatus- :status="mapTaskRunStatusToTaskStatus(taskRun.status)"- size="small"- :disabled="true"- class="shrink-0"- />- <span class="text-xs text-gray-400 shrink-0 flex items-center gap-1">- <TimestampDisplay- :timestamp="taskRun.updateTime"- custom-class="!text-xs !text-gray-400"- />- <template v-if="getTaskRunCreatorDisplay(taskRun)">- · {{ getTaskRunCreatorDisplay(taskRun)?.title }}- </template>- <template v-if="getTaskRunDuration(taskRun)">- · {{ getTaskRunDuration(taskRun) }}- </template>- </span>- <span class="truncate text-gray-600">- {{ getTaskTargetDisplay(taskRun).fullPath }}- </span>- </div>- </div>- </template>-- <!-- Timeline mode (sidebar / drawer) -->- <div- v-else- class="overflow-y-auto pt-1 pb-3"- :class="isSidebarMode ? 'px-3 max-h-[calc(100vh-300px)]' : 'px-1'"- >- <div v-if="isLoading" class="py-4 flex justify-center">- <BBSpin />- </div>- <div- v-else-if="stageTaskRuns.length === 0"- class="py-4 text-sm text-gray-500 flex flex-col justify-center items-center gap-1"- >- <SquareChartGanttIcon :stroke-width="1" :size="36" />- <span>{{ $t("common.no-data") }}</span>- </div>- <NTimeline v-else size="medium">- <NTimelineItem- v-for="taskRun in displayedTaskRuns"- :key="taskRun.name"- :type="getTimelineType(taskRun.status)"- >- <template #icon>- <TaskStatus- :status="mapTaskRunStatusToTaskStatus(taskRun.status)"- size="small"- :disabled="true"- />- </template>- <div- class="-ml-1 px-1 py-0.5 rounded -mt-0.5"- >- <NTooltip :delay="500">- <template #trigger>- <div- class="text-sm leading-4 truncate cursor-pointer hover:underline"- @click="handleClickTarget(taskRun)"- >- <span- v-if="getTaskTargetDisplay(taskRun).instance"- class="text-gray-500"- >- {{ getTaskTargetDisplay(taskRun).instance }}- </span>- <span- v-if="getTaskTargetDisplay(taskRun).instance"- class="text-gray-400 mx-0.5"- >/</span- >- <span>{{- getTaskTargetDisplay(taskRun).database- }}</span>- </div>- </template>- <span class="max-w-xs">{{- getTaskTargetDisplay(taskRun).fullPath- }}</span>- </NTooltip>- <!-- Error preview for failed -->- <div- v-if="taskRun.status === TaskRun_Status.FAILED && taskRun.detail"- class="text-xs text-red-600 line-clamp-3 mt-0.5 cursor-pointer hover:underline"- @click="showDetail(taskRun)"- >- {{ taskRun.detail }}- </div>- <!-- Scheduled run time for pending -->- <ScheduledTimeIndicator- v-if="taskRun.status === TaskRun_Status.PENDING && taskRun.runTime"- :time="taskRun.runTime"- :label="$t('task.scheduled-at')"- format="datetime"- class="mt-0.5"- />- <!-- Duration and Timestamp -->- <div class="text-xs text-gray-400 mt-0.5 flex items-center gap-1">- <TimestampDisplay- :timestamp="taskRun.updateTime"- custom-class="!text-xs !text-gray-400"- />- <template v-if="getTaskRunCreatorDisplay(taskRun)">- <span>·</span>- <router-link- :to="{- name: WORKSPACE_ROUTE_USER_PROFILE,- params: {- principalEmail: getTaskRunCreatorDisplay(taskRun)?.email || '',- },- }"- class="hover:underline"- @click.stop- >- {{ getTaskRunCreatorDisplay(taskRun)?.title }}- </router-link>- </template>- <template v-if="getTaskRunDuration(taskRun)">- <span>·</span>- <NTooltip>- <template #trigger>- <span>{{ getTaskRunDuration(taskRun) }}</span>- </template>- {{ $t("common.duration") }}- </NTooltip>- </template>- </div>- </div>- </NTimelineItem>- </NTimeline>- <!-- Show message if there are more items -->- <div- v-if="sortedTaskRuns.length > MAX_DISPLAY_ITEMS"- class="text-xs text-gray-400 text-left"- >- {{ $t("task.only-showing-latest-n-runs", { n: MAX_DISPLAY_ITEMS }) }}- </div>- </div>-- </div>-- <Drawer v-model:show="taskRunDetailContext.show">- <DrawerContent- :title="$t('common.detail')"- class="max-w-[calc(100vw-2rem)]"- >- <TaskRunDetail- v-if="taskRunDetailContext.taskRun"- :key="taskRunDetailContext.taskRun.name"- :task-run="taskRunDetailContext.taskRun"- :database="getDatabaseForTaskRun(taskRunDetailContext.taskRun)"- />- </DrawerContent>- </Drawer>-</template>--<script lang="ts" setup>-import { SquareChartGanttIcon } from "lucide-vue-next";-import { NTimeline, NTimelineItem, NTooltip } from "naive-ui";-import { computed, onUnmounted, ref, watch, watchEffect } from "vue";-import BBSpin from "@/bbkit/BBSpin.vue";-import TimestampDisplay from "@/components/misc/Timestamp.vue";-import { useResourcePoller } from "@/components/Plan/logic/poller";-import { Drawer, DrawerContent } from "@/components/v2";-import { WORKSPACE_ROUTE_USER_PROFILE } from "@/router/dashboard/workspaceRoutes";-import { useCurrentProjectV1, useUserStore } from "@/store";-import { unknownUser } from "@/types";-import type { Stage, TaskRun } from "@/types/proto-es/v1/rollout_service_pb";-import { TaskRun_Status } from "@/types/proto-es/v1/rollout_service_pb";-import type { User } from "@/types/proto-es/v1/user_service_pb";-import {- databaseForTask,- extractDatabaseResourceName,- extractInstanceResourceName,-} from "@/utils";-import ScheduledTimeIndicator from "../Task/ScheduledTimeIndicator.vue";-import TaskStatus from "../Task/TaskStatus.vue";-import { useTaskNavigation } from "../Task/useTaskNavigation";-import TaskRunDetail from "../TaskRun/TaskRunDetail.vue";-import {- getTaskNameFromTaskRun,- getTaskRunDuration,- getTimelineType,- mapTaskRunStatusToTaskStatus,-} from "../TaskRun/useTaskRunUtils";--const props = withDefaults(- defineProps<{- stage: Stage | null | undefined;- taskRuns: TaskRun[];- // "sidebar" - sticky sidebar on desktop with padding and max-height- // "drawer" - inside a drawer with minimal padding for drawer's own spacing- // "inline" - flat single-line rows, no timeline chrome- mode?: "sidebar" | "drawer" | "inline";- }>(),- {- mode: "sidebar",- }-);--// Mode-based styling-const isSidebarMode = computed(() => props.mode === "sidebar");-const isInlineMode = computed(() => props.mode === "inline");--const { project } = useCurrentProjectV1();-const userStore = useUserStore();-const { navigateToTaskDetail } = useTaskNavigation();-const { lastRefreshTime } = useResourcePoller();--// Track stage transitions to prevent flicker-const isStageTransitioning = ref(false);-const lastStageName = ref<string | undefined>(props.stage?.name);--watch(- () => props.stage?.name,- (newName) => {- if (newName !== lastStageName.value) {- isStageTransitioning.value = true;- lastStageName.value = newName;- }- }-);--// Drawer state for task run detail-const taskRunDetailContext = ref<{- show: boolean;- taskRun?: TaskRun;-}>({- show: false,-});--// Filter task runs for this stage-const stageTaskRuns = computed(() => {- if (!props.stage) return [];-- const stageTaskNames = new Set(props.stage.tasks.map((t) => t.name));- return props.taskRuns.filter((run) =>- stageTaskNames.has(getTaskNameFromTaskRun(run.name))- );-});--// Check if we're loading (initial load or stage transition)-const isLoading = computed(() => {- const hasNoRuns = stageTaskRuns.value.length === 0;- const isInitialLoad = lastRefreshTime.value === 0;- // Show loading during initial load or stage transition when no runs available- return hasNoRuns && (isInitialLoad || isStageTransitioning.value);-});--// Clear stage transition flag when we have data for the current stage-watch(- stageTaskRuns,- (runs) => {- if (runs.length > 0) {- isStageTransitioning.value = false;- }- },- { immediate: true }-);--// Also clear transition flag after a short delay to handle stages with no runs-let transitionTimeoutId: ReturnType<typeof setTimeout> | undefined;--watch(- () => props.stage?.name,- () => {- if (transitionTimeoutId !== undefined) {- clearTimeout(transitionTimeoutId);- }- transitionTimeoutId = setTimeout(() => {- isStageTransitioning.value = false;- transitionTimeoutId = undefined;- }, 300);- }-);--onUnmounted(() => {- if (transitionTimeoutId !== undefined) {- clearTimeout(transitionTimeoutId);- }-});--// Maximum number of task runs to display in the timeline-const MAX_DISPLAY_ITEMS = 50;--// Sort by updateTime descending (most recent first)-const sortedTaskRuns = computed(() => {- return [...stageTaskRuns.value].sort((a, b) => {- const timeA = a.updateTime?.seconds ?? BigInt(0);- const timeB = b.updateTime?.seconds ?? BigInt(0);- return Number(timeB - timeA);- });-});--// Limit displayed items for performance-const displayedTaskRuns = computed(() =>- sortedTaskRuns.value.slice(0, MAX_DISPLAY_ITEMS)-);--const getTaskFromTaskRun = (taskRun: TaskRun) => {- const taskName = getTaskNameFromTaskRun(taskRun.name);- return props.stage?.tasks.find((t) => t.name === taskName);-};--interface TaskTargetDisplay {- instance: string;- database: string;- fullPath: string;-}--// Pre-compute display data for displayed task runs to avoid repeated calls in template-const taskRunDisplayMap = computed(() => {- const map = new Map<string, TaskTargetDisplay>();- for (const taskRun of displayedTaskRuns.value) {- const task = getTaskFromTaskRun(taskRun);- const target = task?.target;- const instance = target ? extractInstanceResourceName(target) || "" : "";- const database = target- ? extractDatabaseResourceName(target).databaseName || "unknown"- : taskRun.name.split("/").pop() || "unknown";- const fullPath = instance ? `${instance} / ${database}` : database;- map.set(taskRun.name, { instance, database, fullPath });- }- return map;-});--const getTaskTargetDisplay = (taskRun: TaskRun): TaskTargetDisplay => {- return (- taskRunDisplayMap.value.get(taskRun.name) ?? {- instance: "",- database: "unknown",- fullPath: "unknown",- }- );-};--watchEffect(() => {- const creators = displayedTaskRuns.value- .map((taskRun) => taskRun.creator)- .filter((creator) => !!creator);- if (creators.length > 0) {- userStore.batchGetOrFetchUsers(creators);- }-});--const taskRunCreatorMap = computed(() => {- const map = new Map<string, User>();- for (const taskRun of displayedTaskRuns.value) {- if (!taskRun.creator) continue;- map.set(- taskRun.name,- userStore.getUserByIdentifier(taskRun.creator) ??- unknownUser(taskRun.creator)- );- }- return map;-});--const getTaskRunCreatorDisplay = (taskRun: TaskRun): User | undefined => {- return taskRunCreatorMap.value.get(taskRun.name);-};--const handleClickTarget = (taskRun: TaskRun) => {- const task = getTaskFromTaskRun(taskRun);- if (task) {- navigateToTaskDetail(task);- }-};--// Get database for a task run (used by TaskRunDetail in drawer)-const getDatabaseForTaskRun = (taskRun: TaskRun) => {- const task = getTaskFromTaskRun(taskRun);- return task ? databaseForTask(project.value, task) : undefined;-};--const showDetail = (taskRun: TaskRun) => {- taskRunDetailContext.value = {- show: true,- taskRun,- };-};-</script>diff --git a/frontend/src/components/RolloutV1/components/Stage/useStageSelection.ts b/frontend/src/components/RolloutV1/components/Stage/useStageSelection.tsdeleted file mode 100644index 6991dfef7a..0000000000--- a/frontend/src/components/RolloutV1/components/Stage/useStageSelection.ts+++ /dev/null@@ -1,78 +0,0 @@-import { type ComputedRef, computed, type Ref } from "vue";-import type { Rollout, Stage } from "@/types/proto-es/v1/rollout_service_pb";-import { isTaskRunning, isTaskUnfinished } from "../shared/taskStatus";--export interface UseStageSelectionReturn {- selectedStage: ComputedRef<Stage | undefined>;- isStageCreated: (stage: Stage) => boolean;-}--export const useStageSelection = (- mergedStages: Ref<Stage[]>,- routeStageId: Ref<string | undefined>,- rollout: Ref<Rollout>-): UseStageSelectionReturn => {- const isStageCreated = (stage: Stage): boolean => {- // A stage is created if it exists in the actual rollout (not just preview)- return rollout.value.stages.some(- (s) => s.environment === stage.environment- );- };-- const hasRunningTasks = (stage: Stage): boolean => {- return stage.tasks.some(isTaskRunning);- };-- const hasUnfinishedTasks = (stage: Stage): boolean => {- return stage.tasks.some(isTaskUnfinished);- };-- const findSuitableStage = (stages: Stage[]): Stage | undefined => {- const createdStages = stages.filter(isStageCreated);-- if (createdStages.length === 0) {- return undefined;- }-- // Auto-selection logic (only created stages)- // Priority 1: First created stage with running tasks- const runningStage = createdStages.find(hasRunningTasks);- if (runningStage) {- return runningStage;- }-- // Priority 2: First created stage with unfinished tasks- const unfinishedStage = createdStages.find(hasUnfinishedTasks);- if (unfinishedStage) {- return unfinishedStage;- }-- // Priority 3: Last created stage- return createdStages[createdStages.length - 1];- };-- const selectedStage = computed(() => {- const stages = mergedStages.value;- if (!routeStageId.value) {- return findSuitableStage(stages);- }-- // Always follow route params if stageId is provided (allow both created and uncreated)- if (routeStageId.value) {- const stage = stages.find((s) => {- const stageId = s.name.split("/").pop();- return stageId === routeStageId.value;- });- if (stage) {- return stage;- }- }-- return undefined;- });-- return {- selectedStage,- isStageCreated,- };-};diff --git a/frontend/src/components/RolloutV1/components/Stage/useStageStatus.ts b/frontend/src/components/RolloutV1/components/Stage/useStageStatus.tsdeleted file mode 100644index 7820c92024..0000000000--- a/frontend/src/components/RolloutV1/components/Stage/useStageStatus.ts+++ /dev/null@@ -1,41 +0,0 @@-import { type ComputedRef, computed } from "vue";-import { TASK_STATUS_FILTERS } from "@/components/RolloutV1/constants/task";-import type { Stage } from "@/types/proto-es/v1/rollout_service_pb";-import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";--export interface UseStageStatusReturn {- stageStatus: ComputedRef<Task_Status>;-}--/**- * Composable for computing stage status based on its tasks- * Priority order follows TASK_STATUS_FILTERS: RUNNING > FAILED > PENDING > NOT_STARTED > CANCELED > DONE > SKIPPED- */-export const useStageStatus = (- stage: ComputedRef<Stage> | Stage,- isCreated: boolean-): UseStageStatusReturn => {- const stageStatus = computed(() => {- const stageValue = "value" in stage ? stage.value : stage;-- if (!isCreated || stageValue.tasks.length === 0) {- return Task_Status.STATUS_UNSPECIFIED;- }-- const tasks = stageValue.tasks;-- // Check statuses in priority order using TASK_STATUS_FILTERS- for (const status of TASK_STATUS_FILTERS) {- if (tasks.some((t) => t.status === status)) {- return status;- }- }-- // Fallback to DONE if no matching status found- return Task_Status.DONE;- });-- return {- stageStatus,- };-};diff --git a/frontend/src/components/RolloutV1/components/Task/LatestTaskRunInfo.vue b/frontend/src/components/RolloutV1/components/Task/LatestTaskRunInfo.vuedeleted file mode 100644index 017db33133..0000000000--- a/frontend/src/components/RolloutV1/components/Task/LatestTaskRunInfo.vue+++ /dev/null@@ -1,166 +0,0 @@-<template>- <div class="space-y-2">- <!-- Line 1: Title + Status + Timestamp + Metadata -->- <div class="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">- <!-- Title -->- <span class="font-medium text-gray-700 shrink-0">{{- t("task-run.latest")- }}</span>- <Separator />- <!-- Status badge -->- <span- class="flex items-center gap-x-1 shrink-0"- :class="statusConfig.class"- >- <component- :is="statusConfig.icon"- class="w-4 h-4"- :class="{ 'animate-spin': status === Task_Status.RUNNING }"- />- <span>{{ t(statusConfig.textKey) }}</span>- </span>- <Separator />- <!-- Timestamp -->- <span class="text-gray-500 shrink-0">- <Timestamp :timestamp="updateTime" />- </span>- <!-- Metadata items -->- <template v-if="executorEmail">- <Separator />- <MetadataItem :tooltip="t('task.executed-by')">- <UserIcon class="w-3.5 h-3.5 shrink-0" />- <span class="truncate">{{ executorEmail }}</span>- </MetadataItem>- </template>- <template v-if="duration">- <Separator />- <MetadataItem :tooltip="t('common.duration')">- <ClockIcon class="w-3.5 h-3.5" />- {{ duration }}- </MetadataItem>- </template>- <template v-if="affectedRowsDisplay">- <Separator />- <MetadataItem :tooltip="t('task.affected-rows')">- <RowsIcon class="w-3.5 h-3.5" />- {{ affectedRowsDisplay }}- </MetadataItem>- </template>- </div>-- <!-- Line 2: Task run logs -->- <TaskRunLogViewer- v-if="taskRunName && summary.entries.length > 0"- :task-run-name="taskRunName"- />- </div>-</template>--<script lang="ts" setup>-import type { Timestamp as TimestampType } from "@bufbuild/protobuf/wkt";-import {- CheckCircle2Icon,- CircleDotIcon,- ClockIcon,- LoaderCircleIcon,- Rows3Icon as RowsIcon,- UserIcon,- XCircleIcon,-} from "lucide-vue-next";-import { NTooltip } from "naive-ui";-import type { Component, FunctionalComponent } from "vue";-import { computed, h } from "vue";-import { useI18n } from "vue-i18n";-import Timestamp from "@/components/misc/Timestamp.vue";-import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";-import { TaskRunLogViewer } from "../TaskRun/TaskRunLogViewer";-import type { TaskRunLogSummary } from "../TaskRun/useTaskRunLogSummary";--// Types-interface StatusConfig {- icon: Component;- class: string;- textKey: string;-}--// Functional components for repeated patterns-const Separator: FunctionalComponent = () =>- h("span", { class: "text-gray-300" }, "·");--const MetadataItem: FunctionalComponent<{ tooltip: string }> = (- props,- { slots }-) =>- h(NTooltip, null, {- trigger: () =>- h(- "span",- {- class:- "flex items-center gap-x-1 text-gray-500 shrink-0 cursor-default",- },- slots.default?.()- ),- default: () => props.tooltip,- });--// Status configuration - defined outside setup for better performance-const STATUS_CONFIG: Record<Task_Status, StatusConfig> = {- [Task_Status.FAILED]: {- icon: XCircleIcon,- class: "text-red-600",- textKey: "task.status.failed",- },- [Task_Status.RUNNING]: {- icon: LoaderCircleIcon,- class: "text-blue-600",- textKey: "task.status.running",- },- [Task_Status.DONE]: {- icon: CheckCircle2Icon,- class: "text-green-600",- textKey: "task.status.done",- },- [Task_Status.PENDING]: {- icon: CircleDotIcon,- class: "text-gray-500",- textKey: "task.status.pending",- },- [Task_Status.SKIPPED]: {- icon: CircleDotIcon,- class: "text-gray-500",- textKey: "task.status.skipped",- },- [Task_Status.CANCELED]: {- icon: CircleDotIcon,- class: "text-gray-500",- textKey: "task.status.canceled",- },- [Task_Status.NOT_STARTED]: {- icon: CircleDotIcon,- class: "text-gray-500",- textKey: "task.status.not-started",- },- [Task_Status.STATUS_UNSPECIFIED]: {- icon: CircleDotIcon,- class: "text-gray-500",- textKey: "common.unknown",- },-};--// Props-const props = defineProps<{- status: Task_Status;- updateTime?: TimestampType;- taskRunName?: string;- executorEmail?: string;- duration?: string;- affectedRowsDisplay?: string;- summary: TaskRunLogSummary;-}>();--const { t } = useI18n();--// Single computed for status - eliminates computed chain-const statusConfig = computed(() => STATUS_CONFIG[props.status]);-</script>diff --git a/frontend/src/components/RolloutV1/components/Task/PendingTasksPreviewDrawer.vue b/frontend/src/components/RolloutV1/components/Task/PendingTasksPreviewDrawer.vuedeleted file mode 100644index 892ed134af..0000000000--- a/frontend/src/components/RolloutV1/components/Task/PendingTasksPreviewDrawer.vue+++ /dev/null@@ -1,178 +0,0 @@-<template>- <Drawer :show="show" @close="$emit('close')">- <DrawerContent :title="$t('rollout.pending-tasks-preview.title')">- <div class="w-[400px] space-y-4">- <p class="text-sm text-control-light">- {{ $t("rollout.pending-tasks-preview.description") }}- </p>-- <BBSpin v-if="isLoading" class="mx-auto py-8" />-- <p v-else-if="!pendingTasksByEnv.length" class="py-8 text-center text-control-light">- {{ $t("rollout.pending-tasks-preview.no-pending-tasks") }}- </p>-- <div v-for="group in pendingTasksByEnv" :key="group.environment" class="border rounded-lg">- <div class="flex items-center gap-2 px-3 py-2 bg-gray-50">- <div class="flex items-center gap-2 flex-1 cursor-pointer" @click="toggleEnv(group.environment)">- <component- :is="expandedEnvs.has(group.environment) ? ChevronDownIcon : ChevronRightIcon"- class="w-4 h-4 text-gray-500"- />- <span class="font-medium">{{ extractEnvironmentResourceName(group.environment) }}</span>- <span class="text-xs text-control-light">- {{ $t("rollout.pending-tasks-preview.task-count", group.tasks.length) }}- </span>- </div>- <NButton- size="tiny"- :loading="creatingEnv === group.environment"- :disabled="!!creatingEnv"- @click="handleCreateTasks(group.environment)"- >- {{ $t("common.create") }}- </NButton>- </div>- <ul v-if="expandedEnvs.has(group.environment)" class="px-3 py-2 space-y-1">- <li v-for="task in group.tasks" :key="task.target">- <DatabaseDisplay :database="task.target" size="small" />- </li>- </ul>- </div>- </div>- </DrawerContent>- </Drawer>-</template>--<script lang="ts" setup>-import { create } from "@bufbuild/protobuf";-import { ChevronDownIcon, ChevronRightIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { ref, watch } from "vue";-import { useI18n } from "vue-i18n";-import BBSpin from "@/bbkit/BBSpin.vue";-import DatabaseDisplay from "@/components/Plan/components/common/DatabaseDisplay.vue";-import { generateRolloutPreview } from "@/components/Plan/logic";-import { Drawer, DrawerContent } from "@/components/v2";-import { rolloutServiceClientConnect } from "@/connect";-import { pushNotification } from "@/store/modules/notification";-import type { Plan } from "@/types/proto-es/v1/plan_service_pb";-import type { Rollout, Task } from "@/types/proto-es/v1/rollout_service_pb";-import { CreateRolloutRequestSchema } from "@/types/proto-es/v1/rollout_service_pb";-import {- extractEnvironmentResourceName,- extractPlanNameFromRolloutName,-} from "@/utils";--interface TaskGroup {- environment: string;- tasks: Task[];-}--const props = defineProps<{- show: boolean;- plan: Plan;- rollout: Rollout;- projectName: string;-}>();--const emit = defineEmits<{- (event: "close"): void;- (event: "created"): void;-}>();--const { t } = useI18n();-const isLoading = ref(false);-const creatingEnv = ref<string | null>(null);-const pendingTasksByEnv = ref<TaskGroup[]>([]);-const expandedEnvs = ref<Set<string>>(new Set());--const loadPendingTasks = async () => {- if (pendingTasksByEnv.value.length > 0 || isLoading.value) return;- isLoading.value = true;- try {- const preview = await generateRolloutPreview(props.plan, props.projectName);-- // Build set of existing tasks (target + specId)- const existingTasks = new Set<string>();- for (const stage of props.rollout.stages) {- for (const task of stage.tasks) {- existingTasks.add(`${task.target}:${task.specId}`);- }- }-- // Find uncreated tasks and group by environment- const groups = new Map<string, Task[]>();- for (const stage of preview.stages) {- for (const task of stage.tasks) {- const key = `${task.target}:${task.specId}`;- if (!existingTasks.has(key)) {- let tasks = groups.get(stage.environment);- if (!tasks) {- tasks = [];- groups.set(stage.environment, tasks);- }- tasks.push(task);- }- }- }-- pendingTasksByEnv.value = Array.from(groups.entries()).map(- ([environment, tasks]) => ({ environment, tasks })- );- // Auto-expand all groups- expandedEnvs.value = new Set(groups.keys());- } finally {- isLoading.value = false;- }-};--const handleCreateTasks = async (environment: string) => {- creatingEnv.value = environment;- try {- const request = create(CreateRolloutRequestSchema, {- parent: extractPlanNameFromRolloutName(props.rollout.name),- target: environment,- });- await rolloutServiceClientConnect.createRollout(request);- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("common.success"),- });- // Remove created group from list- pendingTasksByEnv.value = pendingTasksByEnv.value.filter(- (g) => g.environment !== environment- );- emit("created");- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.error"),- description: String(error),- });- } finally {- creatingEnv.value = null;- }-};--// Load when drawer opens-watch(- () => props.show,- (show) => {- if (show) {- loadPendingTasks();- }- },- { immediate: true }-);--const toggleEnv = (env: string) => {- if (expandedEnvs.value.has(env)) {- expandedEnvs.value.delete(env);- } else {- expandedEnvs.value.add(env);- }-};-</script>diff --git a/frontend/src/components/RolloutV1/components/Task/ScheduledTimeIndicator.vue b/frontend/src/components/RolloutV1/components/Task/ScheduledTimeIndicator.vuedeleted file mode 100644index 9ceea36ab4..0000000000--- a/frontend/src/components/RolloutV1/components/Task/ScheduledTimeIndicator.vue+++ /dev/null@@ -1,50 +0,0 @@-<template>- <span class="scheduled-time-indicator flex items-center gap-x-1 text-blue-600" :class="sizeClass">- <ClockIcon :class="iconClass" />- <span v-if="label">{{ label }}:</span>- <slot>- <span>{{ formattedTime }}</span>- </slot>- </span>-</template>--<script lang="ts" setup>-import type { Timestamp } from "@bufbuild/protobuf/wkt";-import { ClockIcon } from "lucide-vue-next";-import { computed } from "vue";-import { formatAbsoluteDateTime } from "@/utils";--const props = withDefaults(- defineProps<{- time?: Date | Timestamp;- label?: string;- size?: "small" | "medium";- }>(),- {- size: "small",- }-);--const sizeClass = computed(() => {- return props.size === "small" ? "text-xs" : "text-sm";-});--const iconClass = computed(() => {- return props.size === "small" ? "w-3 h-3" : "w-4 h-4";-});--const formattedTime = computed(() => {- if (!props.time) return "";-- let date: Date;- if (props.time instanceof Date) {- date = props.time;- } else {- // Handle protobuf Timestamp- const seconds = props.time.seconds;- date = new Date(Number(seconds) * 1000);- }-- return formatAbsoluteDateTime(date.getTime());-});-</script>diff --git a/frontend/src/components/RolloutV1/components/Task/TaskDatabaseName.vue b/frontend/src/components/RolloutV1/components/Task/TaskDatabaseName.vuedeleted file mode 100644index 92d909e10a..0000000000--- a/frontend/src/components/RolloutV1/components/Task/TaskDatabaseName.vue+++ /dev/null@@ -1,12 +0,0 @@-<template>- <DatabaseDisplay :database="task.target" />-</template>--<script setup lang="ts">-import DatabaseDisplay from "@/components/Plan/components/common/DatabaseDisplay.vue";-import type { Task } from "@/types/proto-es/v1/rollout_service_pb";--defineProps<{- task: Task;-}>();-</script>diff --git a/frontend/src/components/RolloutV1/components/Task/TaskFilter.vue b/frontend/src/components/RolloutV1/components/Task/TaskFilter.vuedeleted file mode 100644index e6e11e697a..0000000000--- a/frontend/src/components/RolloutV1/components/Task/TaskFilter.vue+++ /dev/null@@ -1,65 +0,0 @@-<template>- <div class="flex flex-row gap-1 items-center">- <template v-for="status in TASK_STATUS_FILTERS" :key="status">- <NTag- v-if="getTaskCount(status) > 0"- round- checkable- :checked="selectedStatuses.includes(status)"- @update:checked="- (checked) => {- handleStatusToggle(status, checked);- }- "- >- <template #avatar>- <TaskStatus :status="status" size="small" />- </template>- <div class="flex flex-row items-center gap-1">- <span class="select-none text-base">{{- stringifyTaskStatus(status)- }}</span>- <span class="select-none text-base font-medium">{{- getTaskCount(status)- }}</span>- </div>- </NTag>- </template>- </div>-</template>--<script lang="ts" setup>-import { NTag } from "naive-ui";-import { computed } from "vue";-import { TASK_STATUS_FILTERS } from "@/components/RolloutV1/constants/task";-import type {- Stage,- Task_Status,-} from "@/types/proto-es/v1/rollout_service_pb";-import { stringifyTaskStatus } from "@/utils";-import TaskStatus from "./TaskStatus.vue";--const props = defineProps<{- stage: Stage;- selectedStatuses: Task_Status[];-}>();--const emit = defineEmits<{- (event: "update:selected-statuses", statuses: Task_Status[]): void;-}>();--const allTasks = computed(() => {- return props.stage.tasks;-});--const getTaskCount = (status: Task_Status) => {- return allTasks.value.filter((task) => task.status === status).length;-};--const handleStatusToggle = (status: Task_Status, checked: boolean) => {- const newStatuses = checked- ? [...props.selectedStatuses, status]- : props.selectedStatuses.filter((s) => s !== status);- emit("update:selected-statuses", newStatuses);-};-</script>diff --git a/frontend/src/components/RolloutV1/components/Task/TaskItem.vue b/frontend/src/components/RolloutV1/components/Task/TaskItem.vuedeleted file mode 100644index f237408f2b..0000000000--- a/frontend/src/components/RolloutV1/components/Task/TaskItem.vue+++ /dev/null@@ -1,339 +0,0 @@-<template>- <div- class="collapsible-task-item relative bg-white border rounded-lg transition-all group"- >- <!-- Task content -->- <div class="w-full" :class="isExpanded ? 'py-4 pl-3 pr-4 space-y-3' : 'py-2.5 pl-3 pr-4'">- <!-- Header section -->- <div- class="flex items-center justify-between gap-x-3"- :class="{ 'mb-2': isExpanded }"- >- <div class="flex items-center gap-x-2 flex-1 min-w-0">- <!-- Inline checkbox - always visible like Gmail/GitHub -->- <NCheckbox- :checked="isSelected"- :disabled="!isSelectable"- class="shrink-0"- @click.stop- @update:checked="emit('toggle-select')"- />- <TaskStatus :status="task.status" :size="isExpanded ? 'large' : 'small'" />- <div class="flex items-center gap-x-2 min-w-0">- <RouterLink- v-if="!readonly"- :to="taskDetailRoute"- active-class=""- exact-active-class=""- class="min-w-0 hover:opacity-80 transition-opacity"- >- <DatabaseDisplay- :database="task.target"- :size="isExpanded ? 'large' : 'medium'"- :show-external-link="false"- />- </RouterLink>- <DatabaseDisplay- v-else- :database="task.target"- :size="isExpanded ? 'large' : 'medium'"- :show-external-link="false"- class="shrink-0"- />- <RouterLink- v-if="!readonly && isExpanded"- :to="taskDetailRoute"- active-class=""- exact-active-class=""- class="shrink-0 flex items-center gap-x-1 text-xs text-info hover:opacity-80 transition-opacity"- >- <ArrowUpRightIcon class="w-4 h-4" />- <span>{{ t("common.view-details") }}</span>- </RouterLink>- </div>- <!-- Collapsed view: contextual info + type -->- <div v-if="!isExpanded" class="flex items-center gap-x-1.5 ml-auto shrink-0 text-xs text-gray-500">- <!-- Status-contextual info first -->- <template v-if="timingType === 'scheduled'">- <ScheduledTimeIndicator- :time="scheduledTime"- :title="t('task.scheduled-time')"- />- </template>- <template v-else-if="timingType === 'running'">- <span class="flex items-center gap-x-1 text-blue-600">- <LoaderCircleIcon class="w-3 h-3 animate-spin" />- {{ timingDisplay }}- </span>- </template>- <template v-else-if="collapsedContextInfo">- <span>{{ collapsedContextInfo }}</span>- </template>- </div>- </div>-- <!-- Expand/Collapse button -->- <button- v-if="!readonly"- class="shrink-0 p-1 hover:bg-gray-100 rounded transition-colors"- :class="{ 'self-start': isExpanded }"- @click.stop="emit('toggle-expand')"- >- <ChevronRightIcon v-if="!isExpanded" class="w-4 h-4 text-gray-500" />- <ChevronDownIcon v-else class="w-4 h-4 text-gray-500" />- </button>- </div>-- <!-- Collapsed: contextual status line (time + error/skip) -->- <div- v-if="!isExpanded && collapsedStatusText"- class="flex items-center gap-x-2 text-xs mt-1"- >- <NTag v-if="latestTaskRun?.createTime" size="tiny" round>- <Timestamp :timestamp="latestTaskRun.createTime" />- </NTag>- <span- class="truncate cursor-pointer"- :class="task.status === Task_Status.FAILED ? 'text-red-600' : 'text-gray-500 italic'"- @click.stop="emit('toggle-expand')"- >- {{ collapsedStatusText }}- </span>- </div>-- <!-- Task metadata - expanded only -->- <div v-if="isExpanded" class="space-y-3">- <!-- Task information line with quick actions -->- <div class="flex items-center gap-x-2">- <div- v-if="timingType === 'scheduled'"- class="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-gray-600"- >- <ScheduledTimeIndicator- :time="scheduledTime"- :label="t('task.scheduled-time')"- />- </div>- <!-- Quick action buttons -->- <div v-if="hasActions" class="ml-auto flex items-center gap-x-2 shrink-0">- <NButton- v-if="canRun"- size="tiny"- type="primary"- @click.stop="runTask"- >- <template #icon>- <PlayIcon class="w-3 h-3" />- </template>- {{ task.status === Task_Status.FAILED ? t("common.retry") : t("common.run") }}- </NButton>- <NButton- v-if="canSkip"- size="tiny"- @click.stop="skipTask"- >- <template #icon>- <SkipForwardIcon class="w-3 h-3" />- </template>- {{ t("common.skip") }}- </NButton>- <NButton- v-if="canCancel"- size="tiny"- @click.stop="cancelTask"- >- <template #icon>- <XIcon class="w-3 h-3" />- </template>- {{ t("common.cancel") }}- </NButton>- </div>- </div>-- <!-- SQL Statement section -->- <div v-if="!isReleaseTask">- <div class="flex items-center justify-between mb-1">- <span class="text-sm font-medium text-gray-700">{{ t("common.statement") }}</span>- </div>-- <BBSpin v-if="loading" />- <template v-else>- <HighlightCodeBlock- :code="displayedStatement"- language="sql"- :lazy="true"- class="text-sm whitespace-pre-wrap wrap-break-word max-h-64 overflow-auto rounded-t p-2 bg-white border border-gray-200"- :class="isStatementTruncated ? 'rounded-b-none border-b-0' : 'rounded-b'"- />- <div- v-if="isStatementTruncated"- class="px-3 py-1.5 text-xs text-gray-500 bg-gray-50 border border-gray-200 rounded-b"- >- {{ t("rollout.task.statement-truncated-hint") }}- </div>- </template>- </div>-- <!-- Release Info section for release-based tasks -->- <ReleaseInfoCard- v-else- :release-name="releaseName"- :compact="true"- />-- <!-- Latest Task Run Info -->- <LatestTaskRunInfo- v-if="latestTaskRun"- :status="task.status"- :update-time="latestTaskRun.updateTime"- :task-run-name="latestTaskRun.name"- :executor-email="executorEmail"- :duration="timingType !== 'scheduled' ? timingDisplay : undefined"- :affected-rows-display="affectedRowsDisplay"- :summary="taskRunLogSummary"- />- </div>- </div>-- <!-- Task Rollout Action Panel -->- <TaskRolloutActionPanel- v-if="currentAction && actionTarget"- :show="showActionPanel"- :action="currentAction"- :target="actionTarget"- @close="closeActionPanel"- @confirm="handleActionConfirm"- />- </div>-</template>--<script lang="ts" setup>-import { last } from "lodash-es";-import {- ArrowUpRightIcon,- ChevronDownIcon,- ChevronRightIcon,- LoaderCircleIcon,- PlayIcon,- SkipForwardIcon,- XIcon,-} from "lucide-vue-next";-import { NButton, NCheckbox, NTag } from "naive-ui";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import { RouterLink } from "vue-router";-import BBSpin from "@/bbkit/BBSpin.vue";-import HighlightCodeBlock from "@/components/HighlightCodeBlock.vue";-import Timestamp from "@/components/misc/Timestamp.vue";-import { usePlanContextWithRollout } from "@/components/Plan";-import DatabaseDisplay from "@/components/Plan/components/common/DatabaseDisplay.vue";-import { emitPlanStatusChanged } from "@/components/Plan/logic";-import { buildTaskDetailRoute } from "@/router/dashboard/projectV1RouteHelpers";-import type { Stage, Task } from "@/types/proto-es/v1/rollout_service_pb";-import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";-import { isReleaseBasedTask, releaseNameOfTaskV1 } from "@/utils";-import ReleaseInfoCard from "../Rollout/ReleaseInfoCard.vue";-import { useTaskRunsForTask } from "../shared/useTaskRunsForTask";-import { useTaskRunLogSummary } from "../TaskRun/useTaskRunLogSummary";-import LatestTaskRunInfo from "./LatestTaskRunInfo.vue";-import ScheduledTimeIndicator from "./ScheduledTimeIndicator.vue";-import TaskRolloutActionPanel from "./TaskRolloutActionPanel.vue";-import TaskStatus from "./TaskStatus.vue";-import { useTaskActions } from "./useTaskActions";-import { useTaskDisplay } from "./useTaskDisplay";-import { useTaskStatement } from "./useTaskStatement";-import { useTaskTiming } from "./useTaskTiming";--const props = withDefaults(- defineProps<{- task: Task;- stage: Stage;- isExpanded: boolean;- isSelected: boolean;- isSelectable: boolean;- inSelectMode: boolean;- readonly?: boolean;- }>(),- {- readonly: false,- }-);--const emit = defineEmits<{- (event: "toggle-expand"): void;- (event: "toggle-select"): void;-}>();--const { t } = useI18n();-const { taskRuns: allTaskRuns, events } = usePlanContextWithRollout();--// Task actions (Run/Skip/Cancel)-const {- canRun,- canSkip,- canCancel,- hasActions,- showActionPanel,- currentAction,- actionTarget,- runTask,- skipTask,- cancelTask,- closeActionPanel,-} = useTaskActions(- () => props.task,- () => props.stage-);--// Handle action confirmed - trigger data refresh-const handleActionConfirm = () => {- emitPlanStatusChanged(events, { refreshMode: "fast-follow" });-};--const taskDetailRoute = computed(() => buildTaskDetailRoute(props.task.name));--const isReleaseTask = computed(() => isReleaseBasedTask(props.task));--// Release name for release-based tasks-const releaseName = computed(() => releaseNameOfTaskV1(props.task));--const { loading, displayedStatement, isStatementTruncated } = useTaskStatement(- () => props.task,- () => props.isExpanded-);--const taskRunsForTask = useTaskRunsForTask(- () => props.task.name,- () => allTaskRuns.value-);--const latestTaskRun = computed(() => {- return last(taskRunsForTask.value);-});--const { timingDisplay, timingType, scheduledTime } = useTaskTiming(- () => props.task,- () => latestTaskRun.value-);--const { summary: taskRunLogSummary } = useTaskRunLogSummary(- () => latestTaskRun.value,- () => props.isExpanded-);--const affectedRowsDisplay = computed(() => {- if (!taskRunLogSummary.value.hasAffectedRows) return "";- const rows = taskRunLogSummary.value.totalAffectedRows;- if (rows <= BigInt(0)) return "";- return `${rows.toLocaleString()} row${rows === BigInt(1) ? "" : "s"}`;-});--// Task display formatting (type, executor, messages, collapsed view info)-const { executorEmail, collapsedContextInfo, collapsedStatusText } =- useTaskDisplay(- () => props.task,- () => latestTaskRun.value,- () => timingDisplay.value,- () => affectedRowsDisplay.value- );-</script>diff --git a/frontend/src/components/RolloutV1/components/Task/TaskList.vue b/frontend/src/components/RolloutV1/components/Task/TaskList.vuedeleted file mode 100644index c05c04fb17..0000000000--- a/frontend/src/components/RolloutV1/components/Task/TaskList.vue+++ /dev/null@@ -1,142 +0,0 @@-<template>- <div class="w-full">- <TaskToolbar- v-if="!readonly"- :selected-tasks="selectedTasks"- :all-tasks="filteredTasks"- :is-task-selectable="isTaskSelectable"- :stage="stage"- @select-all="selectAll"- @clear-selection="clearSelection"- @action-complete="handleActionComplete"- />-- <div class="task-list px-4 py-3 space-y-3">- <TaskItem- v-for="task in visibleTasks"- :key="task.name"- :task="task"- :stage="stage"- :is-expanded="isTaskExpanded(task)"- :is-selected="isTaskSelected(task)"- :is-selectable="!readonly && isTaskSelectable(task)"- :in-select-mode="!readonly && selectedTasks.length > 0"- :readonly="readonly"- @toggle-expand="toggleExpand(task)"- @toggle-select="toggleSelect(task)"- />-- <div v-if="filteredTasks.length === 0" class="text-center py-8 text-gray-500">- {{ $t("rollout.task.no-tasks") }}- </div>-- <!-- Show More button -->- <div- v-if="hasMoreTasks"- class="flex justify-start"- >- <NButton- quaternary- type="primary"- size="tiny"- @click="loadMoreTasks"- >- {{ $t("common.show-more") }} ({{ remainingTasksCount }} {{ $t("common.remaining") }})- </NButton>- </div>- </div>- </div>-</template>--<script lang="ts" setup>-import { NButton } from "naive-ui";-import { computed, ref, watch } from "vue";-import {- emitPlanStatusChanged,- usePlanContextWithRollout,-} from "@/components/Plan/logic";-import type { Rollout, Stage } from "@/types/proto-es/v1/rollout_service_pb";-import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";-import { DEFAULT_PAGE_SIZE } from "../../constants";-import TaskItem from "./TaskItem.vue";-import TaskToolbar from "./TaskToolbar.vue";-import { useTaskCollapse } from "./useTaskCollapse";-import { useTaskSelection } from "./useTaskSelection";--const props = withDefaults(- defineProps<{- stage: Stage;- rollout: Rollout;- filterStatuses: Task_Status[];- readonly?: boolean;- }>(),- {- readonly: false,- }-);--const { events } = usePlanContextWithRollout();--const displayedTaskCount = ref(DEFAULT_PAGE_SIZE);--const filteredTasks = computed(() => {- const tasks = props.stage.tasks;- if (props.filterStatuses.length > 0) {- return tasks.filter((task) => props.filterStatuses.includes(task.status));- }- return tasks;-});--const visibleTasks = computed(() => {- return filteredTasks.value.slice(0, displayedTaskCount.value);-});--const hasMoreTasks = computed(() => {- return filteredTasks.value.length > displayedTaskCount.value;-});--const remainingTasksCount = computed(() => {- return filteredTasks.value.length - displayedTaskCount.value;-});--const loadMoreTasks = () => {- displayedTaskCount.value = Math.min(- displayedTaskCount.value + DEFAULT_PAGE_SIZE,- filteredTasks.value.length- );-};--const { isTaskExpanded, toggleExpand } = useTaskCollapse(filteredTasks);--const {- selectedTasks,- isTaskSelected,- isTaskSelectable,- toggleSelect,- selectAll,- clearSelection,-} = useTaskSelection(filteredTasks);--const handleActionComplete = () => {- clearSelection();- emitPlanStatusChanged(events, { refreshMode: "fast-follow" });-};--// Reset pagination when filters change, but preserve state on refresh-watch(- () => props.filterStatuses,- () => {- displayedTaskCount.value = DEFAULT_PAGE_SIZE;- }-);--// Ensure displayedTaskCount doesn't exceed available tasks-watch(- () => filteredTasks.value.length,- (newLength) => {- if (displayedTaskCount.value > newLength) {- displayedTaskCount.value = Math.max(DEFAULT_PAGE_SIZE, newLength);- }- }-);-</script>diff --git a/frontend/src/components/RolloutV1/components/Task/TaskRollbackButton.vue b/frontend/src/components/RolloutV1/components/Task/TaskRollbackButton.vuedeleted file mode 100644index 263f5773e2..0000000000--- a/frontend/src/components/RolloutV1/components/Task/TaskRollbackButton.vue+++ /dev/null@@ -1,56 +0,0 @@-<template>- <div>- <NButton- size="small"- @click="showRollbackDrawer = true"- icon-placement="left"- >- <template #icon>- <Undo2Icon class="w-4 h-auto" />- </template>- {{ $t("common.rollback") }}- </NButton>-- <TaskRunRollbackDrawer- v-model:show="showRollbackDrawer"- :rollout="rollout"- :rollbackable-task-runs="rollbackableTaskRuns"- @close="showRollbackDrawer = false"- />- </div>-</template>--<script setup lang="ts">-import { Undo2Icon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { computed, ref } from "vue";-import { useCurrentProjectV1 } from "@/store";-import type {- Rollout,- Task,- TaskRun,-} from "@/types/proto-es/v1/rollout_service_pb";-import { databaseForTask } from "@/utils";-import TaskRunRollbackDrawer from "../TaskRun/TaskRunRollbackDrawer.vue";--const props = defineProps<{- task: Task;- taskRun: TaskRun;- rollout: Rollout;-}>();--const { project } = useCurrentProjectV1();--const showRollbackDrawer = ref(false);--// Prepare rollbackable task run data for the drawer-const rollbackableTaskRuns = computed(() => {- return [- {- task: props.task,- taskRun: props.taskRun,- database: databaseForTask(project.value, props.task),- },- ];-});-</script>diff --git a/frontend/src/components/RolloutV1/components/Task/TaskRolloutActionPanel.vue b/frontend/src/components/RolloutV1/components/Task/TaskRolloutActionPanel.vuedeleted file mode 100644index 351b917b34..0000000000--- a/frontend/src/components/RolloutV1/components/Task/TaskRolloutActionPanel.vue+++ /dev/null@@ -1,548 +0,0 @@-<template>- <CommonDrawer- :show="show"- :title="title"- :loading="loading || permissionLoading"- @show="resetState"- @close="$emit('close')"- >- <template #default>- <div class="flex flex-col gap-y-4 h-full px-1">- <!-- Error Alert -->- <NAlert- v-if="validationErrors.length > 0"- type="error"- :title="$t('rollout.task-execution-errors')"- >- <ul class="list-disc list-inside flex flex-col gap-y-1">- <li- v-for="(error, index) in validationErrors"- :key="index"- class="text-sm"- >- {{ error }}- </li>- </ul>- </NAlert>-- <!-- Stage information -->- <div- v-if="shouldShowStageInfo"- class="flex flex-row gap-x-2 shrink-0 overflow-y-hidden justify-start items-center"- >- <label class="font-medium text-control">- {{ $t("common.stage") }}- </label>- <EnvironmentV1Name- :environment="- environmentStore.getEnvironmentByName(- target.stage?.environment ?? ''- )- "- :link="false"- />- </div>-- <!-- Task information -->- <div v-if="shouldShowTaskInfo" class="flex flex-col gap-y-1 shrink-0">- <label class="text-control">- <span class="font-medium">{{- $t("common.task", eligibleTasks.length)- }}</span>- <span v-if="taskCountSuffix" class="opacity-80">- ({{ taskCountSuffix }})- </span>- </label>- <!-- Virtual scroll for large lists, regular scroll for small -->- <NVirtualList- v-if="eligibleTasks.length > 50"- :items="eligibleTasks"- :item-size="32"- class="max-h-64"- item-resizable- >- <template #default="{ item: task }">- <div- :key="task.name"- class="flex items-center text-sm gap-2 h-8"- >- <TaskStatus :status="task.status" size="small" />- <TaskDatabaseName :task="task" />- </div>- </template>- </NVirtualList>- <NScrollbar v-else class="max-h-64">- <ul class="text-sm flex flex-col gap-y-2">- <li- v-for="task in eligibleTasks"- :key="task.name"- class="flex items-center gap-2"- >- <TaskStatus :status="task.status" size="small" />- <TaskDatabaseName :task="task" />- </li>- </ul>- </NScrollbar>- </div>-- <!-- Scheduled time picker (RUN only) -->- <div v-if="action === 'RUN'" class="flex flex-col">- <h3 class="font-medium text-control mb-1">- {{ $t("task.execution-time") }}- </h3>- <NRadioGroup- :size="'large'"- :value="runTimeInMS === undefined ? 'immediate' : 'scheduled'"- class="flex! flex-col sm:flex-row gap-2 sm:gap-4"- @update:value="handleExecutionModeChange"- >- <NRadio value="immediate">- <span>{{ $t("task.run-immediately.self") }}</span>- </NRadio>- <NRadio value="scheduled">- <span>{{ $t("task.schedule-for-later.self") }}</span>- </NRadio>- </NRadioGroup>-- <div class="mt-1 text-sm text-control-light">- {{- runTimeInMS === undefined- ? $t("task.run-immediately.description")- : $t("task.schedule-for-later.description")- }}- </div>-- <NDatePicker- v-if="runTimeInMS !== undefined"- v-model:value="runTimeInMS"- type="datetime"- :placeholder="$t('task.select-scheduled-time')"- :is-date-disabled="isDateDisabled"- format="yyyy-MM-dd HH:mm:ss"- :actions="['clear', 'confirm']"- clearable- class="mt-2"- />- </div>-- <!-- Skip prior backup checkbox (RUN only, when tasks have backup enabled) -->- <div- v-if="action === 'RUN' && hasPriorBackupTasks"- class="flex flex-col"- >- <NCheckbox v-model:checked="skipPriorBackup">- {{ $t("task.skip-prior-backup") }}- </NCheckbox>- <div class="ml-6 text-sm text-control-light">- {{ $t("task.skip-prior-backup-description") }}- </div>- </div>-- <!-- Comment field (SKIP only) -->- <div- v-if="action === 'SKIP' && issue"- class="flex flex-col gap-y-1 shrink-0"- >- <p class="font-medium text-control">- {{ $t("common.reason") }}- </p>- <NInput- v-model:value="comment"- type="textarea"- :placeholder="$t('issue.leave-a-comment')"- :autosize="{ minRows: 3, maxRows: 10 }"- :maxlength="1000"- />- </div>- </div>- </template>- <template #footer>- <div class="w-full flex flex-row justify-end items-center gap-x-2">- <NButton quaternary @click="$emit('close')">- {{ $t("common.close") }}- </NButton>-- <NTooltip :disabled="validationErrors.length === 0" placement="top">- <template #trigger>- <NButton- :disabled="permissionLoading || validationErrors.length > 0"- type="primary"- @click="handleConfirm"- >- {{ confirmButtonText }}- </NButton>- </template>- <template #default>- <ErrorList :errors="validationErrors" />- </template>- </NTooltip>- </div>- </template>- </CommonDrawer>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { TimestampSchema } from "@bufbuild/protobuf/wkt";-import dayjs from "dayjs";-import {- NAlert,- NButton,- NCheckbox,- NDatePicker,- NInput,- NRadio,- NRadioGroup,- NScrollbar,- NTooltip,- NVirtualList,-} from "naive-ui";-import { computed, ref, watch, watchEffect } from "vue";-import { useI18n } from "vue-i18n";-import { usePlanContextWithRollout } from "@/components/Plan/logic";-import {- CANCELABLE_TASK_STATUSES,- RUNNABLE_TASK_STATUSES,-} from "@/components/RolloutV1/constants/task";-import { EnvironmentV1Name } from "@/components/v2";-import { rolloutServiceClientConnect } from "@/connect";-import {- pushNotification,- useCurrentUserV1,- useEnvironmentV1Store,-} from "@/store";-import { userNamePrefix } from "@/store/modules/v1/common";-import { Issue_Type } from "@/types/proto-es/v1/issue_service_pb";-import type {- BatchRunTasksRequest,- Stage,- Task,-} from "@/types/proto-es/v1/rollout_service_pb";-import {- BatchCancelTaskRunsRequestSchema,- BatchRunTasksRequestSchema,- BatchSkipTasksRequestSchema,- ListTaskRunsRequestSchema,- Task_Type,- TaskRun_Status,-} from "@/types/proto-es/v1/rollout_service_pb";-import { extractStageUID } from "@/utils";-import CommonDrawer from "../Rollout/CommonDrawer.vue";-import ErrorList from "../Rollout/ErrorList.vue";-import TaskDatabaseName from "./TaskDatabaseName.vue";-import TaskStatus from "./TaskStatus.vue";-import {- canRolloutTasks,- preloadRolloutPermissionContext,-} from "./taskPermissions";--// 1 hour default delay for scheduled tasks-const DEFAULT_RUN_DELAY_MS = 60 * 60 * 1000;--export type TargetType = { type: "tasks"; tasks?: Task[]; stage?: Stage };--const props = defineProps<{- show: boolean;- action: "RUN" | "SKIP" | "CANCEL";- target: TargetType;-}>();--const emit = defineEmits<{- (event: "close"): void;- (event: "confirm"): void;-}>();--const { t } = useI18n();-const { issue, plan, rollout } = usePlanContextWithRollout();-const currentUser = useCurrentUserV1();-const environmentStore = useEnvironmentV1Store();--// State-const loading = ref(false);-const permissionLoading = ref(false);-const comment = ref("");-const runTimeInMS = ref<number | undefined>(undefined);-const skipPriorBackup = ref(false);-const canRolloutPermission = ref(true);--// Task status filters-const isRunnable = (task: Task) => RUNNABLE_TASK_STATUSES.includes(task.status);--const isCancellable = (task: Task) =>- CANCELABLE_TASK_STATUSES.includes(task.status);--// Rollout type detection-const allRolloutTasks = computed(() =>- rollout.value.stages.flatMap((stage) => stage.tasks)-);--const rolloutType = computed(() => {- const tasks = allRolloutTasks.value;- if (tasks.every((task) => task.type === Task_Type.DATABASE_CREATE)) {- return "DATABASE_CREATE";- }- if (tasks.every((task) => task.type === Task_Type.DATABASE_EXPORT)) {- return "DATABASE_EXPORT";- }- return "DATABASE_CHANGE";-});--const isDatabaseCreateOrExport = computed(- () =>- rolloutType.value === "DATABASE_CREATE" ||- rolloutType.value === "DATABASE_EXPORT"-);--// Eligible tasks based on action type-const eligibleTasks = computed(() => {- // If specific tasks are provided, use them (e.g., from per-task actions)- // Otherwise, for DATABASE_CREATE/EXPORT use all rollout tasks,- // for regular rollouts use stage tasks- const tasks = props.target.tasks- ? props.target.tasks- : isDatabaseCreateOrExport.value- ? allRolloutTasks.value- : (props.target.stage?.tasks ?? []);-- if (props.action === "RUN" || props.action === "SKIP") {- return tasks.filter(isRunnable);- }- if (props.action === "CANCEL") {- return tasks.filter(isCancellable);- }- return tasks;-});--// UI visibility-const shouldShowStageInfo = computed(() => !isDatabaseCreateOrExport.value);-const shouldShowTaskInfo = computed(- () => rolloutType.value !== "DATABASE_CREATE"-);--const taskCountSuffix = computed(() => {- if (- eligibleTasks.value.length <= 1 ||- !shouldShowStageInfo.value ||- !props.target.stage- ) {- return "";- }- const total = props.target.stage.tasks.length;- const eligible = eligibleTasks.value.length;- return eligible === total ? String(eligible) : `${eligible} / ${total}`;-});--// Check if any eligible task has prior backup enabled in its plan spec-const hasPriorBackupTasks = computed(() => {- return eligibleTasks.value.some((task) => {- const spec = plan.value.specs.find((s) => s.id === task.specId);- if (spec?.config?.case !== "changeDatabaseConfig") return false;- return spec.config.value.enablePriorBackup === true;- });-});--const title = computed(() => {- const n = eligibleTasks.value.length;- if (props.action === "RUN") return t("task.run-task", { n });- if (props.action === "SKIP") return t("task.skip-task", { n });- if (props.action === "CANCEL") return t("task.cancel-task", { n });- return "";-});--const confirmButtonText = computed(() => {- if (props.action === "RUN") return t("common.run");- if (props.action === "SKIP") return t("common.skip");- return t("common.cancel");-});--// Validation-const validationErrors = computed(() => {- const errors: string[] = [];-- if (eligibleTasks.value.length === 0) {- errors.push(t("common.no-data"));- }-- if (!canRolloutPermission.value) {- const isExportByNonCreator =- issue.value?.type === Issue_Type.DATABASE_EXPORT &&- issue.value.creator !== `${userNamePrefix}${currentUser.value.email}`;- errors.push(- t(- isExportByNonCreator- ? "task.data-export-creator-only"- : "task.no-permission"- )- );- }-- if (- props.action === "RUN" &&- runTimeInMS.value !== undefined &&- runTimeInMS.value <= Date.now()- ) {- errors.push(t("task.error.scheduled-time-must-be-in-the-future"));- }-- return errors;-});--// Cache permission check - only update when panel opens-watch(- () => props.show,- async (show) => {- if (show) {- const tasks = props.target.tasks ?? props.target.stage?.tasks ?? [];- const environment = props.target.stage?.environment;- permissionLoading.value = true;- canRolloutPermission.value = false;- await preloadRolloutPermissionContext(tasks, environment);- canRolloutPermission.value = canRolloutTasks(- tasks,- issue.value,- environment- );- permissionLoading.value = false;- }- },- { immediate: true }-);--// Initialize run time from existing task schedule-watchEffect(() => {- const runTimes = new Set(eligibleTasks.value.map((task) => task.runTime));- if (runTimes.size !== 1) return;-- const runTime = [...runTimes][0];- if (!runTime) return;-- runTimeInMS.value = Number(runTime.seconds) * 1000 + runTime.nanos / 1000000;-});--// Helpers-const isDateDisabled = (date: number) =>- date < dayjs().startOf("day").valueOf();--const handleExecutionModeChange = (value: string) => {- runTimeInMS.value =- value === "immediate" ? undefined : Date.now() + DEFAULT_RUN_DELAY_MS;-};--const resetState = () => {- comment.value = "";- runTimeInMS.value = undefined;- skipPriorBackup.value = false;-};--const groupTasksByStage = (tasks: Task[]) => {- const map = new Map<string, Task[]>();- for (const task of tasks) {- const stageId = extractStageUID(task.name);- if (!stageId) continue; // Skip tasks with invalid names- if (!map.has(stageId)) map.set(stageId, []);- map.get(stageId)!.push(task);- }- return map;-};--const addRunTimeToRequest = (request: BatchRunTasksRequest) => {- if (runTimeInMS.value === undefined) return;-- const seconds = Math.floor(runTimeInMS.value / 1000);- const nanos = (runTimeInMS.value % 1000) * 1000000;- request.runTime = create(TimestampSchema, {- seconds: BigInt(seconds),- nanos,- });-};--// Actions-const runTasks = async () => {- const tasksByStage = groupTasksByStage(eligibleTasks.value);- for (const [stageId, tasks] of tasksByStage) {- const request = create(BatchRunTasksRequestSchema, {- parent: `${rollout.value.name}/stages/${stageId}`,- tasks: tasks.map((task) => task.name),- });- addRunTimeToRequest(request);- request.skipPriorBackup = skipPriorBackup.value;- await rolloutServiceClientConnect.batchRunTasks(request);- }-};--const skipTasks = async () => {- const tasksByStage = groupTasksByStage(eligibleTasks.value);- for (const [stageId, tasks] of tasksByStage) {- const request = create(BatchSkipTasksRequestSchema, {- parent: `${rollout.value.name}/stages/${stageId}`,- tasks: tasks.map((task) => task.name),- reason: comment.value,- });- await rolloutServiceClientConnect.batchSkipTasks(request);- }-};--const cancelTasks = async () => {- const tasksByStage = groupTasksByStage(eligibleTasks.value);- const cancelableRuns = new Map<string, string[]>();-- // Fetch cancelable task runs for each stage- for (const [stageId, tasks] of tasksByStage) {- const taskNames = new Set(tasks.map((t) => t.name));- const parent = `${rollout.value.name}/stages/${stageId}/tasks/-`;- const response = await rolloutServiceClientConnect.listTaskRuns(- create(ListTaskRunsRequestSchema, { parent })- );-- const runs = (response.taskRuns || [])- .filter((run) => {- const taskName = run.name.split("/taskRuns/")[0];- return (- taskNames.has(taskName) &&- (run.status === TaskRun_Status.PENDING ||- run.status === TaskRun_Status.RUNNING)- );- })- .map((run) => run.name);-- if (runs.length > 0) {- cancelableRuns.set(`${rollout.value.name}/stages/${stageId}`, runs);- }- }-- // Cancel in parallel- await Promise.all(- Array.from(cancelableRuns.entries()).map(([stageName, runNames]) =>- rolloutServiceClientConnect.batchCancelTaskRuns(- create(BatchCancelTaskRunsRequestSchema, {- parent: `${stageName}/tasks/-`,- taskRuns: runNames,- })- )- )- );-};--const handleConfirm = async () => {- if (loading.value) return;-- loading.value = true;- try {- if (props.action === "RUN") await runTasks();- else if (props.action === "SKIP") await skipTasks();- else if (props.action === "CANCEL") await cancelTasks();-- emit("confirm");- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.error"),- description: String(error),- });- } finally {- loading.value = false;- emit("close");- }-};-</script>diff --git a/frontend/src/components/RolloutV1/components/Task/TaskStatus.vue b/frontend/src/components/RolloutV1/components/Task/TaskStatus.vuedeleted file mode 100644index 0c38744b3e..0000000000--- a/frontend/src/components/RolloutV1/components/Task/TaskStatus.vue+++ /dev/null@@ -1,128 +0,0 @@-<template>- <NTooltip :disabled="disabled">- <template #trigger>- <div- :class="- twMerge(- 'relative flex shrink-0 items-center justify-center rounded-full select-none overflow-hidden',- classes- )- "- >- <template v-if="status === Task_Status.STATUS_UNSPECIFIED">- <CircleDotDashedIcon class="w-full h-auto" />- </template>- <template- v-else-if="- status === Task_Status.NOT_STARTED- "- >- <span- class="h-1/2 w-1/2 bg-control rounded-full"- aria-hidden="true"- />- </template>- <template v-else-if="status === Task_Status.PENDING">- <PauseIcon class="w-3/4 h-auto" />- </template>- <template v-else-if="status === Task_Status.RUNNING">- <div class="flex h-1/2 w-1/2 relative overflow-visible">- <span- class="w-full h-full rounded-full z-0 absolute animate-ping-slow"- style="background-color: rgba(37, 99, 235, 0.5); /* bg-info/50 */"- aria-hidden="true"- />- <span- class="w-full h-full rounded-full z-1 bg-info"- aria-hidden="true"- />- </div>- </template>- <template v-else-if="status === Task_Status.SKIPPED">- <FastForwardIcon class="w-3/4 h-auto" />- </template>- <template v-else-if="status === Task_Status.DONE">- <heroicons-solid:check class="w-3/4 h-3/4" />- </template>- <template v-else-if="status === Task_Status.FAILED">- <span- class="rounded-full text-center font-medium text-base"- aria-hidden="true"- >!</span- >- </template>- <template v-else-if="status === Task_Status.CANCELED">- <heroicons-solid:minus-sm- class="w-full h-full rounded-full select-none bg-white border-2 border-control-light text-control-light"- />- </template>- </div>- </template>- {{ stringifyTaskStatus(status) }}- </NTooltip>-</template>--<script lang="ts" setup>-import {- CircleDotDashedIcon,- FastForwardIcon,- PauseIcon,-} from "lucide-vue-next";-import { NTooltip } from "naive-ui";-import { twMerge } from "tailwind-merge";-import { computed } from "vue";-import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";-import { stringifyTaskStatus } from "@/utils";--const props = defineProps<{- status: Task_Status;- size?: "tiny" | "small" | "medium" | "large";- disabled?: boolean;-}>();--const classes = computed((): string => {- let sizeClass = "";- switch (props.size) {- case "tiny":- sizeClass = "w-4 h-4";- break;- case "small":- sizeClass = "w-5 h-5";- break;- case "medium":- sizeClass = "w-6 h-6";- break;- case "large":- sizeClass = "w-7 h-7";- break;- default:- sizeClass = "w-6 h-6"; // default to medium if size is not specified- }-- let statusClass = "";- switch (props.status) {- case Task_Status.NOT_STARTED:- statusClass = "bg-white border-2 border-control";- break;- case Task_Status.PENDING:- statusClass = "bg-white border-2 border-info text-info";- break;- case Task_Status.RUNNING:- statusClass = "bg-white border-2 border-info text-info";- break;- case Task_Status.SKIPPED:- statusClass = "bg-white border-2 border-control-light text-gray-600";- break;- case Task_Status.DONE:- statusClass = "bg-success text-white";- break;- case Task_Status.FAILED:- statusClass = "bg-error text-white";- break;- default:- statusClass = "";- }-- return `${sizeClass} ${statusClass}`;-});-</script>diff --git a/frontend/src/components/RolloutV1/components/Task/TaskStatusActions.vue b/frontend/src/components/RolloutV1/components/Task/TaskStatusActions.vuedeleted file mode 100644index 191cacdbd7..0000000000--- a/frontend/src/components/RolloutV1/components/Task/TaskStatusActions.vue+++ /dev/null@@ -1,122 +0,0 @@-<template>- <div>- <div- v-if="hasActions"- class="flex flex-row justify-end items-center gap-x-2"- >- <NButton v-if="primaryAction" :size="size" @click="handlePrimaryAction">- {{ primaryActionLabel }}- </NButton>- <NDropdown- v-if="dropdownOptions.length > 0"- trigger="hover"- :options="dropdownOptions"- @select="handleDropdownSelect"- >- <NButton :size="size" class="px-1!" quaternary>- <template #icon>- <EllipsisVerticalIcon class="w-4 h-4" />- </template>- </NButton>- </NDropdown>- </div>-- <template v-if="currentAction && actionTarget">- <TaskRolloutActionPanel- :show="showActionPanel"- :action="currentAction"- :target="actionTarget"- @close="handleActionPanelClose"- @confirm="handleActionConfirmed"- />- </template>- </div>-</template>--<script setup lang="ts">-import { EllipsisVerticalIcon } from "lucide-vue-next";-import { NButton, NDropdown } from "naive-ui";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import type { Stage, Task } from "@/types/proto-es/v1/rollout_service_pb";-import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";-import TaskRolloutActionPanel from "./TaskRolloutActionPanel.vue";-import { useTaskActions } from "./useTaskActions";--const props = withDefaults(- defineProps<{- task: Task;- stage: Stage;- size?: "tiny" | "small" | "medium" | "large";- }>(),- {- size: "small",- }-);--const emit = defineEmits<{- "action-confirmed": [];-}>();--const { t } = useI18n();--const {- canRun,- canSkip,- canCancel,- hasActions,- showActionPanel,- currentAction,- actionTarget,- runTask,- skipTask,- cancelTask,- closeActionPanel,-} = useTaskActions(- () => props.task,- () => props.stage-);--const primaryAction = computed(() => {- if (canRun.value) {- if (props.task.status === Task_Status.FAILED) return "RETRY";- return "RUN";- }- return null;-});--const primaryActionLabel = computed(() => {- if (primaryAction.value === "RETRY") return t("common.retry");- if (primaryAction.value === "RUN") return t("common.run");- return "";-});--const dropdownOptions = computed(() => {- const options: { key: string; label: string }[] = [];- if (canSkip.value) {- options.push({ key: "SKIP", label: t("common.skip") });- }- if (canCancel.value) {- options.push({ key: "CANCEL", label: t("common.cancel") });- }- return options;-});--const handlePrimaryAction = () => {- runTask();-};--const handleDropdownSelect = (key: string) => {- if (key === "SKIP") skipTask();- else if (key === "CANCEL") cancelTask();-};--const handleActionPanelClose = () => {- closeActionPanel();-};--const handleActionConfirmed = () => {- closeActionPanel();- emit("action-confirmed");-};-</script>diff --git a/frontend/src/components/RolloutV1/components/Task/TaskTable.vue b/frontend/src/components/RolloutV1/components/Task/TaskTable.vuedeleted file mode 100644index 20e31dc29f..0000000000--- a/frontend/src/components/RolloutV1/components/Task/TaskTable.vue+++ /dev/null@@ -1,232 +0,0 @@-<template>- <NDataTable- size="small"- :columns="columnList"- :data="taskList"- :striped="true"- :bordered="false"- :row-key="(task: Task) => task.name"- :virtual-scroll="virtualScrollEnabled"- :max-height="'80vh'"- :row-height="virtualScrollEnabled ? 40 : undefined"- :row-props="rowProps"- :checked-row-keys="selectedTaskNames"- @update:checked-row-keys="handleSelectionChange"- />-</template>--<script lang="tsx" setup>-import type { Timestamp as TimestampProto } from "@bufbuild/protobuf/wkt";-import dayjs from "dayjs";-import { last } from "lodash-es";-import { CalendarClockIcon } from "lucide-vue-next";-import type { DataTableColumn } from "naive-ui";-import { NDataTable, NTag, NTooltip } from "naive-ui";-import { computed, watch } from "vue";-import { useI18n } from "vue-i18n";-import { useRouter } from "vue-router";-import Timestamp from "@/components/misc/Timestamp.vue";-import DatabaseDisplay from "@/components/Plan/components/common/DatabaseDisplay.vue";-import { usePlanContextWithRollout } from "@/components/Plan/logic";-import { buildTaskDetailRoute } from "@/router/dashboard/projectV1RouteHelpers";-import { useDatabaseV1Store } from "@/store";-import { getTimeForPbTimestampProtoEs } from "@/types";-import type { Task } from "@/types/proto-es/v1/rollout_service_pb";-import { Task_Status, Task_Type } from "@/types/proto-es/v1/rollout_service_pb";-import { humanizeTs } from "@/utils";-import TaskStatus from "./TaskStatus.vue";--const semanticTaskType = (type: Task_Type) => {- switch (type) {- case Task_Type.DATABASE_CREATE:- return t("task.type.database-create");- case Task_Type.DATABASE_MIGRATE:- return t("task.type.migrate");- case Task_Type.DATABASE_EXPORT:- return t("task.type.database-export");- case Task_Type.GENERAL:- return t("task.type.general");- default:- return "";- }-};--const props = withDefaults(- defineProps<{- taskStatusFilter: Task_Status[];- tasks: Task[];- selectedTasks?: Task[];- taskSelectable?: (task: Task) => boolean;- }>(),- {- selectedTasks: () => [],- taskSelectable: () => () => true,- }-);--const emit = defineEmits<{- (event: "update:selected-tasks", tasks: Task[]): void;-}>();--const { t } = useI18n();-const router = useRouter();-const databaseStore = useDatabaseV1Store();-const { taskRuns } = usePlanContextWithRollout();--const taskList = computed(() => {- if (props.taskStatusFilter.length === 0) {- return props.tasks;- }- return props.tasks.filter((task) =>- props.taskStatusFilter.includes(task.status)- );-});--// Selection handling-const selectedTaskNames = computed(() => {- return props.selectedTasks.map((task) => task.name);-});--const handleSelectionChange = (selectedKeys: Array<string | number>) => {- const selectedTasks = taskList.value.filter((task) =>- selectedKeys.includes(task.name)- );- emit("update:selected-tasks", selectedTasks);-};--// Virtual scroll configuration-const virtualScrollEnabled = computed(() => taskList.value.length > 100);--const prepareDatabases = async () => {- if (taskList.value.length > 0) {- try {- await databaseStore.batchGetOrFetchDatabases(- taskList.value.map((task) => task.target)- );- } catch {- // Ignore errors - this is just for pre-loading data- }- }-};--// Watch for task list changes and load database data-watch(- taskList,- () => {- prepareDatabases();- },- { immediate: true }-);--// Row click handler-const handleRowClick = (task: Task) => {- router.push(buildTaskDetailRoute(task.name));-};--// Row props for click handling-const rowProps = (task: Task) => {- return {- style: "cursor: pointer;",- onClick: () => handleRowClick(task),- };-};--// Get the latest TaskRun for a given task-const getLatestTaskRun = (task: Task) => {- const relatedTaskRuns = taskRuns.value.filter((taskRun) =>- taskRun.name.startsWith(task.name + "/taskRuns/")- );- return last(relatedTaskRuns);-};--// Format full datetime for display-const formatFullDateTime = (timestamp?: TimestampProto) => {- const timestampInMilliseconds = getTimeForPbTimestampProtoEs(timestamp, 0);- return dayjs(timestampInMilliseconds).local().format();-};--const columnList = computed((): DataTableColumn<Task>[] => {- return [- {- type: "selection",- width: 50,- disabled: (task: Task) => {- return !props.taskSelectable(task);- },- cellProps: () => {- return {- onClick: (e: MouseEvent) => {- e.stopPropagation();- },- };- },- },- {- key: "status",- title: "",- width: "36px",- render: (task) => <TaskStatus status={task.status} size="small" />,- },- {- key: "database",- title: t("common.database"),- resizable: true,- render: (task) => {- return (- <div class="flex items-center gap-2">- <DatabaseDisplay database={task.target} />- <NTag round size="small">- {semanticTaskType(task.type)}- </NTag>- {task.runTime && task.status === Task_Status.PENDING && (- <NTooltip>- {{- trigger: () => (- <NTag round size="small">- <div class="flex items-center gap-1">- <CalendarClockIcon class="w-3.5 h-3.5" />- {humanizeTs(- getTimeForPbTimestampProtoEs(task.runTime, 0) / 1000- )}- </div>- </NTag>- ),- default: () => (- <div class="flex flex-col gap-y-1">- <div class="text-sm opacity-80">- {t("task.scheduled-time")}- </div>- <div class="text-sm whitespace-nowrap">- {formatFullDateTime(task.runTime)}- </div>- </div>- ),- }}- </NTooltip>- )}- </div>- );- },- },- {- key: "detail",- title: t("common.detail"),- ellipsis: true,- resizable: true,- render: (task) => {- const latestTaskRun = getLatestTaskRun(task);- if (!latestTaskRun || !latestTaskRun.detail) {- return "-";- }- return latestTaskRun.detail;- },- },- {- key: "updateTime",- title: t("common.updated-at"),- width: 128,- render: (task) => <Timestamp timestamp={task.updateTime} />,- },- ];-});-</script>diff --git a/frontend/src/components/RolloutV1/components/Task/TaskToolbar.vue b/frontend/src/components/RolloutV1/components/Task/TaskToolbar.vuedeleted file mode 100644index 457b0a6732..0000000000--- a/frontend/src/components/RolloutV1/components/Task/TaskToolbar.vue+++ /dev/null@@ -1,315 +0,0 @@-<template>- <div- class="task-toolbar sticky top-0 z-10 px-4"- >- <div class="flex items-center justify-between border px-3 py-1 rounded-lg border-blue-200 bg-blue-100">- <!-- Left section -->- <div class="flex items-center gap-x-3">- <!-- Select all checkbox -->- <NTooltip :disabled="!isSelectAllDisabled || !getSelectAllTooltip()">- <template #trigger>- <NCheckbox- v-if="allTasks.length > 0"- :checked="allSelectableTasksSelected"- :indeterminate="someTasksSelected && !allSelectableTasksSelected"- :disabled="isSelectAllDisabled"- @update:checked="handleSelectAllChange"- />- </template>- <span class="w-56 text-sm">{{ getSelectAllTooltip() }}</span>- </NTooltip>-- <!-- Selection state -->- <span class="text-sm text-blue-900">- {{ selectionCountText }}- </span>-- <!-- Bulk actions (always shown) -->- <div class="flex items-center ">-- <NTooltip :disabled="!isRunDisabled || !getRunTooltip()">- <template #trigger>- <NButton- quaternary- size="small"- type="primary"- :disabled="isRunDisabled"- @click="handleAction('RUN')"- >- <template #icon>- <PlayIcon :size="14" />- </template>- {{ $t("common.run") }}- </NButton>- </template>- <span class="w-56 text-sm">{{ getRunTooltip() }}</span>- </NTooltip>-- <NTooltip :disabled="!isSkipDisabled || !getSkipTooltip()">- <template #trigger>- <NButton- quaternary- size="small"- type="primary"- :disabled="isSkipDisabled"- @click="handleAction('SKIP')"- >- <template #icon>- <SkipForwardIcon :size="14" />- </template>- {{ $t("common.skip") }}- </NButton>- </template>- <span class="w-56 text-sm">{{ getSkipTooltip() }}</span>- </NTooltip>-- <NTooltip :disabled="!isCancelDisabled || !getCancelTooltip()">- <template #trigger>- <NButton- quaternary- size="small"- type="primary"- :disabled="isCancelDisabled"- @click="handleAction('CANCEL')"- >- <template #icon>- <XIcon :size="14" />- </template>- {{ $t("common.cancel") }}- </NButton>- </template>- <span class="w-56 text-sm">{{ getCancelTooltip() }}</span>- </NTooltip>-- </div>- </div>-- </div>-- <!-- Action confirmation panel -->- <TaskRolloutActionPanel- v-if="showActionPanel && pendingAction"- :show="showActionPanel"- :action="pendingAction"- :target="{ type: 'tasks', tasks: selectedTasks, stage }"- @close="showActionPanel = false"- @confirm="handleActionPerformed"- />- </div>-</template>--<script lang="ts" setup>-import { PlayIcon, SkipForwardIcon, XIcon } from "lucide-vue-next";-import { NButton, NCheckbox, NTooltip } from "naive-ui";-import { computed, ref, watch } from "vue";-import { useI18n } from "vue-i18n";-import { usePlanContext } from "@/components/Plan/logic";-import {- CANCELABLE_TASK_STATUSES,- RUNNABLE_TASK_STATUSES,-} from "@/components/RolloutV1/constants/task";-import { useCurrentUserV1 } from "@/store";-import { userNamePrefix } from "@/store/modules/v1/common";-import { Issue_Type } from "@/types/proto-es/v1/issue_service_pb";-import type { Stage, Task } from "@/types/proto-es/v1/rollout_service_pb";-import type { TaskAction } from "../../types";-import TaskRolloutActionPanel from "./TaskRolloutActionPanel.vue";-import {- canRolloutTasks,- preloadRolloutPermissionContext,-} from "./taskPermissions";--const props = defineProps<{- selectedTasks: Task[];- allTasks: Task[];- isTaskSelectable: (task: Task) => boolean;- stage: Stage;-}>();--const emit = defineEmits<{- (event: "select-all"): void;- (event: "clear-selection"): void;- (event: "action-complete"): void;-}>();--const { t } = useI18n();-const { issue } = usePlanContext();-const currentUser = useCurrentUserV1();--const showActionPanel = ref(false);-const pendingAction = ref<TaskAction | null>(null);-const rolloutPermissionReady = ref(false);--watch(- () => props.allTasks.map((task) => task.name),- async () => {- rolloutPermissionReady.value = false;- await preloadRolloutPermissionContext(- props.allTasks,- props.stage.environment- );- rolloutPermissionReady.value = true;- },- { immediate: true }-);--const selectableTasks = computed(() => {- return props.allTasks.filter(props.isTaskSelectable);-});--const allSelectableTasksSelected = computed(() => {- if (selectableTasks.value.length === 0) {- return false;- }- return (- props.selectedTasks.length === selectableTasks.value.length &&- selectableTasks.value.every((task) =>- props.selectedTasks.some((st) => st.name === task.name)- )- );-});--const someTasksSelected = computed(() => {- return props.selectedTasks.length > 0 && !allSelectableTasksSelected.value;-});--const selectionCountText = computed(() => {- return t("rollout.task.selected-count", {- count: props.selectedTasks.length,- });-});--const isSelectAllDisabled = computed(() => {- return selectableTasks.value.length === 0;-});--const getSelectAllTooltip = () => {- if (selectableTasks.value.length === 0) {- return t("task.no-selectable-tasks");- }- return "";-};--const canPerformTaskActions = computed(() => {- if (!rolloutPermissionReady.value) return false;- return canRolloutTasks(- props.selectedTasks,- issue.value,- props.stage.environment- );-});--const hasRunnableTasks = computed(() => {- return props.selectedTasks.some((task) =>- RUNNABLE_TASK_STATUSES.includes(task.status)- );-});--const hasSkippableTasks = computed(() => {- return props.selectedTasks.some((task) =>- RUNNABLE_TASK_STATUSES.includes(task.status)- );-});--const hasCancellableTasks = computed(() => {- return props.selectedTasks.some((task) =>- CANCELABLE_TASK_STATUSES.includes(task.status)- );-});--/**- * Get base disabled tooltip for common conditions (no selection, no permission)- */-const getBaseDisabledTooltip = (): string => {- if (props.selectedTasks.length === 0) {- return t("task.no-tasks-selected");- }- if (!rolloutPermissionReady.value) {- return "";- }- if (!canPerformTaskActions.value) {- // Special message for data export issues when user is not the creator- if (- issue.value &&- issue.value.type === Issue_Type.DATABASE_EXPORT &&- issue.value.creator !== `${userNamePrefix}${currentUser.value.email}`- ) {- return t("task.data-export-creator-only");- }- return t("task.no-permission");- }- return "";-};--/**- * Get action-specific tooltip by combining base tooltip with action requirements- */-const getActionTooltip = (- hasValidTasks: boolean,- noValidTasksMessage: string-): string => {- const baseTooltip = getBaseDisabledTooltip();- if (baseTooltip) {- return baseTooltip;- }- if (!hasValidTasks) {- return noValidTasksMessage;- }- return "";-};--const getRunTooltip = () =>- getActionTooltip(hasRunnableTasks.value, t("task.no-runnable-tasks"));--const getSkipTooltip = () =>- getActionTooltip(hasSkippableTasks.value, t("task.no-skippable-tasks"));--const getCancelTooltip = () =>- getActionTooltip(hasCancellableTasks.value, t("task.no-cancellable-tasks"));--const isRunDisabled = computed(() => {- return (- props.selectedTasks.length === 0 ||- !rolloutPermissionReady.value ||- !hasRunnableTasks.value ||- !canPerformTaskActions.value- );-});--const isSkipDisabled = computed(() => {- return (- props.selectedTasks.length === 0 ||- !rolloutPermissionReady.value ||- !hasSkippableTasks.value ||- !canPerformTaskActions.value- );-});--const isCancelDisabled = computed(() => {- return (- props.selectedTasks.length === 0 ||- !rolloutPermissionReady.value ||- !hasCancellableTasks.value ||- !canPerformTaskActions.value- );-});--const handleSelectAllChange = (checked: boolean) => {- if (checked) {- emit("select-all");- } else {- emit("clear-selection");- }-};--const handleAction = (action: TaskAction) => {- pendingAction.value = action;- showActionPanel.value = true;-};--const handleActionPerformed = () => {- showActionPanel.value = false;- pendingAction.value = null;- emit("action-complete");-};-</script>diff --git a/frontend/src/components/RolloutV1/components/Task/TaskView.vue b/frontend/src/components/RolloutV1/components/Task/TaskView.vuedeleted file mode 100644index dadc3598c4..0000000000--- a/frontend/src/components/RolloutV1/components/Task/TaskView.vue+++ /dev/null@@ -1,275 +0,0 @@-<template>- <div v-if="task" class="w-full h-full flex flex-col gap-y-4 p-4">- <!-- Task Basic Info -->- <div class="w-full flex flex-col gap-y-3">- <div- class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3"- >- <div class="flex flex-row items-center gap-x-3 flex-wrap">- <NTag round>- {{ selectedStageTitle }}- </NTag>- <TaskStatus :status="task.status" />- <div class="flex flex-row items-center text-xl min-w-0">- <DatabaseDisplay :database="database.name" :size="'large'" />- </div>- <div class="flex flex-row gap-x-2 flex-wrap">- <NTooltip v-if="task.runTime && task.status === Task_Status.PENDING">- <template #trigger>- <NTag round>- <div class="flex items-center gap-1">- <CalendarClockIcon class="w-4 h-4 opacity-80" />- <span>{{- humanizeTs(- getTimeForPbTimestampProtoEs(task.runTime, 0) / 1000- )- }}</span>- </div>- </NTag>- </template>- <div class="flex flex-col gap-y-1">- <div class="text-sm opacity-80">- {{ $t("task.scheduled-time") }}- </div>- <div class="text-sm whitespace-nowrap">- {{ formatFullDateTime(task.runTime) }}- </div>- </div>- </NTooltip>- </div>- </div>-- <div class="flex justify-start sm:justify-end">- <!-- Task Status Actions -->- <TaskStatusActions- :task="task"- :stage="selectedStage!"- @action-confirmed="handleTaskActionConfirmed"- />- <!-- Rollback entry -->- <TaskRollbackButton- v-if="rollbackableTaskRun"- :task="task"- :task-run="rollbackableTaskRun"- :rollout="rollout"- />- </div>- </div>- </div>-- <!-- Latest Task Run Detail -->- <div v-if="latestTaskRun" class="w-full">- <div class="flex items-center justify-between">- <span class="text-base font-medium">{{- $t("task-run.latest-logs")- }}</span>- </div>- <TaskRunDetail :task-run="latestTaskRun" :database="database" />- </div>-- <!-- Task Runs Table -->- <div v-if="taskRuns.length > 0" class="w-full">- <div class="flex items-center justify-between mb-2">- <span class="text-base font-medium">{{ $t("task-run.history") }}</span>- </div>- <TaskRunTable :task-runs="taskRuns" />- </div>-- <!-- Sheet Statement -->- <div v-if="!isReleaseTask" class="w-full flex-1 min-h-0">- <div class="flex items-center justify-between mb-2">- <span class="text-base font-medium">{{ $t("common.statement") }}</span>- <div>- <RouterLink- v-if="relatedSpec"- :to="{- name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,- params: {- projectId: extractProjectResourceName(plan.name),- planId: extractPlanUID(plan.name),- specId: relatedSpec.id,- },- }"- >- <NButton size="small" text type="primary">- <template #icon>- <LinkIcon :size="14" />- </template>- <span class="underline">- {{ $t("plan.spec.change") }}: {{ getSpecTitle(relatedSpec) }}- </span>- </NButton>- </RouterLink>- </div>- </div>- <MonacoEditor- v-if="statement"- class="h-full min-h-[200px] border rounded-[3px] text-sm overflow-clip"- :content="statement"- :readonly="true"- :auto-height="{ min: 200, max: 480 }"- />- <div- v-else- class="h-32 border rounded-[3px] flex items-center justify-center text-control"- >- {{ $t("common.no-data") }}- </div>- </div>-- <!-- Release Info for release-based tasks -->- <ReleaseInfoCard- v-else- :release-name="releaseName"- class="w-full"- />- </div>-</template>--<script setup lang="ts">-import type { Timestamp } from "@bufbuild/protobuf/wkt";-import dayjs from "dayjs";-import { last } from "lodash-es";-import { CalendarClockIcon, LinkIcon } from "lucide-vue-next";-import { NButton, NTag, NTooltip } from "naive-ui";-import { computed, watchEffect } from "vue";-import { RouterLink } from "vue-router";-import { MonacoEditor } from "@/components/MonacoEditor";-import DatabaseDisplay from "@/components/Plan/components/common/DatabaseDisplay.vue";-import {- emitPlanStatusChanged,- getSpecTitle,- usePlanContextWithRollout,-} from "@/components/Plan/logic";-import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";-import {- taskRunNamePrefix,- useCurrentProjectV1,- useEnvironmentV1Store,- useSheetV1Store,-} from "@/store";-import { getTimeForPbTimestampProtoEs, unknownTask } from "@/types";-import {- Task_Status,- TaskRun_Status,-} from "@/types/proto-es/v1/rollout_service_pb";-import {- databaseForTask,- extractPlanUID,- extractProjectResourceName,- getSheetStatement,- isReleaseBasedTask,- releaseNameOfTaskV1,- sheetNameOfTaskV1,-} from "@/utils";-import ReleaseInfoCard from "../Rollout/ReleaseInfoCard.vue";-import TaskRunDetail from "../TaskRun/TaskRunDetail.vue";-import TaskRunTable from "../TaskRun/TaskRunTable.vue";-import TaskRollbackButton from "./TaskRollbackButton.vue";-import TaskStatus from "./TaskStatus.vue";-import TaskStatusActions from "./TaskStatusActions.vue";--const props = defineProps<{- planId: string;- stageId: string;- taskId: string;-}>();--const { project } = useCurrentProjectV1();-const {- rollout,- taskRuns: allTaskRuns,- events,- plan,-} = usePlanContextWithRollout();-const sheetStore = useSheetV1Store();-const environmentStore = useEnvironmentV1Store();--// Stage-related computed properties-// Stage → Task relationship: Access tasks via stage.tasks array-const selectedStage = computed(() => {- return rollout.value.stages.find((s) => s.id === props.stageId);-});--const selectedStageEnvironment = computed(() => {- if (!selectedStage.value?.environment) return undefined;- return environmentStore.getEnvironmentByName(selectedStage.value.environment);-});--const selectedStageTitle = computed(() => {- // Prefer environment title, fallback to stage name- return (- selectedStageEnvironment.value?.title || selectedStage.value?.name || ""- );-});--// Task-related computed properties-// Efficient lookup: We already have the stage from URL, so search within that stage's tasks only-const task = computed(() => {- return (- selectedStage.value?.tasks.find((t) =>- t.name.endsWith(`/${props.taskId}`)- ) || unknownTask()- );-});--const isReleaseTask = computed(() => isReleaseBasedTask(task.value));--// Release name for release-based tasks-const releaseName = computed(() => releaseNameOfTaskV1(task.value));--const taskRuns = computed(() => {- return allTaskRuns.value.filter((run) =>- run.name.startsWith(`${task.value.name}/${taskRunNamePrefix}`)- );-});--const latestTaskRun = computed(() => last(taskRuns.value));--const rollbackableTaskRun = computed(() => {- if (- latestTaskRun.value &&- latestTaskRun.value.status === TaskRun_Status.DONE &&- latestTaskRun.value.hasPriorBackup- ) {- return latestTaskRun.value;- }- return undefined;-});--// Task basic info-const database = computed(() => databaseForTask(project.value, task.value));--// Related spec-const relatedSpec = computed(() => {- if (!plan.value || !task.value.specId) return undefined;- return plan.value.specs.find((spec) => spec.id === task.value.specId);-});--const formatFullDateTime = (timestamp?: Timestamp) => {- const timestampInMilliseconds = getTimeForPbTimestampProtoEs(timestamp, 0);- return dayjs(timestampInMilliseconds).local().format();-};--// Sheet statement-const statement = computed(() => {- const sheet = sheetStore.getSheetByName(sheetNameOfTaskV1(task.value));- if (sheet) {- return getSheetStatement(sheet);- }- return "";-});--// Prepare sheet of the task.-watchEffect(async () => {- const sheetName = sheetNameOfTaskV1(task.value);- if (sheetName) {- await sheetStore.getOrFetchSheetByName(sheetName);- }-});--// Handle task action completion to refresh data-const handleTaskActionConfirmed = async () => {- emitPlanStatusChanged(events, { refreshMode: "fast-follow" });-};-</script>diff --git a/frontend/src/components/RolloutV1/components/Task/taskPermissions.ts b/frontend/src/components/RolloutV1/components/Task/taskPermissions.tsdeleted file mode 100644index 9f9b7db730..0000000000--- a/frontend/src/components/RolloutV1/components/Task/taskPermissions.ts+++ /dev/null@@ -1,154 +0,0 @@-import {- useCurrentUserV1,- usePolicyV1Store,- useProjectIamPolicyStore,- useProjectV1Store,-} from "@/store";-import { projectNamePrefix, roleNamePrefix } from "@/store/modules/v1/common";-import type { Issue } from "@/types/proto-es/v1/issue_service_pb";-import { Issue_Type } from "@/types/proto-es/v1/issue_service_pb";-import { PolicyType } from "@/types/proto-es/v1/org_policy_service_pb";-import type { Task } from "@/types/proto-es/v1/rollout_service_pb";-import {- extractProjectResourceName,- hasProjectPermissionV2,- hasWorkspacePermissionV2,- memberMapToRolesInProjectIAM,-} from "@/utils";--type RolloutPolicyAccessState = "loaded" | "unavailable";--const rolloutPolicyAccessStateByEnvironment = new Map<- string,- RolloutPolicyAccessState->();--/**- * Derive the full project resource name from the issue or first task.- * Both carry the project id in their resource name- * (e.g. "projects/foo/issues/1" or "projects/foo/rollouts/…").- */-const resolveProjectName = (tasks: Task[], issue?: Issue): string => {- const source = issue?.name ?? tasks[0]?.name ?? "";- const id = extractProjectResourceName(source);- return id ? `${projectNamePrefix}${id}` : "";-};--/**- * Check if the current user can rollout the given tasks- * - For data export issues: only the issue creator can rollout- * - If user has bb.taskRuns.create permission → always allow- * - If user lacks bb.taskRuns.create permission → check environment rollout policy roles- * @param tasks - Array of tasks to check- * @param issue - Optional issue to check for data export special handling- * @returns true if user can rollout, false otherwise- */-export const canRolloutTasks = (- tasks: Task[],- issue?: Issue,- environment?: string-): boolean => {- if (tasks.length === 0) {- return false;- }-- const currentUser = useCurrentUserV1();-- // Special check for data export issues: only the creator can run tasks- if (issue && issue.type === Issue_Type.DATABASE_EXPORT) {- return issue.creator === currentUser.value.name;- }-- // Resolve project from issue/task resource name instead of useRoute()- // so the check works correctly inside async callbacks (after await).- const projectName = resolveProjectName(tasks, issue);- const project = useProjectV1Store().getProjectByName(projectName);-- // First check: if user has bb.taskRuns.create permission, always allow rollout- const hasCreatePermission =- hasWorkspacePermissionV2("bb.taskRuns.create") ||- hasProjectPermissionV2(project, "bb.taskRuns.create");- if (hasCreatePermission) {- return true;- }-- // Second check: if no permission, check if user matches environment rollout policy roles- const projectIamPolicyStore = useProjectIamPolicyStore();- const policyStore = usePolicyV1Store();- const projectIamPolicy = projectIamPolicyStore.getProjectIamPolicy(- project.name- );- const memberRoles = memberMapToRolesInProjectIAM(projectIamPolicy);- const userRoles = memberRoles.get(currentUser.value.name);-- return tasks.every(() => {- if (!environment) {- return false;- }-- // Get rollout policy for the environment.- // Policy data is expected to already be prefetched by the surrounding page.- const rolloutPolicy = policyStore.getPolicyByParentAndType({- parentPath: environment,- policyType: PolicyType.ROLLOUT_POLICY,- });-- // If policy data is not in cache yet, fail closed until the surrounding view- // has preloaded the relevant rollout policies.- if (!rolloutPolicy) {- return (- rolloutPolicyAccessStateByEnvironment.get(environment) === "unavailable"- );- }-- // If no rollout policy is defined, allow rollout.- if (- !rolloutPolicy?.policy ||- rolloutPolicy.policy.case !== "rolloutPolicy"- ) {- return true;- }-- const policy = rolloutPolicy.policy.value;-- // Check if current user has any of the required roles in the rollout policy- for (const requiredRole of policy.roles) {- if (- requiredRole.startsWith(roleNamePrefix) &&- userRoles?.has(requiredRole)- ) {- return true;- }- }-- return false;- });-};--export const preloadRolloutPermissionContext = async (- tasks: Task[],- environment?: string,- issue?: Issue-) => {- if (tasks.length === 0 || !environment) return;-- const projectName = resolveProjectName(tasks, issue);- const policyStore = usePolicyV1Store();- const projectIamPolicyStore = useProjectIamPolicyStore();-- await Promise.allSettled([- projectIamPolicyStore.getOrFetchProjectIamPolicy(projectName),- ]);-- const policyResults = await Promise.allSettled([- policyStore.getOrFetchPolicyByParentAndType({- parentPath: environment,- policyType: PolicyType.ROLLOUT_POLICY,- }),- ]);-- rolloutPolicyAccessStateByEnvironment.set(- environment,- policyResults[0]?.status === "fulfilled" ? "loaded" : "unavailable"- );-};diff --git a/frontend/src/components/RolloutV1/components/Task/useExpectedTaskCount.ts b/frontend/src/components/RolloutV1/components/Task/useExpectedTaskCount.tsdeleted file mode 100644index 02d475a695..0000000000--- a/frontend/src/components/RolloutV1/components/Task/useExpectedTaskCount.ts+++ /dev/null@@ -1,45 +0,0 @@-import type { Ref } from "vue";-import { ref, watch } from "vue";-import { useDBGroupStore } from "@/store";-import { isValidDatabaseGroupName } from "@/types";-import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";-import type { Plan } from "@/types/proto-es/v1/plan_service_pb";--export const useExpectedTaskCount = (plan: Ref<Plan>) => {- const dbGroupStore = useDBGroupStore();- const expectedTaskCount = ref(0);-- const countTargets = async (targets: string[]): Promise<number> => {- let count = 0;- for (const target of targets) {- if (isValidDatabaseGroupName(target)) {- try {- const dbGroup = await dbGroupStore.getOrFetchDBGroupByName(target, {- view: DatabaseGroupView.FULL,- silent: true,- });- count += dbGroup.matchedDatabases?.length ?? 0;- } catch {- // Ignore errors- }- } else {- count++;- }- }- return count;- };-- const update = async () => {- let count = 0;- for (const spec of plan.value.specs) {- if (spec.config.case === "changeDatabaseConfig") {- count += await countTargets(spec.config.value.targets ?? []);- }- }- expectedTaskCount.value = count;- };-- watch(() => plan.value.specs, update, { immediate: true });-- return { expectedTaskCount };-};diff --git a/frontend/src/components/RolloutV1/components/Task/useTaskActions.ts b/frontend/src/components/RolloutV1/components/Task/useTaskActions.tsdeleted file mode 100644index 31102c33ed..0000000000--- a/frontend/src/components/RolloutV1/components/Task/useTaskActions.ts+++ /dev/null@@ -1,130 +0,0 @@-import type { ComputedRef, Ref } from "vue";-import { computed, ref, watch } from "vue";-import { usePlanContext } from "@/components/Plan/logic";-import {- CANCELABLE_TASK_STATUSES,- RUNNABLE_TASK_STATUSES,-} from "@/components/RolloutV1/constants/task";-import type { Stage, Task } from "@/types/proto-es/v1/rollout_service_pb";-import type { TaskAction } from "../../types";-import {- canRolloutTasks,- preloadRolloutPermissionContext,-} from "./taskPermissions";--export interface TaskActionTarget {- type: "tasks";- tasks: Task[];- stage: Stage;-}--export interface UseTaskActionsReturn {- canRun: ComputedRef<boolean>;- canSkip: ComputedRef<boolean>;- canCancel: ComputedRef<boolean>;- hasActions: ComputedRef<boolean>;- showActionPanel: Ref<boolean>;- currentAction: ComputedRef<TaskAction | undefined>;- actionTarget: ComputedRef<TaskActionTarget | undefined>;- runTask: () => void;- skipTask: () => void;- cancelTask: () => void;- closeActionPanel: () => void;-}--export const useTaskActions = (- task: () => Task,- stage: () => Stage | undefined-): UseTaskActionsReturn => {- const showActionPanel = ref(false);- const selectedAction = ref<TaskAction>();- const { issue } = usePlanContext();-- // Cache permission check - only re-evaluate when task name changes- // This prevents flickering during poller refetches- const canPerformActions = ref(false);- watch(- () => task().name,- async () => {- canPerformActions.value = false;- const environment = stage()?.environment;- await preloadRolloutPermissionContext([task()], environment);- canPerformActions.value = canRolloutTasks(- [task()],- issue.value,- environment- );- },- { immediate: true }- );-- // Use stable primitive for status to prevent re-computation on object reference change- const taskStatus = computed(() => task().status);-- const canRun = computed(- () =>- canPerformActions.value &&- RUNNABLE_TASK_STATUSES.includes(taskStatus.value)- );-- const canSkip = computed(- () =>- canPerformActions.value &&- RUNNABLE_TASK_STATUSES.includes(taskStatus.value)- );-- const canCancel = computed(- () =>- canPerformActions.value &&- CANCELABLE_TASK_STATUSES.includes(taskStatus.value)- );-- const hasActions = computed(- () => canRun.value || canSkip.value || canCancel.value- );-- const currentAction = computed(() =>- showActionPanel.value && selectedAction.value- ? selectedAction.value- : undefined- );-- const actionTarget = computed((): TaskActionTarget | undefined => {- const s = stage();- if (!currentAction.value || !s) return undefined;- return { type: "tasks", tasks: [task()], stage: s };- });-- const runTask = () => {- selectedAction.value = "RUN";- showActionPanel.value = true;- };-- const skipTask = () => {- selectedAction.value = "SKIP";- showActionPanel.value = true;- };-- const cancelTask = () => {- selectedAction.value = "CANCEL";- showActionPanel.value = true;- };-- const closeActionPanel = () => {- showActionPanel.value = false;- };-- return {- canRun,- canSkip,- canCancel,- hasActions,- showActionPanel,- currentAction,- actionTarget,- runTask,- skipTask,- cancelTask,- closeActionPanel,- };-};diff --git a/frontend/src/components/RolloutV1/components/Task/useTaskCollapse.ts b/frontend/src/components/RolloutV1/components/Task/useTaskCollapse.tsdeleted file mode 100644index 043bd21678..0000000000--- a/frontend/src/components/RolloutV1/components/Task/useTaskCollapse.ts+++ /dev/null@@ -1,64 +0,0 @@-import { head } from "lodash-es";-import { type Ref, ref, watch } from "vue";-import type { Task } from "@/types/proto-es/v1/rollout_service_pb";-import { isValidTaskName } from "@/utils";-import { addToSet, deleteFromSet } from "../shared/reactivity";--export interface UseTaskCollapseReturn {- expandedTaskIds: Ref<Set<string>>;- isTaskExpanded: (task: Task) => boolean;- toggleExpand: (task: Task) => void;-}--export const useTaskCollapse = (tasks: Ref<Task[]>): UseTaskCollapseReturn => {- const expandedTaskIds = ref<Set<string>>(new Set());- const lastTaskNames = ref<string>("");-- const isTaskExpanded = (task: Task): boolean => {- if (isValidTaskName(task.name)) {- return expandedTaskIds.value.has(task.name);- }- return false;- };-- const toggleExpand = (task: Task) => {- if (expandedTaskIds.value.has(task.name)) {- deleteFromSet(expandedTaskIds, task.name);- } else {- addToSet(expandedTaskIds, task.name);- }- };-- // Auto-expand first non-completed task when tasks change (initial load or stage switch)- watch(- tasks,- (newTasks) => {- if (newTasks.length === 0) {- return;- }-- // Create a unique identifier for the current task set- const currentTaskNames = newTasks.map((t) => t.name).join(",");-- // If tasks have changed (stage switch) or it's the first load, reset and auto-expand- if (currentTaskNames !== lastTaskNames.value) {- lastTaskNames.value = currentTaskNames;-- // Clear expanded tasks from previous stage- expandedTaskIds.value.clear();-- const taskToExpand = head(newTasks);- if (taskToExpand) {- addToSet(expandedTaskIds, taskToExpand.name);- }- }- },- { immediate: true }- );-- return {- expandedTaskIds,- isTaskExpanded,- toggleExpand,- };-};diff --git a/frontend/src/components/RolloutV1/components/Task/useTaskDisplay.ts b/frontend/src/components/RolloutV1/components/Task/useTaskDisplay.tsdeleted file mode 100644index 56d1749c64..0000000000--- a/frontend/src/components/RolloutV1/components/Task/useTaskDisplay.ts+++ /dev/null@@ -1,61 +0,0 @@-import type { ComputedRef } from "vue";-import { computed } from "vue";-import type { Task, TaskRun } from "@/types/proto-es/v1/rollout_service_pb";-import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";--export interface UseTaskDisplayReturn {- executorEmail: ComputedRef<string>;- collapsedContextInfo: ComputedRef<string>;- collapsedStatusText: ComputedRef<string>;-}--/**- * Composable for task display formatting.- * Handles task type labels, executor info, and collapsed view display.- */-export const useTaskDisplay = (- task: () => Task,- latestTaskRun: () => TaskRun | undefined,- timingDisplay: () => string,- affectedRowsDisplay: () => string-): UseTaskDisplayReturn => {- const executorEmail = computed(() => {- const creator = latestTaskRun()?.creator || "";- const match = creator.match(/users\/([^/]+)/);- return match?.[1] || "";- });-- // Collapsed view: contextual info (duration, affected rows for completed tasks)- const collapsedContextInfo = computed(() => {- if (task().status !== Task_Status.DONE) return "";-- const parts: string[] = [];- if (timingDisplay()) parts.push(timingDisplay());- if (affectedRowsDisplay()) parts.push(affectedRowsDisplay());- return parts.join(" · ");- });-- // Collapsed view: error or skip reason- const collapsedStatusText = computed(() => {- const detail = latestTaskRun()?.detail || "";- if (detail) {- return detail;- }-- const currentTask = task();- if (- currentTask.status === Task_Status.SKIPPED &&- currentTask.skippedReason- ) {- return currentTask.skippedReason;- }-- return "";- });-- return {- executorEmail,- collapsedContextInfo,- collapsedStatusText,- };-};diff --git a/frontend/src/components/RolloutV1/components/Task/useTaskInstancePreload.ts b/frontend/src/components/RolloutV1/components/Task/useTaskInstancePreload.tsdeleted file mode 100644index 719af20dd9..0000000000--- a/frontend/src/components/RolloutV1/components/Task/useTaskInstancePreload.ts+++ /dev/null@@ -1,45 +0,0 @@-import { ref, watch } from "vue";-import { useDatabaseV1Store } from "@/store";-import type { Stage } from "@/types/proto-es/v1/rollout_service_pb";--/**- * Preloads databases (and their instances) referenced by tasks- * This ensures database and engine icons display correctly- */-export const useTaskInstancePreload = (stages: () => Stage[]) => {- const databaseStore = useDatabaseV1Store();- const fetchedDatabases = ref(new Set<string>());-- watch(- stages,- async (currentStages) => {- const uniqueDatabaseNames = new Set<string>();-- // Extract all unique database names from task targets- for (const stage of currentStages) {- for (const task of stage.tasks) {- if (task.target) {- uniqueDatabaseNames.add(task.target);- }- }- }-- // Only fetch databases we haven't fetched yet- const newDatabases = Array.from(uniqueDatabaseNames).filter(- (name) => !fetchedDatabases.value.has(name)- );-- if (newDatabases.length > 0) {- // Batch fetch databases (which also fetches their instances)- try {- await databaseStore.batchGetOrFetchDatabases(newDatabases);- // Mark these databases as fetched- newDatabases.forEach((name) => fetchedDatabases.value.add(name));- } catch {- // Ignore errors - this is just for pre-loading data- }- }- },- { immediate: true }- );-};diff --git a/frontend/src/components/RolloutV1/components/Task/useTaskNavigation.ts b/frontend/src/components/RolloutV1/components/Task/useTaskNavigation.tsdeleted file mode 100644index 15dac8f87c..0000000000--- a/frontend/src/components/RolloutV1/components/Task/useTaskNavigation.ts+++ /dev/null@@ -1,15 +0,0 @@-import { useRouter } from "vue-router";-import { buildTaskDetailRoute } from "@/router/dashboard/projectV1RouteHelpers";-import type { Task } from "@/types/proto-es/v1/rollout_service_pb";--export const useTaskNavigation = () => {- const router = useRouter();-- const navigateToTaskDetail = (task: Task) => {- router.push(buildTaskDetailRoute(task.name));- };-- return {- navigateToTaskDetail,- };-};diff --git a/frontend/src/components/RolloutV1/components/Task/useTaskSelection.ts b/frontend/src/components/RolloutV1/components/Task/useTaskSelection.tsdeleted file mode 100644index 55f2d602f3..0000000000--- a/frontend/src/components/RolloutV1/components/Task/useTaskSelection.ts+++ /dev/null@@ -1,67 +0,0 @@-import { type ComputedRef, computed, type Ref, ref } from "vue";-import type { Task } from "@/types/proto-es/v1/rollout_service_pb";-import {- addToSet,- clearSet,- deleteFromSet,- triggerSetReactivity,-} from "../shared/reactivity";-import { isTaskSelectable } from "../shared/taskStatus";--export interface UseTaskSelectionReturn {- selectedTaskIds: Ref<Set<string>>;- selectedTasks: ComputedRef<Task[]>;- isTaskSelected: (task: Task) => boolean;- isTaskSelectable: (task: Task) => boolean;- toggleSelect: (task: Task) => void;- selectAll: () => void;- clearSelection: () => void;-}--export const useTaskSelection = (- tasks: Ref<Task[]>-): UseTaskSelectionReturn => {- const selectedTaskIds = ref<Set<string>>(new Set());-- const selectedTasks = computed(() => {- return tasks.value.filter((task) => selectedTaskIds.value.has(task.name));- });-- const isTaskSelected = (task: Task): boolean => {- return selectedTaskIds.value.has(task.name);- };-- const toggleSelect = (task: Task) => {- if (!isTaskSelectable(task)) {- return;- }-- if (selectedTaskIds.value.has(task.name)) {- deleteFromSet(selectedTaskIds, task.name);- } else {- addToSet(selectedTaskIds, task.name);- }- };-- const selectAll = () => {- const selectableTasks = tasks.value.filter(isTaskSelectable);- selectableTasks.forEach((task) => {- selectedTaskIds.value.add(task.name);- });- triggerSetReactivity(selectedTaskIds);- };-- const clearSelection = () => {- clearSet(selectedTaskIds);- };-- return {- selectedTaskIds,- selectedTasks,- isTaskSelected,- isTaskSelectable,- toggleSelect,- selectAll,- clearSelection,- };-};diff --git a/frontend/src/components/RolloutV1/components/Task/useTaskStatement.ts b/frontend/src/components/RolloutV1/components/Task/useTaskStatement.tsdeleted file mode 100644index 923a690599..0000000000--- a/frontend/src/components/RolloutV1/components/Task/useTaskStatement.ts+++ /dev/null@@ -1,76 +0,0 @@-import { type ComputedRef, computed, type Ref, ref, watchEffect } from "vue";-import { useI18n } from "vue-i18n";-import { useSheetV1Store } from "@/store";-import type { Task } from "@/types/proto-es/v1/rollout_service_pb";-import { getSheetStatement, sheetNameOfTaskV1 } from "@/utils";-import { MAX_STATEMENT_DISPLAY_SIZE } from "../../constants";--export interface UseTaskStatementReturn {- loading: Ref<boolean>;- displayedStatement: ComputedRef<string>;- isStatementTruncated: ComputedRef<boolean>;-}--export const useTaskStatement = (- task: () => Task,- isExpanded: () => boolean-): UseTaskStatementReturn => {- const { t } = useI18n();- const sheetStore = useSheetV1Store();-- const loading = ref(false);- const statement = ref("");-- // Only fetch statement when expanded (no preview needed for collapsed view)- watchEffect(async () => {- if (!isExpanded()) {- // Skip fetching for collapsed tasks- return;- }-- const sheetName = sheetNameOfTaskV1(task());- if (!sheetName) {- statement.value = "";- return;- }-- // Check cache first- const cachedSheet = sheetStore.getSheetByName(sheetName);- if (cachedSheet) {- statement.value = getSheetStatement(cachedSheet);- return;- }-- // Fetch if not in cache- loading.value = true;- try {- await sheetStore.getOrFetchSheetByName(sheetName);- const sheet = sheetStore.getSheetByName(sheetName);- statement.value = sheet ? getSheetStatement(sheet) : "";- } finally {- loading.value = false;- }- });-- // Check if statement exceeds display limit- const isStatementTruncated = computed(() => {- return statement.value.length > MAX_STATEMENT_DISPLAY_SIZE;- });-- // Statement for expanded view (truncated if too large for performance)- const displayedStatement = computed(() => {- if (!statement.value) {- return t("rollout.task.no-statement");- }- if (isStatementTruncated.value) {- return statement.value.substring(0, MAX_STATEMENT_DISPLAY_SIZE);- }- return statement.value;- });-- return {- loading,- displayedStatement,- isStatementTruncated,- };-};diff --git a/frontend/src/components/RolloutV1/components/Task/useTaskTiming.ts b/frontend/src/components/RolloutV1/components/Task/useTaskTiming.tsdeleted file mode 100644index cb6c2abe2b..0000000000--- a/frontend/src/components/RolloutV1/components/Task/useTaskTiming.ts+++ /dev/null@@ -1,75 +0,0 @@-import type { ComputedRef } from "vue";-import { computed } from "vue";-import type { Task, TaskRun } from "@/types/proto-es/v1/rollout_service_pb";-import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";-import { formatAbsoluteDateTime } from "@/utils";-import { getTaskRunDuration } from "../TaskRun/useTaskRunUtils";--export type TimingType = "scheduled" | "running" | "completed" | "none";--export interface UseTaskTimingReturn {- timingDisplay: ComputedRef<string>;- timingType: ComputedRef<TimingType>;- scheduledTime: ComputedRef<Date | undefined>;-}--export const useTaskTiming = (- task: () => Task,- latestTaskRun: () => TaskRun | undefined-): UseTaskTimingReturn => {- const scheduledTime = computed(() => {- const currentTask = task();- if (currentTask.status === Task_Status.PENDING && currentTask.runTime) {- const runTimeMs = Number(currentTask.runTime.seconds) * 1000;- if (runTimeMs > Date.now()) {- return new Date(runTimeMs);- }- }- return undefined;- });-- const timingType = computed((): TimingType => {- const currentTask = task();- const status = currentTask.status;-- if (scheduledTime.value) {- return "scheduled";- }-- if (status === Task_Status.RUNNING) {- return "running";- }-- if (- status === Task_Status.DONE ||- status === Task_Status.FAILED ||- status === Task_Status.CANCELED- ) {- return "completed";- }-- return "none";- });-- const timingDisplay = computed(() => {- const taskRun = latestTaskRun();- const type = timingType.value;-- if (type === "scheduled" && scheduledTime.value) {- return formatAbsoluteDateTime(scheduledTime.value.getTime());- }-- // Use getTaskRunDuration for running and completed tasks- if ((type === "running" || type === "completed") && taskRun) {- return getTaskRunDuration(taskRun);- }-- return "";- });-- return {- timingDisplay,- timingType,- scheduledTime,- };-};diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunComment.vue b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunComment.vuedeleted file mode 100644index 2a0e286f78..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunComment.vue+++ /dev/null@@ -1,104 +0,0 @@-<template>- <div class="flex flex-col xl:flex-row xl:items-center xl:gap-x-1">- <NEllipsis- :expand-trigger="expandTrigger || undefined"- :line-clamp="lineClamp"- :tooltip="false"- >- <span>{{ comment }}</span>- </NEllipsis>- <template v-if="commentLink.link">- <router-link- v-if="commentLink.link.startsWith('/')"- class="inline normal-link shrink-0"- :to="commentLink.link"- >- {{ commentLink.title }}- </router-link>- <a- v-else- class="inline normal-link shrink-0"- :href="commentLink.link"- target="_blank"- rel="noopener noreferrer"- >- {{ commentLink.title }}- </a>- </template>- </div>-</template>--<script setup lang="tsx">-import { NEllipsis } from "naive-ui";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import { getTimeForPbTimestampProtoEs } from "@/types";-import type { TaskRun } from "@/types/proto-es/v1/rollout_service_pb";-import { TaskRun_Status } from "@/types/proto-es/v1/rollout_service_pb";-import { formatAbsoluteDateTime } from "@/utils";--export type CommentLink = {- title: string;- link: string;-};--const props = withDefaults(- defineProps<{- taskRun: TaskRun;- expandTrigger?: false | "click";- lineClamp?: number;- }>(),- {- expandTrigger: "click",- lineClamp: 2,- }-);--const { t } = useI18n();--const earliestAllowedTime = computed(() => {- return props.taskRun.runTime- ? getTimeForPbTimestampProtoEs(props.taskRun.runTime)- : null;-});--const comment = computed(() => {- const { taskRun } = props;- if (taskRun.status === TaskRun_Status.PENDING) {- if (earliestAllowedTime.value) {- return t("task-run.status.enqueued-with-rollout-time", {- time: formatAbsoluteDateTime(earliestAllowedTime.value),- });- }- return t("task-run.status.enqueued");- } else if (taskRun.status === TaskRun_Status.RUNNING) {- if (taskRun.schedulerInfo) {- const cause = taskRun.schedulerInfo.waitingCause;- if (cause?.cause?.case === "parallelTasksLimit") {- return t("task-run.status.waiting-max-tasks-per-rollout", {- time: formatAbsoluteDateTime(- getTimeForPbTimestampProtoEs(taskRun.schedulerInfo.reportTime)- ),- });- }- }- }- return taskRun.detail || "-";-});--const commentLink = computed((): CommentLink => {- const { taskRun } = props;- if (taskRun.status === TaskRun_Status.FAILED) {- if (comment.value.includes("version")) {- return {- title: t("common.troubleshoot"),- link: "https://docs.bytebase.com/change-database/troubleshoot/?source=console#duplicate-version",- };- }- }- return {- title: "",- link: "",- };-});-</script>diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunDetail.vue b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunDetail.vuedeleted file mode 100644index 0d9af1e10a..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunDetail.vue+++ /dev/null@@ -1,75 +0,0 @@-<template>- <NTabs v-model:value="state.currentTab" type="line">- <NTabPane name="LOG" :tab="$t('issue.task-run.logs')">- <TaskRunLogViewer- v-if="taskRun.name"- :key="componentId"- :task-run-name="taskRun.name"- />- </NTabPane>- <NTabPane- v-if="showTaskRunSessionTab"- name="SESSION"- :tab="$t('issue.task-run.session')"- >- <TaskRunSession :key="componentId" :task-run="taskRun" />- </NTabPane>-- <template v-if="showRefreshButton" #suffix>- <NButton text @click="refresh">- <template #icon>- <RefreshCcwIcon class="w-4 h-auto" />- </template>- {{ $t("common.refresh") }}- </NButton>- </template>- </NTabs>-</template>--<script lang="ts" setup>-import { uniqueId } from "lodash-es";-import { RefreshCcwIcon } from "lucide-vue-next";-import { NButton, NTabPane, NTabs } from "naive-ui";-import { computed, reactive, ref } from "vue";-import { Engine } from "@/types/proto-es/v1/common_pb";-import type { Database } from "@/types/proto-es/v1/database_service_pb";-import {- type TaskRun,- TaskRun_Status,-} from "@/types/proto-es/v1/rollout_service_pb";-import { TaskRunLogViewer } from "./TaskRunLogViewer";-import TaskRunSession from "./TaskRunSession";--const TASK_RUN_SESSION_SUPPORTED_ENGINES = [Engine.POSTGRES];--interface LocalState {- currentTab: "LOG" | "SESSION";-}--const props = defineProps<{- taskRun: TaskRun;- database?: Database;-}>();--const state = reactive<LocalState>({- currentTab: "LOG",-});-// Mainly using to force re-render of TaskRunSession component which will re-fetch the session data.-const componentId = ref<string>(uniqueId());--const refresh = () => {- componentId.value = uniqueId();-};--const showTaskRunSessionTab = computed(- () =>- props.database?.instanceResource &&- TASK_RUN_SESSION_SUPPORTED_ENGINES.includes(- props.database.instanceResource.engine- )-);--const showRefreshButton = computed(- () => props.taskRun.status === TaskRun_Status.RUNNING-);-</script>diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/SectionContent.vue b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/SectionContent.vuedeleted file mode 100644index f24e59e97e..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/SectionContent.vue+++ /dev/null@@ -1,56 +0,0 @@-<template>- <NVirtualList- :items="section.items"- :item-size="ITEM_HEIGHT"- item-resizable- :style="{ maxHeight: `${MAX_VISIBLE_ITEMS * ITEM_HEIGHT}px` }"- class="bg-gray-50 border-t border-gray-100"- >- <template #default="{ item, index }">- <div- class="flex items-start gap-x-2 py-0.5 hover:bg-gray-100"- :class="[indent ? 'px-6' : 'px-3', { 'border-t border-gray-100': index > 0 }]"- >- <span class="text-gray-300 w-6 text-right shrink-0 tabular-nums">- {{ index + 1 }}- </span>- <span class="text-gray-400 shrink-0 tabular-nums">- {{ item.time }}- </span>- <span- v-if="item.relativeTime"- class="text-gray-300 shrink-0 tabular-nums"- >- {{ item.relativeTime }}- </span>- <span :class="item.levelClass" class="shrink-0">- {{ item.levelIndicator }}- </span>- <span :class="item.detailClass" class="break-all">- {{ item.detail }}- </span>- <span class="shrink-0 ml-auto flex items-center gap-x-2">- <span v-if="item.duration" class="text-blue-500 tabular-nums">- {{ item.duration }}- </span>- <span v-if="item.affectedRows !== undefined" class="text-gray-400">- {{ item.affectedRows }} rows- </span>- </span>- </div>- </template>- </NVirtualList>-</template>--<script lang="ts" setup>-import { NVirtualList } from "naive-ui";-import type { Section } from "./types";--const ITEM_HEIGHT = 20;-const MAX_VISIBLE_ITEMS = 10;--defineProps<{- section: Section;- indent?: boolean;-}>();-</script>diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/SectionHeader.vue b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/SectionHeader.vuedeleted file mode 100644index 436d11c418..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/SectionHeader.vue+++ /dev/null@@ -1,40 +0,0 @@-<template>- <div- class="flex items-center gap-x-2 py-1.5 bg-white hover:bg-gray-50 cursor-pointer select-none"- :class="indent ? 'px-6' : 'px-3'"- @click="$emit('toggle')"- >- <component- :is="isExpanded ? ChevronDownIcon : ChevronRightIcon"- class="w-3.5 h-3.5 text-gray-400 shrink-0"- />- <component- :is="section.statusIcon"- class="w-3.5 h-3.5 shrink-0"- :class="[section.statusClass, { 'animate-spin': section.status === 'running' }]"- />- <span class="text-gray-700">{{ section.label }}</span>- <span v-if="section.entryCount > 1" class="text-gray-400">- ({{ section.entryCount }})- </span>- <span class="flex-1" />- <span v-if="section.duration" class="text-gray-500 tabular-nums">- {{ section.duration }}- </span>- </div>-</template>--<script lang="ts" setup>-import { ChevronDownIcon, ChevronRightIcon } from "lucide-vue-next";-import type { Section } from "./types";--defineProps<{- section: Section;- isExpanded: boolean;- indent?: boolean;-}>();--defineEmits<{- toggle: [];-}>();-</script>diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/TaskRunLogViewer.vue b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/TaskRunLogViewer.vuedeleted file mode 100644index f91cd1e953..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/TaskRunLogViewer.vue+++ /dev/null@@ -1,273 +0,0 @@-<template>- <div- v-if="sections.length > 0"- class="w-full font-mono text-xs bg-gray-50 border border-gray-200 overflow-hidden rounded"- >- <!-- Toolbar with summary stats and expand/collapse buttons -->- <div- class="flex items-center justify-between px-2 py-1 bg-gray-100 border-b border-gray-200"- >- <!-- Left: Summary stats -->- <div class="flex items-center gap-x-2 text-gray-500">- <ListIcon class="w-3.5 h-3.5" />- <span>- {{- $t("task-run.log-viewer.summary", {- sections: totalSections,- entries: totalEntries,- })- }}- </span>- <span v-if="totalDuration" class="text-blue-500 tabular-nums">- {{ totalDuration }}- </span>- </div>-- <!-- Right: Expand/Collapse toggle button -->- <button- class="flex items-center gap-x-1 px-1.5 py-0.5 text-gray-600 hover:text-gray-900 hover:bg-gray-200 rounded transition-colors"- @click="toggleExpandAll"- >- <component- :is="areAllExpanded ? ChevronsDownUpIcon : ChevronsUpDownIcon"- class="w-3.5 h-3.5"- />- <span>{{- areAllExpanded- ? $t("task-run.log-viewer.collapse-all")- : $t("task-run.log-viewer.expand-all")- }}</span>- </button>- </div>-- <!-- Multi-replica view: show replica groups when server restarts detected -->- <template v-if="hasMultipleReplicas">- <!-- Server restart notice -->- <div- class="flex items-center gap-x-2 px-3 py-2 bg-amber-50 border-b border-amber-200 text-amber-800"- >- <AlertTriangleIcon class="w-4 h-4 shrink-0" />- <span>{{ $t("task-run.log-viewer.multiple-replicas-notice") }}</span>- </div>-- <!-- Replica groups -->- <div- v-for="(replicaGroup, replicaIdx) in replicaGroups"- :key="replicaGroup.replicaId"- class="border-b border-gray-300 last:border-b-0"- >- <!-- Replica Header -->- <div- class="flex items-center gap-x-2 px-3 py-1.5 bg-gray-100 hover:bg-gray-200 cursor-pointer select-none"- @click="toggleReplica(replicaGroup.replicaId)"- >- <component- :is="isReplicaExpanded(replicaGroup.replicaId) ? ChevronDownIcon : ChevronRightIcon"- class="w-3.5 h-3.5 text-gray-500 shrink-0"- />- <ServerIcon class="w-3.5 h-3.5 text-gray-500 shrink-0" />- <span class="text-gray-700 font-medium">- {{ $t("task-run.log-viewer.replica-n", { n: replicaIdx + 1 }) }}- </span>- <span class="text-gray-400 text-[10px] font-normal">- {{ replicaGroup.replicaId.substring(0, 8) }}- </span>- </div>-- <!-- Sections within replica group -->- <div v-if="isReplicaExpanded(replicaGroup.replicaId)">- <!-- Orphan sections (before any release file marker) -->- <div- v-for="section in replicaGroup.sections"- :key="section.id"- class="border-b border-gray-200 last:border-b-0"- >- <SectionHeader- :section="section"- :is-expanded="isSectionExpanded(section.id)"- :indent="true"- @toggle="toggleSection(section.id)"- />- <SectionContent- v-if="isSectionExpanded(section.id)"- :section="section"- :indent="true"- />- </div>-- <!-- Release file groups -->- <div- v-for="(fileGroup, fileIdx) in replicaGroup.releaseFileGroups"- :key="`${replicaGroup.replicaId}-file-${fileIdx}`"- class="border-b border-gray-200 last:border-b-0"- >- <!-- Release file header -->- <div- class="flex items-center gap-x-2 px-3 py-1.5 bg-blue-50 hover:bg-blue-100 cursor-pointer select-none ml-4"- @click="toggleReleaseFile(`${replicaGroup.replicaId}-file-${fileIdx}`)"- >- <component- :is="isReleaseFileExpanded(`${replicaGroup.replicaId}-file-${fileIdx}`) ? ChevronDownIcon : ChevronRightIcon"- class="w-3.5 h-3.5 text-blue-500 shrink-0"- />- <FileCodeIcon class="w-3.5 h-3.5 text-blue-500 shrink-0" />- <span class="text-blue-700 font-medium">- {{ getReleaseFileLabel(fileGroup.version, fileGroup.filePath) }}- </span>- </div>-- <!-- Sections within release file group -->- <div v-if="isReleaseFileExpanded(`${replicaGroup.replicaId}-file-${fileIdx}`)" class="ml-4">- <div- v-for="section in fileGroup.sections"- :key="section.id"- class="border-b border-gray-200 last:border-b-0"- >- <SectionHeader- :section="section"- :is-expanded="isSectionExpanded(section.id)"- :indent="true"- @toggle="toggleSection(section.id)"- />- <SectionContent- v-if="isSectionExpanded(section.id)"- :section="section"- :indent="true"- />- </div>- </div>- </div>- </div>- </div>- </template>-- <!-- Single-replica view with release files -->- <template v-else-if="hasReleaseFiles">- <div- v-for="(fileGroup, fileIdx) in releaseFileGroups"- :key="`file-${fileIdx}`"- class="border-b border-gray-200 last:border-b-0"- >- <!-- Release file header -->- <div- class="flex items-center gap-x-2 px-3 py-1.5 bg-blue-50 hover:bg-blue-100 cursor-pointer select-none"- @click="toggleReleaseFile(`file-${fileIdx}`)"- >- <component- :is="isReleaseFileExpanded(`file-${fileIdx}`) ? ChevronDownIcon : ChevronRightIcon"- class="w-3.5 h-3.5 text-blue-500 shrink-0"- />- <FileCodeIcon class="w-3.5 h-3.5 text-blue-500 shrink-0" />- <span class="text-blue-700 font-medium">- {{ getReleaseFileLabel(fileGroup.version, fileGroup.filePath) }}- </span>- </div>-- <!-- Sections within release file group -->- <div v-if="isReleaseFileExpanded(`file-${fileIdx}`)">- <div- v-for="section in fileGroup.sections"- :key="section.id"- class="border-b border-gray-200 last:border-b-0"- >- <SectionHeader- :section="section"- :is-expanded="isSectionExpanded(section.id)"- :indent="true"- @toggle="toggleSection(section.id)"- />- <SectionContent- v-if="isSectionExpanded(section.id)"- :section="section"- :indent="true"- />- </div>- </div>- </div>- </template>-- <!-- Single-replica view: standard flat sections (no release files) -->- <template v-else>- <div- v-for="section in sections"- :key="section.id"- class="border-b border-gray-200 last:border-b-0"- >- <SectionHeader- :section="section"- :is-expanded="isSectionExpanded(section.id)"- @toggle="toggleSection(section.id)"- />- <SectionContent- v-if="isSectionExpanded(section.id)"- :section="section"- />- </div>- </template>- </div>-</template>--<script lang="ts" setup>-import {- AlertTriangleIcon,- ChevronDownIcon,- ChevronRightIcon,- ChevronsDownUpIcon,- ChevronsUpDownIcon,- FileCodeIcon,- ListIcon,- ServerIcon,-} from "lucide-vue-next";-import SectionContent from "./SectionContent.vue";-import SectionHeader from "./SectionHeader.vue";-import { useTaskRunLogData } from "./useTaskRunLogData";-import { useTaskRunLogSections } from "./useTaskRunLogSections";--const props = defineProps<{- taskRunName: string;-}>();--// Fetch task run log entries and sheets internally-const { entries, sheet, sheetsMap } = useTaskRunLogData(- () => props.taskRunName-);--const {- sections,- hasMultipleReplicas,- hasReleaseFiles,- releaseFileGroups,- replicaGroups,- toggleSection,- toggleReplica,- toggleReleaseFile,- isSectionExpanded,- isReplicaExpanded,- isReleaseFileExpanded,- expandAll,- collapseAll,- areAllExpanded,- totalSections,- totalEntries,- totalDuration,-} = useTaskRunLogSections(- () => entries.value,- () => sheet.value,- () => sheetsMap.value-);--const toggleExpandAll = () => {- if (areAllExpanded.value) {- collapseAll();- } else {- expandAll();- }-};--const getReleaseFileLabel = (version: string, filePath: string): string => {- if (filePath) {- return `${version}: ${filePath}`;- }- return version;-};-</script>diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/index.ts b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/index.tsdeleted file mode 100644index 144e97948e..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export { default as TaskRunLogViewer } from "./TaskRunLogViewer.vue";-export * from "./types";diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/types.ts b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/types.tsdeleted file mode 100644index 6a79892c22..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/types.ts+++ /dev/null@@ -1,46 +0,0 @@-import type { Component } from "vue";-import type { TaskRunLogEntry_Type } from "@/types/proto-es/v1/rollout_service_pb";--export type SectionStatus = "success" | "error" | "running" | "pending";--export interface DisplayItem {- key: string;- time: string;- relativeTime: string;- levelIndicator: string;- levelClass: string;- detail: string;- detailClass: string;- affectedRows?: number;- duration?: string;-}--export interface Section {- id: string;- type: TaskRunLogEntry_Type;- label: string;- status: SectionStatus;- statusIcon: Component;- statusClass: string;- duration: string;- entryCount: number;- items: DisplayItem[];-}--export interface EntryGroup {- type: TaskRunLogEntry_Type;- entries: import("@/types/proto-es/v1/rollout_service_pb").TaskRunLogEntry[];-}--export interface ReleaseFileGroup {- version: string;- filePath: string;- sections: Section[];-}--export interface ReplicaGroup {- replicaId: string;- releaseFileGroups: ReleaseFileGroup[];- // Sections not associated with any release file (e.g., logs before file execution)- sections: Section[];-}diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/useTaskRunLogData.ts b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/useTaskRunLogData.tsdeleted file mode 100644index 2b10ccd3c7..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/useTaskRunLogData.ts+++ /dev/null@@ -1,167 +0,0 @@-import { create } from "@bufbuild/protobuf";-import { computedAsync } from "@vueuse/core";-import type { MaybeRefOrGetter, Ref } from "vue";-import { computed, ref, toValue, watch } from "vue";-import {- rolloutServiceClientConnect,- sheetServiceClientConnect,-} from "@/connect";-import { useReleaseStore, useRolloutByName } from "@/store";-import {- GetTaskRunLogRequestSchema,- type TaskRunLogEntry,-} from "@/types/proto-es/v1/rollout_service_pb";-import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";-import {- extractRolloutNameFromTaskRunName,- extractTaskNameFromTaskRunName,- isReleaseBasedTask,- releaseNameOfTaskV1,- sheetNameOfTaskV1,-} from "@/utils";--export interface UseTaskRunLogDataReturn {- entries: Ref<TaskRunLogEntry[]>;- sheet: Ref<Sheet | undefined>;- sheetsMap: Ref<Map<string, Sheet>>;-}--/**- * Composable that fetches task run log entries and associated sheets.- * Handles both regular tasks (single sheet) and release tasks (multiple sheets by version).- */-export const useTaskRunLogData = (- taskRunName: MaybeRefOrGetter<string | undefined>-): UseTaskRunLogDataReturn => {- const releaseStore = useReleaseStore();-- // Sheet for non-release tasks- const sheet = ref<Sheet | undefined>(undefined);- // Map of version -> Sheet for release tasks- const sheetsMap = ref<Map<string, Sheet>>(new Map());-- // Fetch task run log entries- const taskRunLog = computedAsync(async () => {- const name = toValue(taskRunName);- if (!name) return undefined;- const request = create(GetTaskRunLogRequestSchema, {- parent: name,- });- return await rolloutServiceClientConnect.getTaskRunLog(request);- }, undefined);-- const entries = computed(() => taskRunLog.value?.entries ?? []);-- // Extract rollout name from task run name to get the task- const rolloutName = computed(() => {- const name = toValue(taskRunName);- if (!name) return "";- return extractRolloutNameFromTaskRunName(name);- });-- const { rollout } = useRolloutByName(rolloutName);-- // Find the task from the rollout- const task = computed(() => {- const name = toValue(taskRunName);- if (!name || !rollout.value) return undefined;-- const taskName = extractTaskNameFromTaskRunName(name);- if (!taskName) return undefined;-- for (const stage of rollout.value.stages) {- const foundTask = stage.tasks.find((t) => t.name === taskName);- if (foundTask) return foundTask;- }- return undefined;- });-- // Track fetch version to handle race conditions- let fetchVersion = 0;-- const fetchReleaseSheets = async (- releaseName: string,- version: number- ): Promise<void> => {- const release = await releaseStore.fetchReleaseByName(releaseName, true);- if (version !== fetchVersion) return;-- const results = await Promise.all(- release.files- .filter((f) => f.sheet && f.version)- .map(async (file) => {- try {- const s = await sheetServiceClientConnect.getSheet({- name: file.sheet,- raw: true,- });- return { version: file.version, sheet: s };- } catch {- return null;- }- })- );- if (version !== fetchVersion) return;-- const newMap = new Map<string, Sheet>();- for (const r of results) {- if (r?.sheet) newMap.set(r.version, r.sheet);- }- sheetsMap.value = newMap;- };-- const fetchSingleSheet = async (- sheetName: string,- version: number- ): Promise<void> => {- try {- const fetched = await sheetServiceClientConnect.getSheet({- name: sheetName,- raw: true,- });- if (version !== fetchVersion) return;- sheet.value = fetched;- } catch {- if (version === fetchVersion) {- sheet.value = undefined;- }- }- };-- // Fetch sheet(s) based on task type- watch(- task,- async (currentTask) => {- const currentVersion = ++fetchVersion;-- if (!currentTask) {- sheet.value = undefined;- sheetsMap.value = new Map();- return;- }-- try {- if (isReleaseBasedTask(currentTask)) {- const releaseName = releaseNameOfTaskV1(currentTask);- if (releaseName) {- await fetchReleaseSheets(releaseName, currentVersion);- }- } else {- const sheetName = sheetNameOfTaskV1(currentTask);- if (sheetName) {- await fetchSingleSheet(sheetName, currentVersion);- }- }- } catch {- // Ignore fetch errors- }- },- { immediate: true }- );-- return {- entries,- sheet,- sheetsMap,- };-};diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/useTaskRunLogSections.ts b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/useTaskRunLogSections.tsdeleted file mode 100644index b73e75198d..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/useTaskRunLogSections.ts+++ /dev/null@@ -1,844 +0,0 @@-import {- CheckCircle2Icon,- CircleIcon,- LoaderCircleIcon,- XCircleIcon,-} from "lucide-vue-next";-import type { Component, ComputedRef, MaybeRefOrGetter, Ref } from "vue";-import { computed, ref, toValue, watch } from "vue";-import { useI18n } from "vue-i18n";-import type { TaskRunLogEntry } from "@/types/proto-es/v1/rollout_service_pb";-import {- TaskRunLogEntry_TransactionControl_Type,- TaskRunLogEntry_Type,-} from "@/types/proto-es/v1/rollout_service_pb";-import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";-import { addToSet, deleteFromSet } from "../../shared/reactivity";-import type {- DisplayItem,- ReleaseFileGroup,- ReplicaGroup,- Section,- SectionStatus,-} from "./types";-import {- formatDuration,- formatRelativeTime,- formatTime,- getTimestampMs,- getUniqueReplicaIds,- groupEntriesByReleaseFile,- groupEntriesByReplica,- groupEntriesByType,- hasError,- hasReleaseFileMarkers,- isComplete,-} from "./utils";--const STATUS_CONFIG: Record<SectionStatus, { icon: Component; class: string }> =- {- success: { icon: CheckCircle2Icon, class: "text-green-600" },- error: { icon: XCircleIcon, class: "text-red-600" },- running: { icon: LoaderCircleIcon, class: "text-blue-600" },- pending: { icon: CircleIcon, class: "text-gray-400" },- };--export interface UseTaskRunLogSectionsReturn {- sections: ComputedRef<Section[]>;- hasMultipleReplicas: ComputedRef<boolean>;- hasReleaseFiles: ComputedRef<boolean>;- releaseFileGroups: ComputedRef<ReleaseFileGroup[]>;- replicaGroups: ComputedRef<ReplicaGroup[]>;- expandedSections: Ref<Set<string>>;- expandedReplicas: Ref<Set<string>>;- expandedReleaseFiles: Ref<Set<string>>;- toggleSection: (sectionId: string) => void;- toggleReplica: (replicaId: string) => void;- toggleReleaseFile: (fileId: string) => void;- isSectionExpanded: (sectionId: string) => boolean;- isReplicaExpanded: (replicaId: string) => boolean;- isReleaseFileExpanded: (fileId: string) => boolean;- expandAll: () => void;- collapseAll: () => void;- areAllExpanded: ComputedRef<boolean>;- totalSections: ComputedRef<number>;- totalEntries: ComputedRef<number>;- totalDuration: ComputedRef<string>;-}--export const useTaskRunLogSections = (- entries: MaybeRefOrGetter<TaskRunLogEntry[]>,- sheet: MaybeRefOrGetter<Sheet | undefined>,- sheetsMap: MaybeRefOrGetter<Map<string, Sheet> | undefined> = () => undefined-): UseTaskRunLogSectionsReturn => {- const { t } = useI18n();-- const expandedSections = ref<Set<string>>(new Set());- const userCollapsedSections = ref<Set<string>>(new Set());- const expandedReplicas = ref<Set<string>>(new Set());- const userCollapsedReplicas = ref<Set<string>>(new Set());- const expandedReleaseFiles = ref<Set<string>>(new Set());- const userCollapsedReleaseFiles = ref<Set<string>>(new Set());-- const getSectionLabel = (type: TaskRunLogEntry_Type): string => {- const labelMap: Partial<Record<TaskRunLogEntry_Type, string>> = {- [TaskRunLogEntry_Type.SCHEMA_DUMP]: t("task-run.log-type.schema-dump"),- [TaskRunLogEntry_Type.COMMAND_EXECUTE]: t(- "task-run.log-type.command-execute"- ),- [TaskRunLogEntry_Type.DATABASE_SYNC]: t(- "task-run.log-type.database-sync"- ),- [TaskRunLogEntry_Type.TRANSACTION_CONTROL]: t(- "task-run.log-type.transaction"- ),- [TaskRunLogEntry_Type.PRIOR_BACKUP]: t("task-run.log-type.prior-backup"),- [TaskRunLogEntry_Type.RETRY_INFO]: t("task-run.log-type.retry"),- [TaskRunLogEntry_Type.COMPUTE_DIFF]: t("task-run.log-type.compute-diff"),- [TaskRunLogEntry_Type.RELEASE_FILE_EXECUTE]: t(- "task-run.log-type.release-file-execute"- ),- };- return labelMap[type] ?? "Unknown";- };-- // Extract statement from sheet content using byte range- const extractStatementFromRange = (- range: { start: number; end: number },- sheetContent: Uint8Array | undefined,- sheetsMapValue: Map<string, Sheet> | undefined,- fileVersion?: string- ): string | undefined => {- // For release tasks, look up sheet by version from sheetsMap- // For non-release tasks, use the single sheet- let content = sheetContent;- if (fileVersion && sheetsMapValue) {- const fileSheet = sheetsMapValue.get(fileVersion);- if (fileSheet?.content) {- content = fileSheet.content;- }- }- if (!content) return undefined;-- const subarray = content.subarray(range.start, range.end);- return new TextDecoder().decode(subarray);- };-- const getCommandExecuteDetail = (- entry: TaskRunLogEntry,- sheetContent: Uint8Array | undefined,- sheetsMapValue: Map<string, Sheet> | undefined,- fileVersion?: string- ): string => {- const cmd = entry.commandExecute;- if (!cmd) return "";- if (cmd.response?.error) return cmd.response.error;-- const statement =- cmd.statement ||- (cmd.range- ? extractStatementFromRange(- cmd.range,- sheetContent,- sheetsMapValue,- fileVersion- )- : undefined);- if (statement) {- const stmt = statement.trim().replace(/\s+/g, " ");- return stmt.length > 80 ? stmt.substring(0, 80) + "..." : stmt;- }- return "-";- };-- const getTransactionControlDetail = (entry: TaskRunLogEntry): string => {- const txn = entry.transactionControl;- if (!txn) return "";- const typeLabels: Record<number, string> = {- [TaskRunLogEntry_TransactionControl_Type.BEGIN]: "BEGIN",- [TaskRunLogEntry_TransactionControl_Type.COMMIT]: "COMMIT",- [TaskRunLogEntry_TransactionControl_Type.ROLLBACK]: "ROLLBACK",- };- const typeStr = typeLabels[txn.type] ?? "";- return txn.error ? `${typeStr} error: ${txn.error}` : typeStr;- };-- const getTimedEntryDetail = (- data:- | { error?: string; startTime?: unknown; endTime?: unknown }- | undefined,- runningLabel: string- ): string => {- if (!data) return "";- if (data.error) return data.error;- if (data.startTime && data.endTime) return "completed";- return runningLabel;- };-- const getPriorBackupDetail = (entry: TaskRunLogEntry): string => {- const backup = entry.priorBackup;- if (!backup) return "";- if (backup.error) return backup.error;- const items = backup.priorBackupDetail?.items;- if (items?.length) {- return t("task-run.log-detail.backup-completed", {- count: items.length,- });- }- if (backup.startTime && backup.endTime) return "completed";- return t("task-run.log-detail.backing-up");- };-- const getRetryInfoDetail = (entry: TaskRunLogEntry): string => {- const retry = entry.retryInfo;- if (!retry) return "";- const attempt = t("task-run.log-detail.retry-attempt", {- current: retry.retryCount,- max: retry.maximumRetries,- });- return retry.error ? `${attempt} - ${retry.error}` : attempt;- };-- const getReleaseFileExecuteDetail = (entry: TaskRunLogEntry): string => {- const rfe = entry.releaseFileExecute;- if (!rfe) return "";- return rfe.filePath ? `${rfe.version}: ${rfe.filePath}` : rfe.version;- };-- const getEntryDetail = (- entry: TaskRunLogEntry,- sheetContent: Uint8Array | undefined,- sheetsMapValue: Map<string, Sheet> | undefined,- fileVersion?: string- ): string => {- switch (entry.type) {- case TaskRunLogEntry_Type.COMMAND_EXECUTE:- return getCommandExecuteDetail(- entry,- sheetContent,- sheetsMapValue,- fileVersion- );- case TaskRunLogEntry_Type.TRANSACTION_CONTROL:- return getTransactionControlDetail(entry);- case TaskRunLogEntry_Type.SCHEMA_DUMP:- return getTimedEntryDetail(- entry.schemaDump,- t("task-run.log-detail.dumping")- );- case TaskRunLogEntry_Type.DATABASE_SYNC:- return getTimedEntryDetail(- entry.databaseSync,- t("task-run.log-detail.syncing")- );- case TaskRunLogEntry_Type.PRIOR_BACKUP:- return getPriorBackupDetail(entry);- case TaskRunLogEntry_Type.RETRY_INFO:- return getRetryInfoDetail(entry);- case TaskRunLogEntry_Type.COMPUTE_DIFF:- return getTimedEntryDetail(- entry.computeDiff,- t("task-run.log-detail.computing")- );- case TaskRunLogEntry_Type.RELEASE_FILE_EXECUTE:- return getReleaseFileExecuteDetail(entry);- default:- return "";- }- };-- const getCommandDuration = (entry: TaskRunLogEntry): string | undefined => {- if (entry.type !== TaskRunLogEntry_Type.COMMAND_EXECUTE) return undefined;- const cmd = entry.commandExecute;- if (!cmd?.logTime || !cmd.response?.logTime) return undefined;- const startMs = getTimestampMs(cmd.logTime);- const endMs = getTimestampMs(cmd.response.logTime);- if (startMs <= 0 || endMs <= 0) return undefined;- const durationMs = endMs - startMs;- return formatDuration(durationMs);- };-- const buildDisplayItems = (- groupEntries: TaskRunLogEntry[],- groupIdx: number,- startTime: number,- sheetContent: Uint8Array | undefined,- sheetsMapValue: Map<string, Sheet> | undefined,- fileVersion?: string- ): DisplayItem[] => {- return groupEntries.map((entry, idx) => {- const entryTime = getTimestampMs(entry.logTime);- const relativeMs = startTime > 0 ? entryTime - startTime : 0;- const entryHasError = hasError(entry);-- return {- key: `${groupIdx}-${idx}`,- time: formatTime(entry.logTime),- relativeTime: relativeMs > 0 ? formatRelativeTime(relativeMs) : "",- levelIndicator: entryHasError ? "\u2717" : "\u2713",- levelClass: entryHasError ? "text-red-600" : "text-green-600",- detail: getEntryDetail(- entry,- sheetContent,- sheetsMapValue,- fileVersion- ),- detailClass: entryHasError ? "text-red-700" : "text-gray-600",- affectedRows:- entry.type === TaskRunLogEntry_Type.COMMAND_EXECUTE- ? Number(entry.commandExecute?.response?.affectedRows ?? 0) ||- undefined- : undefined,- duration: getCommandDuration(entry),- };- });- };-- const calculateSectionStatus = (- groupEntries: TaskRunLogEntry[]- ): SectionStatus => {- const hasAnyError = groupEntries.some(hasError);- const allComplete = groupEntries.every(isComplete);-- if (hasAnyError) return "error";- if (allComplete) return "success";- return "running";- };-- // Get the actual start and end times for an entry based on its type- const getEntryTimeRange = (- entry: TaskRunLogEntry- ): { start: number; end: number } => {- switch (entry.type) {- case TaskRunLogEntry_Type.COMMAND_EXECUTE: {- const cmd = entry.commandExecute;- const start = getTimestampMs(cmd?.logTime);- const end = getTimestampMs(cmd?.response?.logTime);- return { start: start || 0, end: end || start || 0 };- }- case TaskRunLogEntry_Type.SCHEMA_DUMP: {- const dump = entry.schemaDump;- return {- start: getTimestampMs(dump?.startTime),- end: getTimestampMs(dump?.endTime),- };- }- case TaskRunLogEntry_Type.DATABASE_SYNC: {- const sync = entry.databaseSync;- return {- start: getTimestampMs(sync?.startTime),- end: getTimestampMs(sync?.endTime),- };- }- case TaskRunLogEntry_Type.PRIOR_BACKUP: {- const backup = entry.priorBackup;- return {- start: getTimestampMs(backup?.startTime),- end: getTimestampMs(backup?.endTime),- };- }- case TaskRunLogEntry_Type.COMPUTE_DIFF: {- const diff = entry.computeDiff;- return {- start: getTimestampMs(diff?.startTime),- end: getTimestampMs(diff?.endTime),- };- }- default: {- const time = getTimestampMs(entry.logTime);- return { start: time, end: time };- }- }- };-- const buildSectionsFromEntries = (- entriesList: TaskRunLogEntry[],- sheetContent: Uint8Array | undefined,- sheetsMapValue: Map<string, Sheet> | undefined,- idPrefix = "",- forceError = false,- fileVersion?: string- ): Section[] => {- if (!entriesList.length) return [];-- const groups = groupEntriesByType(entriesList);-- return groups.map((group, groupIdx) => {- const { type, entries: groupEntries } = group;-- // For interrupted replicas, treat "running" as "error"- let status = calculateSectionStatus(groupEntries);- if (forceError && status === "running") {- status = "error";- }-- // Calculate duration using actual operation start/end times- const timeRanges = groupEntries.map(getEntryTimeRange);- const startTimes = timeRanges.map((r) => r.start).filter((t) => t > 0);- const endTimes = timeRanges.map((r) => r.end).filter((t) => t > 0);- const startTime = startTimes.length ? Math.min(...startTimes) : 0;- const endTime = endTimes.length ? Math.max(...endTimes) : 0;- const durationMs = endTime - startTime;-- const items = buildDisplayItems(- groupEntries,- groupIdx,- startTime,- sheetContent,- sheetsMapValue,- fileVersion- );- const statusCfg = STATUS_CONFIG[status];-- return {- id: idPrefix- ? `${idPrefix}-section-${groupIdx}`- : `section-${groupIdx}`,- type,- label: getSectionLabel(type),- status,- statusIcon: statusCfg.icon,- statusClass: statusCfg.class,- duration:- startTime > 0 && endTime > 0 ? formatDuration(durationMs) : "",- entryCount: groupEntries.length,- items,- };- });- };-- const sections = computed((): Section[] => {- const entriesValue = toValue(entries);- const sheetContent = toValue(sheet)?.content;- const sheetsMapValue = toValue(sheetsMap);- return buildSectionsFromEntries(entriesValue, sheetContent, sheetsMapValue);- });-- const hasMultipleReplicas = computed((): boolean => {- const entriesValue = toValue(entries);- const replicaIds = getUniqueReplicaIds(entriesValue);- return replicaIds.length > 1;- });-- const hasReleaseFiles = computed((): boolean => {- const entriesValue = toValue(entries);- return hasReleaseFileMarkers(entriesValue);- });-- // Build release file groups from entries- const buildReleaseFileGroupsFromEntries = (- entriesList: TaskRunLogEntry[],- sheetContent: Uint8Array | undefined,- sheetsMapValue: Map<string, Sheet> | undefined,- idPrefix = "",- forceError = false- ): ReleaseFileGroup[] => {- const fileGroups = groupEntriesByReleaseFile(entriesList);-- return fileGroups- .filter((group) => group.file !== null) // Only include groups with file markers- .map((group, idx) => {- const fileId = idPrefix ? `${idPrefix}-file-${idx}` : `file-${idx}`;- const version = group.file!.version;- return {- version,- filePath: group.file!.filePath,- // Pass version so COMMAND_EXECUTE entries can look up the correct sheet- sections: buildSectionsFromEntries(- group.entries,- sheetContent,- sheetsMapValue,- fileId,- forceError,- version- ),- };- });- };-- // Get orphan sections (entries before any release file marker)- const getOrphanSections = (- entriesList: TaskRunLogEntry[],- sheetContent: Uint8Array | undefined,- sheetsMapValue: Map<string, Sheet> | undefined,- idPrefix = "",- forceError = false- ): Section[] => {- const fileGroups = groupEntriesByReleaseFile(entriesList);- const orphanGroup = fileGroups.find((group) => group.file === null);- if (!orphanGroup || orphanGroup.entries.length === 0) {- return [];- }- return buildSectionsFromEntries(- orphanGroup.entries,- sheetContent,- sheetsMapValue,- idPrefix ? `${idPrefix}-orphan` : "orphan",- forceError- );- };-- // Release file groups for single-replica view- const releaseFileGroups = computed((): ReleaseFileGroup[] => {- const entriesValue = toValue(entries);- if (!hasReleaseFileMarkers(entriesValue)) return [];- const sheetContent = toValue(sheet)?.content;- const sheetsMapValue = toValue(sheetsMap);- return buildReleaseFileGroupsFromEntries(- entriesValue,- sheetContent,- sheetsMapValue- );- });-- const replicaGroups = computed((): ReplicaGroup[] => {- const entriesValue = toValue(entries);- if (!entriesValue.length) return [];-- const replicaIds = getUniqueReplicaIds(entriesValue);- if (replicaIds.length <= 1) return [];-- const sheetContent = toValue(sheet)?.content;- const sheetsMapValue = toValue(sheetsMap);- const entriesByReplica = groupEntriesByReplica(entriesValue);-- return replicaIds.map((replicaId, idx) => {- const replicaEntries = entriesByReplica.get(replicaId) || [];- const isLatestReplica = idx === replicaIds.length - 1;- const forceError = !isLatestReplica;-- // Check if this replica has release file markers- const hasFiles = hasReleaseFileMarkers(replicaEntries);-- if (hasFiles) {- return {- replicaId,- releaseFileGroups: buildReleaseFileGroupsFromEntries(- replicaEntries,- sheetContent,- sheetsMapValue,- replicaId,- forceError- ),- sections: getOrphanSections(- replicaEntries,- sheetContent,- sheetsMapValue,- replicaId,- forceError- ),- };- }-- return {- replicaId,- releaseFileGroups: [],- sections: buildSectionsFromEntries(- replicaEntries,- sheetContent,- sheetsMapValue,- replicaId,- forceError- ),- };- });- });-- const toggleSection = (sectionId: string) => {- if (expandedSections.value.has(sectionId)) {- deleteFromSet(expandedSections, sectionId);- addToSet(userCollapsedSections, sectionId);- } else {- addToSet(expandedSections, sectionId);- deleteFromSet(userCollapsedSections, sectionId);- }- };-- const toggleReplica = (replicaId: string) => {- if (expandedReplicas.value.has(replicaId)) {- deleteFromSet(expandedReplicas, replicaId);- addToSet(userCollapsedReplicas, replicaId);- } else {- addToSet(expandedReplicas, replicaId);- deleteFromSet(userCollapsedReplicas, replicaId);- }- };-- const isSectionExpanded = (sectionId: string): boolean => {- return expandedSections.value.has(sectionId);- };-- const isReplicaExpanded = (replicaId: string): boolean => {- return expandedReplicas.value.has(replicaId);- };-- const toggleReleaseFile = (fileId: string) => {- if (expandedReleaseFiles.value.has(fileId)) {- deleteFromSet(expandedReleaseFiles, fileId);- addToSet(userCollapsedReleaseFiles, fileId);- } else {- addToSet(expandedReleaseFiles, fileId);- deleteFromSet(userCollapsedReleaseFiles, fileId);- }- };-- const isReleaseFileExpanded = (fileId: string): boolean => {- return expandedReleaseFiles.value.has(fileId);- };-- // All section/replica/file IDs as computeds to avoid nested function depth issues- const allSectionIds = computed((): string[] => {- if (hasMultipleReplicas.value) {- return replicaGroups.value.flatMap((group) => [- ...group.sections.map((s) => s.id),- ...group.releaseFileGroups.flatMap((fg) =>- fg.sections.map((s) => s.id)- ),- ]);- }- if (hasReleaseFiles.value) {- return releaseFileGroups.value.flatMap((fg) =>- fg.sections.map((s) => s.id)- );- }- return sections.value.map((section) => section.id);- });-- const allReplicaIds = computed((): string[] => {- return replicaGroups.value.map((group) => group.replicaId);- });-- const allReleaseFileIds = computed((): string[] => {- if (hasMultipleReplicas.value) {- return replicaGroups.value.flatMap((group) =>- group.releaseFileGroups.map(- (_, fileIdx) => `${group.replicaId}-file-${fileIdx}`- )- );- }- return releaseFileGroups.value.map((_, idx) => `file-${idx}`);- });-- const expandAll = () => {- for (const sectionId of allSectionIds.value) {- addToSet(expandedSections, sectionId);- deleteFromSet(userCollapsedSections, sectionId);- }- if (hasMultipleReplicas.value) {- for (const replicaId of allReplicaIds.value) {- addToSet(expandedReplicas, replicaId);- deleteFromSet(userCollapsedReplicas, replicaId);- }- }- for (const fileId of allReleaseFileIds.value) {- addToSet(expandedReleaseFiles, fileId);- deleteFromSet(userCollapsedReleaseFiles, fileId);- }- };-- const collapseAll = () => {- for (const sectionId of allSectionIds.value) {- deleteFromSet(expandedSections, sectionId);- addToSet(userCollapsedSections, sectionId);- }- if (hasMultipleReplicas.value) {- for (const replicaId of allReplicaIds.value) {- deleteFromSet(expandedReplicas, replicaId);- addToSet(userCollapsedReplicas, replicaId);- }- }- for (const fileId of allReleaseFileIds.value) {- deleteFromSet(expandedReleaseFiles, fileId);- addToSet(userCollapsedReleaseFiles, fileId);- }- };-- const areAllExpanded = computed((): boolean => {- if (allSectionIds.value.length === 0) return false;-- const allSectionsExpanded = allSectionIds.value.every((id) =>- expandedSections.value.has(id)- );- const allFilesExpanded =- allReleaseFileIds.value.length === 0 ||- allReleaseFileIds.value.every((id) => expandedReleaseFiles.value.has(id));-- if (hasMultipleReplicas.value) {- const allReplicasExpanded = allReplicaIds.value.every((id) =>- expandedReplicas.value.has(id)- );- return allSectionsExpanded && allReplicasExpanded && allFilesExpanded;- }-- return allSectionsExpanded && allFilesExpanded;- });-- const countSections = (secs: Section[]): number => secs.length;-- const countEntries = (secs: Section[]): number =>- secs.reduce((sum, s) => sum + s.entryCount, 0);-- const totalSections = computed((): number => {- if (hasMultipleReplicas.value) {- return replicaGroups.value.reduce(- (sum, group) =>- sum +- countSections(group.sections) +- group.releaseFileGroups.reduce(- (fSum, fg) => fSum + countSections(fg.sections),- 0- ),- 0- );- }- if (hasReleaseFiles.value) {- return releaseFileGroups.value.reduce(- (sum, fg) => sum + countSections(fg.sections),- 0- );- }- return sections.value.length;- });-- const totalEntries = computed((): number => {- if (hasMultipleReplicas.value) {- return replicaGroups.value.reduce(- (sum, group) =>- sum +- countEntries(group.sections) +- group.releaseFileGroups.reduce(- (fSum, fg) => fSum + countEntries(fg.sections),- 0- ),- 0- );- }- if (hasReleaseFiles.value) {- return releaseFileGroups.value.reduce(- (sum, fg) => sum + countEntries(fg.sections),- 0- );- }- return countEntries(sections.value);- });-- const totalDuration = computed((): string => {- const entriesValue = toValue(entries);- if (!entriesValue.length) return "";-- const timeRanges = entriesValue.map(getEntryTimeRange);- const startTimes = timeRanges.map((r) => r.start).filter((t) => t > 0);- const endTimes = timeRanges.map((r) => r.end).filter((t) => t > 0);-- if (!startTimes.length || !endTimes.length) return "";-- const startTime = Math.min(...startTimes);- const endTime = Math.max(...endTimes);- const durationMs = endTime - startTime;-- return formatDuration(durationMs);- });-- // Auto-expand error sections (respecting user's manual collapse)- watch(- sections,- (newSections) => {- for (const section of newSections) {- if (- section.status === "error" &&- !userCollapsedSections.value.has(section.id)- ) {- addToSet(expandedSections, section.id);- }- }- },- { immediate: true }- );-- // Auto-expand all replicas and error sections in replica groups- watch(- replicaGroups,- (newReplicaGroups) => {- for (const replicaGroup of newReplicaGroups) {- // Auto-expand all replica groups by default- if (!userCollapsedReplicas.value.has(replicaGroup.replicaId)) {- addToSet(expandedReplicas, replicaGroup.replicaId);- }- // Auto-expand error sections within replica groups (orphan sections)- for (const section of replicaGroup.sections) {- if (- section.status === "error" &&- !userCollapsedSections.value.has(section.id)- ) {- addToSet(expandedSections, section.id);- }- }- // Auto-expand release file groups and their error sections- replicaGroup.releaseFileGroups.forEach((fg, fileIdx) => {- const fileId = `${replicaGroup.replicaId}-file-${fileIdx}`;- // Auto-expand all release file groups by default- if (!userCollapsedReleaseFiles.value.has(fileId)) {- addToSet(expandedReleaseFiles, fileId);- }- // Auto-expand error sections within file groups- for (const section of fg.sections) {- if (- section.status === "error" &&- !userCollapsedSections.value.has(section.id)- ) {- addToSet(expandedSections, section.id);- }- }- });- }- },- { immediate: true }- );-- // Auto-expand release file groups (single-replica view)- watch(- releaseFileGroups,- (newReleaseFileGroups) => {- newReleaseFileGroups.forEach((fg, idx) => {- const fileId = `file-${idx}`;- // Auto-expand all release file groups by default- if (!userCollapsedReleaseFiles.value.has(fileId)) {- addToSet(expandedReleaseFiles, fileId);- }- // Auto-expand error sections within file groups- for (const section of fg.sections) {- if (- section.status === "error" &&- !userCollapsedSections.value.has(section.id)- ) {- addToSet(expandedSections, section.id);- }- }- });- },- { immediate: true }- );-- return {- sections,- hasMultipleReplicas,- hasReleaseFiles,- releaseFileGroups,- replicaGroups,- expandedSections,- expandedReplicas,- expandedReleaseFiles,- toggleSection,- toggleReplica,- toggleReleaseFile,- isSectionExpanded,- isReplicaExpanded,- isReleaseFileExpanded,- expandAll,- collapseAll,- areAllExpanded,- totalSections,- totalEntries,- totalDuration,- };-};diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/utils.ts b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/utils.tsdeleted file mode 100644index ee48d864ad..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunLogViewer/utils.ts+++ /dev/null@@ -1,206 +0,0 @@-import type { Timestamp as PbTimestamp } from "@bufbuild/protobuf/wkt";-import { getDateForPbTimestampProtoEs } from "@/types";-import type { TaskRunLogEntry } from "@/types/proto-es/v1/rollout_service_pb";-import { TaskRunLogEntry_Type } from "@/types/proto-es/v1/rollout_service_pb";-import type { EntryGroup } from "./types";--// Timestamp utilities-export const getTimestampMs = (ts: PbTimestamp | undefined): number => {- if (!ts) return 0;- return Number(ts.seconds) * 1000 + ts.nanos / 1000000;-};--export const formatTime = (ts: PbTimestamp | undefined): string => {- if (!ts) return "--:--:--.---";- const date = getDateForPbTimestampProtoEs(ts);- if (!date) return "--:--:--.---";- return (- [- date.getHours().toString().padStart(2, "0"),- date.getMinutes().toString().padStart(2, "0"),- date.getSeconds().toString().padStart(2, "0"),- ].join(":") +- "." +- date.getMilliseconds().toString().padStart(3, "0")- );-};--export const formatDuration = (ms: number): string => {- if (ms < 1) return "<1ms";- if (ms < 1000) return `${ms.toFixed(0)}ms`;- if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;- const mins = Math.floor(ms / 60000);- const secs = ((ms % 60000) / 1000).toFixed(0);- return `${mins}m ${secs}s`;-};--export const formatRelativeTime = (ms: number): string => {- if (ms < 1000) return `+${ms.toFixed(0)}ms`;- return `+${(ms / 1000).toFixed(2)}s`;-};--// Entry analysis-export const hasError = (entry: TaskRunLogEntry): boolean => {- switch (entry.type) {- case TaskRunLogEntry_Type.COMMAND_EXECUTE:- return !!entry.commandExecute?.response?.error;- case TaskRunLogEntry_Type.TRANSACTION_CONTROL:- return !!entry.transactionControl?.error;- case TaskRunLogEntry_Type.SCHEMA_DUMP:- return !!entry.schemaDump?.error;- case TaskRunLogEntry_Type.DATABASE_SYNC:- return !!entry.databaseSync?.error;- case TaskRunLogEntry_Type.PRIOR_BACKUP:- return !!entry.priorBackup?.error;- case TaskRunLogEntry_Type.COMPUTE_DIFF:- return !!entry.computeDiff?.error;- default:- return false;- }-};--export const isComplete = (entry: TaskRunLogEntry): boolean => {- switch (entry.type) {- case TaskRunLogEntry_Type.COMMAND_EXECUTE:- return !!entry.commandExecute?.response;- case TaskRunLogEntry_Type.SCHEMA_DUMP:- return !!(entry.schemaDump?.startTime && entry.schemaDump?.endTime);- case TaskRunLogEntry_Type.DATABASE_SYNC:- return !!(entry.databaseSync?.startTime && entry.databaseSync?.endTime);- case TaskRunLogEntry_Type.PRIOR_BACKUP:- return !!(entry.priorBackup?.startTime && entry.priorBackup?.endTime);- case TaskRunLogEntry_Type.COMPUTE_DIFF:- return !!(entry.computeDiff?.startTime && entry.computeDiff?.endTime);- case TaskRunLogEntry_Type.TRANSACTION_CONTROL:- case TaskRunLogEntry_Type.RETRY_INFO:- return true;- default:- return true;- }-};--// Group consecutive entries of the same type-export const groupEntriesByType = (- entries: TaskRunLogEntry[]-): EntryGroup[] => {- if (!entries.length) return [];-- // Sort entries by time first- const sortedEntries = [...entries].sort((a, b) => {- return getTimestampMs(a.logTime) - getTimestampMs(b.logTime);- });-- const groups: EntryGroup[] = [];- let currentGroup: EntryGroup | null = null;-- for (const entry of sortedEntries) {- if (currentGroup && currentGroup.type === entry.type) {- currentGroup.entries.push(entry);- } else {- currentGroup = { type: entry.type, entries: [entry] };- groups.push(currentGroup);- }- }-- return groups;-};--// Get unique replica IDs from entries, preserving order of first appearance-export const getUniqueReplicaIds = (entries: TaskRunLogEntry[]): string[] => {- if (!entries.length) return [];-- const sortedEntries = [...entries].sort((a, b) => {- return getTimestampMs(a.logTime) - getTimestampMs(b.logTime);- });-- const seen = new Set<string>();- const replicaIds: string[] = [];-- for (const entry of sortedEntries) {- const replicaId = entry.replicaId || "";- if (replicaId && !seen.has(replicaId)) {- seen.add(replicaId);- replicaIds.push(replicaId);- }- }-- return replicaIds;-};--// Group entries by replica ID, maintaining time order within each group-export const groupEntriesByReplica = (- entries: TaskRunLogEntry[]-): Map<string, TaskRunLogEntry[]> => {- const result = new Map<string, TaskRunLogEntry[]>();-- for (const entry of entries) {- const replicaId = entry.replicaId || "unknown";- if (!result.has(replicaId)) {- result.set(replicaId, []);- }- result.get(replicaId)!.push(entry);- }-- return result;-};--export interface ReleaseFileInfo {- version: string;- filePath: string;-}--export interface ReleaseFileEntriesGroup {- file: ReleaseFileInfo | null; // null for entries before any release file marker- entries: TaskRunLogEntry[];-}--// Check if entries contain any release file execute markers-export const hasReleaseFileMarkers = (entries: TaskRunLogEntry[]): boolean => {- return entries.some(- (entry) => entry.type === TaskRunLogEntry_Type.RELEASE_FILE_EXECUTE- );-};--// Group entries by release file markers-// Entries are grouped as: [orphan entries], [file1 entries], [file2 entries], ...-export const groupEntriesByReleaseFile = (- entries: TaskRunLogEntry[]-): ReleaseFileEntriesGroup[] => {- if (!entries.length) return [];-- // Sort entries by time first- const sortedEntries = [...entries].sort((a, b) => {- return getTimestampMs(a.logTime) - getTimestampMs(b.logTime);- });-- const groups: ReleaseFileEntriesGroup[] = [];- let currentGroup: ReleaseFileEntriesGroup = { file: null, entries: [] };-- for (const entry of sortedEntries) {- if (entry.type === TaskRunLogEntry_Type.RELEASE_FILE_EXECUTE) {- // Start a new group for this file- // Push the current group if it has entries- if (currentGroup.entries.length > 0) {- groups.push(currentGroup);- }- // Create new group for this file- const rfe = entry.releaseFileExecute;- currentGroup = {- file: rfe- ? { version: rfe.version, filePath: rfe.filePath || "" }- : null,- entries: [],- };- } else {- // Add entry to current group- currentGroup.entries.push(entry);- }- }-- // Push the last group if it has entries- if (currentGroup.entries.length > 0) {- groups.push(currentGroup);- }-- return groups;-};diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunRollbackDrawer.vue b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunRollbackDrawer.vuedeleted file mode 100644index 2e2000d4d3..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunRollbackDrawer.vue+++ /dev/null@@ -1,378 +0,0 @@-<template>- <Drawer v-model:show="show" :width="720" placement="right">- <DrawerContent- :title="$t('common.rollback')"- :closable="!state.loading"- class="max-w-[calc(100vw-2rem)]"- >- <div class="flex flex-col gap-y-4">- <!-- Steps indicator -->- <NSteps :current="currentStep" size="small">- <NStep :title="$t('task.select-task', 2)" />- <NStep :title="$t('task-run.rollback.preview-statement.self')" />- </NSteps>-- <!-- Step content -->- <div class="flex-1">- <!-- Step 1: Select Tasks -->- <template v-if="currentStep === 1">- <TaskTable- bordered- :tasks="rollbackableTasks"- :task-status-filter="[]"- :selected-tasks="selectedTasks"- :task-selectable="isTaskSelectable"- @update:selected-tasks="handleSelectedTasksUpdate"- />- </template>-- <!-- Step 2: Preview Statements -->- <template v-else-if="currentStep === 2">- <div class="flex flex-col gap-y-4">- <NAlert type="info">- {{ $t("task-run.rollback.preview-statement.description") }}- </NAlert>-- <div class="flex flex-col gap-y-4">- <div- v-for="preview in rollbackPreviews"- :key="preview.taskRunName"- class="flex flex-col gap-y-2"- >- <DatabaseDisplay :database="preview.task.target" />- <template v-if="!isUndefined(preview.statement)">- <MonacoEditor- v-if="preview.statement"- class="border rounded-[3px] text-sm overflow-clip"- :content="preview.statement"- :readonly="true"- :auto-height="{ min: 100, max: 200 }"- />- <!-- Empty generated statement placeholder -->- <div- v-else- class="flex items-center justify-center p-8 border rounded-[3px] bg-gray-50"- >- <div class="text-center flex flex-col gap-y-2">- <DatabaseBackupIcon- class="w-6 h-6 mx-auto text-gray-400"- />- <p class="text-sm text-gray-500">- {{ $t("task-run.rollback.no-statement-generated") }}- </p>- </div>- </div>- </template>- <div- v-else-if="preview.error"- class="p-3 border border-red-200 bg-red-50 rounded-sm text-sm text-red-600"- >- {{ preview.error }}- </div>- <NSkeleton v-else text :repeat="3" class="h-24" />- </div>- </div>- </div>- </template>- </div>- </div>-- <template #footer>- <div class="flex items-center justify-between">- <div class="flex items-center gap-x-2">- <NButton- v-if="currentStep === 1"- quaternary- :disabled="state.loading"- @click="handleCancel"- >- {{ $t("common.cancel") }}- </NButton>- <NButton- v-else- quaternary- :disabled="state.loading"- @click="handlePrevStep"- >- {{ $t("common.back") }}- </NButton>- <NButton- v-if="currentStep === 1"- type="primary"- :disabled="selectedTasks.length === 0"- @click="handleNextStep"- >- {{ $t("common.next") }}- </NButton>- <NButton- v-else-if="currentStep === 2"- type="primary"- :loading="state.loading"- :disabled="!canCreateRollback"- @click="handleConfirm"- >- {{ $t("common.confirm") }}- </NButton>- </div>- </div>- </template>- </DrawerContent>- </Drawer>-</template>--<script setup lang="ts">-import { create } from "@bufbuild/protobuf";-import { createContextValues } from "@connectrpc/connect";-import { isUndefined } from "lodash-es";-import { DatabaseBackupIcon } from "lucide-vue-next";-import { NAlert, NButton, NSkeleton, NStep, NSteps } from "naive-ui";-import { v4 as uuidv4 } from "uuid";-import { computed, nextTick, reactive, ref, watch } from "vue";-import { useRouter } from "vue-router";-import { MonacoEditor } from "@/components/MonacoEditor";-import DatabaseDisplay from "@/components/Plan/components/common/DatabaseDisplay.vue";-import { Drawer, DrawerContent } from "@/components/v2";-import {- planServiceClientConnect,- rolloutServiceClientConnect,-} from "@/connect";-import { silentContextKey } from "@/connect/context-key";-import { PROJECT_V1_ROUTE_PLAN_DETAIL } from "@/router/dashboard/projectV1";-import {- pushNotification,- useCurrentProjectV1,- useSheetV1Store,-} from "@/store";-import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";-import {- CreatePlanRequestSchema,- Plan_ChangeDatabaseConfigSchema,- Plan_SpecSchema,- PlanSchema,-} from "@/types/proto-es/v1/plan_service_pb";-import type {- Rollout,- Task,- TaskRun,-} from "@/types/proto-es/v1/rollout_service_pb";-import { PreviewTaskRunRollbackRequestSchema } from "@/types/proto-es/v1/rollout_service_pb";-import { SheetSchema } from "@/types/proto-es/v1/sheet_service_pb";-import {- databaseForTask,- extractPlanUID,- extractPlanUIDFromRolloutName,- extractProjectResourceName,- hasProjectPermissionV2,-} from "@/utils";-import TaskTable from "../Task/TaskTable.vue";--type LocalState = {- loading: boolean;-};--const props = defineProps<{- rollout: Rollout;- rollbackableTaskRuns: Array<{- task: Task;- taskRun: TaskRun;- database: ReturnType<typeof databaseForTask>;- }>;-}>();--const emit = defineEmits<{- (event: "close"): void;-}>();--const router = useRouter();-const { project } = useCurrentProjectV1();--const show = defineModel<boolean>("show", { default: false });--const state = reactive<LocalState>({- loading: false,-});--const currentStep = ref(1);-const selectedTasks = ref<Task[]>([]);-const rollbackPreviews = ref<- Array<{- taskRunName: string;- task: Task;- database: ReturnType<typeof databaseForTask>;- statement?: string;- error?: string;- }>->([]);--// Extract just the tasks from rollbackableTaskRuns-const rollbackableTasks = computed(() => {- return props.rollbackableTaskRuns.map((item) => item.task);-});--// Map selected tasks back to their task runs-const selectedTaskRuns = computed(() => {- return props.rollbackableTaskRuns.filter((item) =>- selectedTasks.value.some((task) => task.name === item.task.name)- );-});--// Task is selectable if it has a corresponding rollbackable task run-const isTaskSelectable = (task: Task): boolean => {- // In this case, all tasks in rollbackableTasks should be selectable- // but we can add additional logic here if needed- return rollbackableTasks.value.some((t) => t.name === task.name);-};--const canCreateRollback = computed(() => {- return (- rollbackPreviews.value.length > 0 &&- rollbackPreviews.value.every((p) => !p.error) &&- rollbackPreviews.value.some((p) => p.statement) && // At least one non-empty statement- hasProjectPermissionV2(project.value, "bb.plans.create")- );-});--const handleSelectedTasksUpdate = (tasks: Task[]) => {- selectedTasks.value = tasks;-};--const handleCancel = () => {- show.value = false;- emit("close");-};--const handleNextStep = async () => {- if (selectedTasks.value.length === 0) return;-- currentStep.value = 2;- rollbackPreviews.value = selectedTaskRuns.value.map((item) => ({- taskRunName: item.taskRun.name,- task: item.task,- database: item.database,- }));-- // Fetch preview for each selected task run- for (const preview of rollbackPreviews.value) {- try {- const request = create(PreviewTaskRunRollbackRequestSchema, {- name: preview.taskRunName,- });- const response = await rolloutServiceClientConnect.previewTaskRunRollback(- request,- {- contextValues: createContextValues().set(silentContextKey, true),- }- );- const index = rollbackPreviews.value.findIndex(- (p) => p.taskRunName === preview.taskRunName- );- if (index !== -1) {- rollbackPreviews.value[index].statement = response.statement;- }- } catch (error) {- const index = rollbackPreviews.value.findIndex(- (p) => p.taskRunName === preview.taskRunName- );- if (index !== -1) {- rollbackPreviews.value[index].error = String(error);- }- }- }-};--const handlePrevStep = () => {- if (currentStep.value === 2) {- currentStep.value = 1;- }-};--const handleConfirm = async () => {- if (!canCreateRollback.value) return;-- state.loading = true;- try {- const sheetStore = useSheetV1Store();- const specs: Plan_Spec[] = [];-- // Create sheets and specs for each rollback- for (const preview of rollbackPreviews.value) {- if (!preview.statement) continue;-- // Create a sheet for the rollback statement- const sheet = await sheetStore.createSheet(- project.value.name,- create(SheetSchema, {- name: `${project.value.name}/sheets/${uuidv4()}`,- content: new TextEncoder().encode(preview.statement),- })- );-- // Create spec for this database- const spec = create(Plan_SpecSchema, {- id: uuidv4(),- config: {- case: "changeDatabaseConfig",- value: create(Plan_ChangeDatabaseConfigSchema, {- targets: [preview.task.target],- sheet: sheet.name,- }),- },- });- specs.push(spec);- }-- // Create the plan- const plan = create(PlanSchema, {- name: `${project.value.name}/plans/${uuidv4()}`,- title: `Rollback for rollout#${extractPlanUIDFromRolloutName(props.rollout.name)}`,- description: `This plan is created to rollback ${rollbackPreviews.value.length} task(s) in rollout #${extractPlanUIDFromRolloutName(props.rollout.name)}`,- specs,- });-- const request = create(CreatePlanRequestSchema, {- parent: project.value.name,- plan,- });- const createdPlan = await planServiceClientConnect.createPlan(request);- router.push({- name: PROJECT_V1_ROUTE_PLAN_DETAIL,- params: {- projectId: extractProjectResourceName(project.value.name),- planId: extractPlanUID(createdPlan.name),- },- });- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: "Failed to create rollback plan",- description: String(error),- });- } finally {- state.loading = false;- }-};--// Reset state when drawer opens-const resetState = () => {- currentStep.value = 1;- selectedTasks.value = [];- rollbackPreviews.value = [];- state.loading = false;-};--// Reset state when drawer closes-watch(show, (newValue) => {- if (newValue) {- resetState();- // Auto-select and advance to step 2 if there's only one task- if (rollbackableTasks.value.length === 1) {- selectedTasks.value = [rollbackableTasks.value[0]];- // Use nextTick to ensure state is properly initialized before advancing- nextTick(() => {- handleNextStep();- });- }- }-});-</script>diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunRollbackSection.vue b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunRollbackSection.vuedeleted file mode 100644index 066146f02d..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunRollbackSection.vue+++ /dev/null@@ -1,78 +0,0 @@-<template>- <div v-if="rollbackableTaskRuns.length > 0" class="w-full mt-3 pl-4">- <NButton- size="small"- text- @click="showRollbackDrawer = true"- icon-placement="right"- >- <template #icon>- <DatabaseBackupIcon class="w-4 h-auto" />- </template>- {{ $t("task-run.rollback.available", rollbackableTaskRuns.length) }}- </NButton>-- <TaskRunRollbackDrawer- v-model:show="showRollbackDrawer"- :rollout="rollout"- :rollbackable-task-runs="rollbackableTaskRuns"- @close="showRollbackDrawer = false"- />- </div>-</template>--<script setup lang="ts">-import { DatabaseBackupIcon } from "lucide-vue-next";-import { NButton } from "naive-ui";-import { computed, ref } from "vue";-import { usePlanContextWithRollout } from "@/components/Plan/logic";-import { taskRunNamePrefix, useCurrentProjectV1 } from "@/store";-import type {- Rollout,- Task,- TaskRun,-} from "@/types/proto-es/v1/rollout_service_pb";-import { TaskRun_Status } from "@/types/proto-es/v1/rollout_service_pb";-import { databaseForTask } from "@/utils";-import TaskRunRollbackDrawer from "./TaskRunRollbackDrawer.vue";--const props = defineProps<{- rollout: Rollout;-}>();--const { project } = useCurrentProjectV1();-const { taskRuns } = usePlanContextWithRollout();--const showRollbackDrawer = ref(false);--// Get rollbackable task runs-const rollbackableTaskRuns = computed(() => {- const result: Array<{- task: Task;- taskRun: TaskRun;- database: ReturnType<typeof databaseForTask>;- }> = [];-- for (const stage of props.rollout.stages) {- for (const task of stage.tasks) {- // Find the latest successful task run with prior backup- const rollbackableRun = taskRuns.value.find(- (run) =>- run.name.startsWith(`${task.name}/${taskRunNamePrefix}`) &&- run.status === TaskRun_Status.DONE &&- run.hasPriorBackup- );-- if (rollbackableRun) {- result.push({- task,- taskRun: rollbackableRun,- database: databaseForTask(project.value, task),- });- }- }- }-- return result;-});-</script>diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunSession/Cells/StatementCell.vue b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunSession/Cells/StatementCell.vuedeleted file mode 100644index 490145487c..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunSession/Cells/StatementCell.vue+++ /dev/null@@ -1,38 +0,0 @@-<template>- <div class="text-sm group">- <TextOverflowPopover- v-if="query"- :content="query.trim()"- :max-length="100"- :max-popover-content-length="1000"- :line-wrap="false"- :line-break-replacer="' '"- code-class="relative"- placement="top"- >- <template #default="{ displayContent }">- <span class="flex-1 flex flex-row justify-start items-center gap-x-1">- <span class="line-clamp-1">- {{ displayContent }}- </span>- <CopyButton :content="query.trim()" />- </span>- </template>- <template #popover-header>- <div class="absolute bottom-1 right-1">- <CopyButton :content="query.trim()" />- </div>- </template>- </TextOverflowPopover>- <div v-else class="text-control-placeholder">-</div>- </div>-</template>--<script setup lang="ts">-import TextOverflowPopover from "@/components/misc/TextOverflowPopover.vue";-import { CopyButton } from "@/components/v2";--defineProps<{- query: string;-}>();-</script>diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunSession/Cells/TimeCell.vue b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunSession/Cells/TimeCell.vuedeleted file mode 100644index a254d83ce5..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunSession/Cells/TimeCell.vue+++ /dev/null@@ -1,18 +0,0 @@-<template>- <div class="text-sm">- <HumanizeDate- v-if="date"- :date="date"- format="YYYY-MM-DD HH:mm:ss.SSS UTCZZ"- />- <div v-else class="text-control-placeholder">-</div>- </div>-</template>--<script setup lang="ts">-import HumanizeDate from "@/components/misc/HumanizeDate.vue";--defineProps<{- date: Date | undefined;-}>();-</script>diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunSession/Cells/index.ts b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunSession/Cells/index.tsdeleted file mode 100644index 60f6710307..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunSession/Cells/index.ts+++ /dev/null@@ -1,4 +0,0 @@-import StatementCell from "./StatementCell.vue";-import TimeCell from "./TimeCell.vue";--export { StatementCell, TimeCell };diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunSession/PostgresSessionTable.vue b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunSession/PostgresSessionTable.vuedeleted file mode 100644index 7c76bfe25e..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunSession/PostgresSessionTable.vue+++ /dev/null@@ -1,202 +0,0 @@-<template>- <div class="w-full flex flex-col gap-y-2">- <NDataTable- :single-column="true"- :columns="columns"- :data="[session]"- :row-key="rowKey"- size="small"- />-- <div class="pt-2 flex flex-row justify-start items-center">- <span class="textlabel">- {{ $t("issue.task-run.task-run-session.blocking-sessions.self") }}- </span>- <span class="textinfolabel ml-1">- ({{- $t("issue.task-run.task-run-session.blocking-sessions.description")- }})- </span>- </div>- <NDataTable- size="small"- :columns="columns"- :data="blockingSessions"- :row-key="rowKey"- />-- <template v-if="blockedSessions.length > 0">- <div class="pt-2 flex flex-row justify-start items-center">- <AlignHorizontalJustifyStartIcon class="w-4 h-auto mr-2 opacity-80" />- <p class="textlabel">- {{ $t("issue.task-run.task-run-session.blocked-sessions.self") }}- </p>- <p class="textinfolabel ml-1">- {{- $t("issue.task-run.task-run-session.blocked-sessions.description")- }}- </p>- </div>- <NDataTable- size="small"- :columns="columns"- :data="blockedSessions"- :row-key="rowKey"- />- </template>- </div>-</template>--<script setup lang="tsx">-import { AlignHorizontalJustifyStartIcon } from "lucide-vue-next";-import { type DataTableColumn, NDataTable } from "naive-ui";-import { computed } from "vue";-import { getDateForPbTimestampProtoEs } from "@/types";-import type {- TaskRunSession_Postgres,- TaskRunSession_Postgres_Session,-} from "@/types/proto-es/v1/rollout_service_pb";-import { StatementCell, TimeCell } from "./Cells";--const props = defineProps<{- taskRunSession: TaskRunSession_Postgres;-}>();--const session = computed(() => props.taskRunSession.session!);-const blockingSessions = computed(() => props.taskRunSession.blockingSessions);-const blockedSessions = computed(() => props.taskRunSession.blockedSessions);--const rowKey = (session: TaskRunSession_Postgres_Session) => {- return session.pid;-};--const columns = computed(() => {- const columns: (DataTableColumn<TaskRunSession_Postgres_Session> & {- hide?: boolean;- })[] = [- {- key: "pid",- title: () => "pid",- width: 50,- className: "whitespace-nowrap",- render: (session) => {- return session.pid;- },- },- {- key: "blocked_by_pids",- title: () => "blocked_by_pids",- width: 120,- className: "whitespace-nowrap",- render: (session) => {- return session.blockedByPids.join(", ");- },- },- {- key: "query",- resizable: true,- title: () => "query",- width: "60%",- minWidth: 256,- render: (session) => {- return <StatementCell query={session.query} />;- },- },- {- key: "state",- title: () => "state",- width: 120,- render: (session) => {- return session.state;- },- },- {- key: "wait_event_type",- title: () => "wait_event_type",- width: 144,- render: (session) => {- return session.waitEventType;- },- },- {- key: "wait_event",- title: () => "wait_event",- width: 120,- render: (session) => {- return session.waitEvent;- },- },- {- key: "datname",- title: () => "datname",- width: 120,- render: (session) => {- return session.datname;- },- },- {- key: "usename",- title: () => "usename",- width: 120,- render: (session) => {- return session.usename;- },- },- {- key: "application_name",- title: () => "application_name",- width: 144,- render: (session) => {- return session.applicationName;- },- },- {- key: "client_addr",- title: () => "client_addr",- width: 120,- render: (session) => {- return session.clientAddr;- },- },- {- key: "client_port",- width: 120,- title: () => "client_port",- render: (session) => {- return session.clientPort;- },- },- {- key: "backend_start",- title: () => "backend_start",- width: 120,- render: (session) => {- return (- <TimeCell date={getDateForPbTimestampProtoEs(session.backendStart)} />- );- },- },- {- key: "xact_start",- title: () => "xact_start",- width: 120,- render: (session) => {- return (- <TimeCell date={getDateForPbTimestampProtoEs(session.xactStart)} />- );- },- },- {- key: "query_start",- title: () => "query_start",- width: 120,- render: (session) => {- return (- <TimeCell date={getDateForPbTimestampProtoEs(session.queryStart)} />- );- },- },- ];- return columns.filter((column) => !column.hide);-});-</script>diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunSession/TaskRunSession.vue b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunSession/TaskRunSession.vuedeleted file mode 100644index 230fadc7b7..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunSession/TaskRunSession.vue+++ /dev/null@@ -1,71 +0,0 @@-<template>- <template v-if="showSessionTables">- <PostgresSessionTable- v-if="postgresSession"- :task-run-session="postgresSession"- />-- <div v-if="isLoading" class="flex justify-center items-center py-10">- <BBSpin />- </div>- </template>- <div v-else class="text-control-placeholder">- {{ $t("issue.task-run.task-run-session.no-session-found") }}- </div>-</template>--<script setup lang="tsx">-import { create } from "@bufbuild/protobuf";-import { createContextValues } from "@connectrpc/connect";-import { computedAsync } from "@vueuse/core";-import { computed, ref } from "vue";-import { BBSpin } from "@/bbkit";-import { rolloutServiceClientConnect } from "@/connect";-import { silentContextKey } from "@/connect/context-key";-import {- GetTaskRunSessionRequestSchema,- type TaskRun,- TaskRun_Status,-} from "@/types/proto-es/v1/rollout_service_pb";-import PostgresSessionTable from "./PostgresSessionTable.vue";--const props = defineProps<{- taskRun: TaskRun;-}>();--const isLoading = ref(false);--const showSessionTables = computed(- () => props.taskRun.status === TaskRun_Status.RUNNING-);--const taskRunSession = computedAsync(- async () => {- if (!showSessionTables.value) {- return undefined;- }- const request = create(GetTaskRunSessionRequestSchema, {- parent: props.taskRun.name,- });- const response = await rolloutServiceClientConnect.getTaskRunSession(- request,- {- contextValues: createContextValues().set(silentContextKey, true),- }- );- return response;- },- undefined,- {- evaluating: isLoading,- }-);--const postgresSession = computed(() => {- const session = taskRunSession.value;- if (session?.session?.case === "postgres") {- return session.session.value;- }- return undefined;-});-</script>diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunSession/index.ts b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunSession/index.tsdeleted file mode 100644index 0a3abcbab1..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunSession/index.ts+++ /dev/null@@ -1,3 +0,0 @@-import TaskRunSession from "./TaskRunSession.vue";--export default TaskRunSession;diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunStatusIcon.vue b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunStatusIcon.vuedeleted file mode 100644index 84746f98cb..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunStatusIcon.vue+++ /dev/null@@ -1,62 +0,0 @@-<template>- <div- class="relative w-5 h-5 flex shrink-0 items-center justify-center rounded-full select-none"- :class="classes"- >- <template v-if="status === TaskRun_Status.PENDING">- <span class="h-1.5 w-1.5 bg-info rounded-full" aria-hidden="true" />- </template>- <template v-else-if="status === TaskRun_Status.RUNNING">- <div class="flex h-2.5 w-2.5 relative overflow-visible">- <span- class="w-full h-full rounded-full z-0 absolute animate-ping-slow bg-blue-600/50"- aria-hidden="true"- />- <span- class="w-full h-full rounded-full z-1 bg-info"- aria-hidden="true"- />- </div>- </template>- <template v-else-if="status === TaskRun_Status.DONE">- <heroicons-outline:check class="w-5 h-5" />- </template>- <template v-else-if="status === TaskRun_Status.FAILED">- <span class="text-white font-medium text-base" aria-hidden="true">!</span>- </template>- <template v-else-if="status === TaskRun_Status.CANCELED">- <heroicons-outline:minus-sm class="w-5 h-5" />- </template>- </div>-</template>--<script setup lang="ts">-import { computed } from "vue";-import { TaskRun_Status } from "@/types/proto-es/v1/rollout_service_pb";--const props = defineProps<{- status: TaskRun_Status;-}>();--const classes = computed(() => {- switch (props.status) {- case TaskRun_Status.PENDING:- return "bg-white border-2 border-info text-info";- case TaskRun_Status.RUNNING:- return "bg-white border-2 border-info text-info";- case TaskRun_Status.DONE:- return "bg-success text-white";- case TaskRun_Status.FAILED:- return "bg-error text-white";- case TaskRun_Status.CANCELED:- return "bg-white border-2 border-gray-400 text-gray-400";- }- console.assert(- false,- `should never reach this line. status=${- props.status- } ${TaskRun_Status[props.status]}`- );- return "";-});-</script>diff --git a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunTable.vue b/frontend/src/components/RolloutV1/components/TaskRun/TaskRunTable.vuedeleted file mode 100644index 0ea8e361d3..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/TaskRunTable.vue+++ /dev/null@@ -1,223 +0,0 @@-<template>- <NDataTable- size="small"- :row-key="rowKey"- :columns="columnList"- :data="sortedTaskRuns"- :striped="true"- :bordered="true"- :virtual-scroll="virtualScroll"- :max-height="maxHeight"- />-- <Drawer v-model:show="taskRunDetailContext.show">- <DrawerContent- :title="$t('common.detail')"- class="max-w-[calc(100vw-2rem)]"- >- <TaskRunDetail- v-if="taskRunDetailContext.taskRun"- :key="taskRunDetailContext.taskRun.name"- :task-run="taskRunDetailContext.taskRun"- :database="getDatabaseForTaskRun(taskRunDetailContext.taskRun)"- />- </DrawerContent>- </Drawer>-</template>--<script lang="tsx" setup>-import { create } from "@bufbuild/protobuf";-import type { Duration } from "@bufbuild/protobuf/wkt";-import { DurationSchema } from "@bufbuild/protobuf/wkt";-import type { DataTableColumn } from "naive-ui";-import { NButton, NDataTable } from "naive-ui";-import { computed, ref } from "vue";-import { useI18n } from "vue-i18n";-import HumanizeDate from "@/components/misc/HumanizeDate.vue";-import DatabaseDisplay from "@/components/Plan/components/common/DatabaseDisplay.vue";-import { usePlanContextWithRollout } from "@/components/Plan/logic";-import { Drawer, DrawerContent } from "@/components/v2";-import { useCurrentProjectV1 } from "@/store";-import {- getDateForPbTimestampProtoEs,- getTimeForPbTimestampProtoEs,-} from "@/types";-import type { Task, TaskRun } from "@/types/proto-es/v1/rollout_service_pb";-import { TaskRun_Status } from "@/types/proto-es/v1/rollout_service_pb";-import { databaseForTask, extractTaskUID, humanizeDurationV1 } from "@/utils";-import TaskRunComment from "./TaskRunComment.vue";-import TaskRunDetail from "./TaskRunDetail.vue";-import TaskRunStatusIcon from "./TaskRunStatusIcon.vue";--const props = defineProps<{- taskRuns: TaskRun[];- showDatabaseColumn?: boolean; // Whether to show database column- virtualScroll?: boolean;- maxHeight?: string | number;-}>();--// Sort task runs by creation time descending (newest first)-const sortedTaskRuns = computed(() => {- return [...props.taskRuns].sort((a, b) => {- const timeA = a.createTime ? Number(a.createTime.seconds) : 0;- const timeB = b.createTime ? Number(b.createTime.seconds) : 0;- return timeB - timeA; // Descending order- });-});--const { t } = useI18n();-const { project } = useCurrentProjectV1();-const { rollout } = usePlanContextWithRollout();--// Helper function to get task for a given task run-const getTaskForTaskRun = (taskRun: TaskRun): Task | undefined => {- if (!rollout.value) return undefined;-- // Search through all stages and tasks in the rollout- for (const stage of rollout.value.stages) {- for (const task of stage.tasks) {- if (extractTaskUID(task.name) === extractTaskUID(taskRun.name)) {- return task;- }- }- }- return undefined;-};--// Helper function to get database for a task run-const getDatabaseForTaskRun = (taskRun: TaskRun) => {- const task = getTaskForTaskRun(taskRun);- return task ? databaseForTask(project.value, task) : undefined;-};--const taskRunDetailContext = ref<{- show: boolean;- taskRun?: TaskRun;-}>({- show: false,-});--const rowKey = (taskRun: TaskRun) => {- return taskRun.name;-};--const columnList = computed((): DataTableColumn<TaskRun>[] => {- return [- {- key: "status",- width: 48,- render: (taskRun: TaskRun) => {- return <TaskRunStatusIcon status={taskRun.status} />;- },- },- ...(props.showDatabaseColumn- ? [- {- key: "database",- title: t("common.database"),- width: 200,- resizable: true,- render: (taskRun: TaskRun) => {- const db = getDatabaseForTaskRun(taskRun);- return db ? (- <DatabaseDisplay database={db.name} showEnvironment={true} />- ) : (- "-"- );- },- },- ]- : []),- {- key: "detail",- title: t("common.detail"),- ellipsis: true,- resizable: true,- render: (taskRun: TaskRun) => {- return <TaskRunComment taskRun={taskRun} />;- },- },- {- key: "createTime",- title: t("task.created"),- width: 140,- render: (taskRun: TaskRun) => (- <HumanizeDate date={getDateForPbTimestampProtoEs(taskRun.createTime)} />- ),- },- {- key: "startTime",- title: t("task.started"),- width: 140,- render: (taskRun: TaskRun) =>- taskRun.startTime ? (- <HumanizeDate- date={getDateForPbTimestampProtoEs(taskRun.startTime)}- />- ) : (- "-"- ),- },- {- key: "executionDuration",- title: t("task.execution-time"),- width: 120,- render: (taskRun: TaskRun) => {- const duration = executionDurationOfTaskRun(taskRun);- return duration ? humanizeDurationV1(duration) : "-";- },- },- {- key: "actions",- title: "",- width: 80,- render: (taskRun: TaskRun) =>- shouldShowDetailButton(taskRun) ? (- <NButton size="tiny" onClick={() => showDetail(taskRun)}>- {t("common.detail")}- </NButton>- ) : null,- },- ];-});--const executionDurationOfTaskRun = (taskRun: TaskRun): Duration | undefined => {- const { startTime, updateTime } = taskRun;- if (!startTime || !updateTime) {- return undefined;- }- if (Number(startTime.seconds) === 0) {- return undefined;- }- if (taskRun.status === TaskRun_Status.RUNNING) {- const elapsedMS = Date.now() - getTimeForPbTimestampProtoEs(startTime);- return create(DurationSchema, {- seconds: BigInt(Math.floor(elapsedMS / 1000)),- nanos: (elapsedMS % 1000) * 1e6,- });- }- const startMS = getTimeForPbTimestampProtoEs(startTime);- const updateMS = getTimeForPbTimestampProtoEs(updateTime);- const elapsedMS = updateMS - startMS;- return create(DurationSchema, {- seconds: BigInt(Math.floor(elapsedMS / 1000)),- nanos: (elapsedMS % 1000) * 1e6,- });-};--const shouldShowDetailButton = (taskRun: TaskRun) => {- return [- TaskRun_Status.RUNNING,- TaskRun_Status.DONE,- TaskRun_Status.FAILED,- TaskRun_Status.CANCELED,- ].includes(taskRun.status);-};--const showDetail = (taskRun: TaskRun) => {- taskRunDetailContext.value = {- show: true,- taskRun,- };-};-</script>diff --git a/frontend/src/components/RolloutV1/components/TaskRun/useRollbackableTasks.ts b/frontend/src/components/RolloutV1/components/TaskRun/useRollbackableTasks.tsdeleted file mode 100644index a7dad7cfe4..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/useRollbackableTasks.ts+++ /dev/null@@ -1,55 +0,0 @@-import { computed, type Ref } from "vue";-import { useCurrentProjectV1 } from "@/store";-import { taskRunNamePrefix } from "@/store/modules/v1/common";-import type {- Stage,- Task,- TaskRun,-} from "@/types/proto-es/v1/rollout_service_pb";-import { TaskRun_Status } from "@/types/proto-es/v1/rollout_service_pb";-import { databaseForTask } from "@/utils";--export type RollbackableTaskRun = {- task: Task;- taskRun: TaskRun;- database: ReturnType<typeof databaseForTask>;-};--export const useRollbackableTasks = (- stage: Ref<Stage | null | undefined>,- taskRuns: Ref<TaskRun[]>-) => {- const { project } = useCurrentProjectV1();-- const rollbackableTaskRuns = computed<RollbackableTaskRun[]>(() => {- if (!stage.value) {- return [];- }-- const result: RollbackableTaskRun[] = [];-- for (const task of stage.value.tasks) {- // Find the latest successful task run with prior backup- const rollbackableRun = taskRuns.value.find(- (run) =>- run.name.startsWith(`${task.name}/${taskRunNamePrefix}`) &&- run.status === TaskRun_Status.DONE &&- run.hasPriorBackup- );-- if (rollbackableRun) {- result.push({- task,- taskRun: rollbackableRun,- database: databaseForTask(project.value, task),- });- }- }-- return result;- });-- return {- rollbackableTaskRuns,- };-};diff --git a/frontend/src/components/RolloutV1/components/TaskRun/useTaskRunLogSummary.ts b/frontend/src/components/RolloutV1/components/TaskRun/useTaskRunLogSummary.tsdeleted file mode 100644index 55f9ada861..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/useTaskRunLogSummary.ts+++ /dev/null@@ -1,135 +0,0 @@-import type { ComputedRef, MaybeRefOrGetter } from "vue";-import { computed, onUnmounted, ref, toValue, watch } from "vue";-import { usePlanContext } from "@/components/Plan/logic";-import { useTaskRunLogStore } from "@/store/modules/v1/taskRunLog";-import type {- TaskRun,- TaskRunLog,- TaskRunLogEntry,-} from "@/types/proto-es/v1/rollout_service_pb";-import { TaskRunLogEntry_Type } from "@/types/proto-es/v1/rollout_service_pb";--export interface TaskRunLogSummary {- totalAffectedRows: bigint;- hasAffectedRows: boolean;- entries: TaskRunLogEntry[];-}--export interface UseTaskRunLogSummaryReturn {- taskRunLog: ComputedRef<TaskRunLog | undefined>;- summary: ComputedRef<TaskRunLogSummary>;- isLoading: ComputedRef<boolean>;-}--const EMPTY_SUMMARY: TaskRunLogSummary = {- totalAffectedRows: BigInt(0),- hasAffectedRows: false,- entries: [],-};--const calculateSummary = (log: TaskRunLog | undefined): TaskRunLogSummary => {- if (!log?.entries?.length) return EMPTY_SUMMARY;-- let totalAffectedRows = BigInt(0);- let hasAffectedRows = false;-- for (const entry of log.entries) {- if (entry.type === TaskRunLogEntry_Type.COMMAND_EXECUTE) {- const affectedRows = entry.commandExecute?.response?.affectedRows;- if (affectedRows !== undefined) {- totalAffectedRows += affectedRows;- hasAffectedRows = true;- }- }- }-- return {- totalAffectedRows,- hasAffectedRows,- entries: log.entries,- };-};--/**- * Composable for fetching and summarizing task run logs.- *- * Features:- * - Fetches logs when taskRun changes or shouldFetch becomes true- * - Auto-refetches when taskRun status changes (to get final results)- * - Auto-refetches when poller refreshes taskRuns- * - Calculates total affected rows from command executions- *- * @param taskRun - The task run to fetch logs for- * @param shouldFetch - Whether to actively fetch (e.g., only when UI is visible)- */-export const useTaskRunLogSummary = (- taskRun: MaybeRefOrGetter<TaskRun | undefined>,- shouldFetch: MaybeRefOrGetter<boolean>-): UseTaskRunLogSummaryReturn => {- const { events } = usePlanContext();- const taskRunLogStore = useTaskRunLogStore();- const isLoading = ref(false);-- // Helper to get current values- const getTaskRunName = () => toValue(taskRun)?.name;- const canFetch = () => toValue(shouldFetch) && !!getTaskRunName();-- const fetchLog = async (skipCache = false) => {- const taskRunName = getTaskRunName();- if (!taskRunName) return;-- isLoading.value = true;- try {- await taskRunLogStore.fetchTaskRunLog(taskRunName, { skipCache });- } finally {- isLoading.value = false;- }- };-- // Fetch when taskRun name changes or shouldFetch becomes true- watch(- [getTaskRunName, () => toValue(shouldFetch)],- async ([taskRunName, fetch], [, oldFetch]) => {- if (!fetch || !taskRunName) return;- // Skip cache when transitioning to fetch mode (e.g., item expanded)- const skipCache = !oldFetch && fetch;- await fetchLog(skipCache);- },- { immediate: true }- );-- // Refetch when taskRun status changes to get final results- watch(- () => toValue(taskRun)?.status,- async (newStatus, oldStatus) => {- if (newStatus !== oldStatus && canFetch()) {- await fetchLog(true);- }- }- );-- // Refetch when poller refreshes taskRuns- const unsubscribe = events.on(- "resource-refresh-completed",- async ({ resources }) => {- if (resources.includes("taskRuns") && canFetch()) {- await fetchLog(true);- }- }- );-- onUnmounted(unsubscribe);-- const taskRunLog = computed(() => {- const name = getTaskRunName();- return name ? taskRunLogStore.getTaskRunLog(name) : undefined;- });-- const summary = computed(() => calculateSummary(taskRunLog.value));-- return {- taskRunLog,- summary,- isLoading: computed(() => isLoading.value),- };-};diff --git a/frontend/src/components/RolloutV1/components/TaskRun/useTaskRunUtils.ts b/frontend/src/components/RolloutV1/components/TaskRun/useTaskRunUtils.tsdeleted file mode 100644index e4ebeeb6a8..0000000000--- a/frontend/src/components/RolloutV1/components/TaskRun/useTaskRunUtils.ts+++ /dev/null@@ -1,129 +0,0 @@-import { taskRunNamePrefix } from "@/store";-import type { TaskRun } from "@/types/proto-es/v1/rollout_service_pb";-import {- Task_Status,- TaskRun_Status,-} from "@/types/proto-es/v1/rollout_service_pb";--/**- * Extract task name from task run name.- * Format: projects/{project}/plans/{plan}/rollout/stages/{stage}/tasks/{task}/taskRuns/{taskRun}- */-export const getTaskNameFromTaskRun = (taskRunName: string): string => {- return taskRunName.replace(- `/${taskRunNamePrefix}${taskRunName.split("/").pop()}`,- ""- );-};--/**- * Map TaskRun_Status to Task_Status for TaskStatus component.- */-export const mapTaskRunStatusToTaskStatus = (- status: TaskRun_Status-): Task_Status => {- switch (status) {- case TaskRun_Status.PENDING:- return Task_Status.PENDING;- case TaskRun_Status.RUNNING:- return Task_Status.RUNNING;- case TaskRun_Status.DONE:- return Task_Status.DONE;- case TaskRun_Status.FAILED:- return Task_Status.FAILED;- case TaskRun_Status.CANCELED:- return Task_Status.CANCELED;- default:- return Task_Status.STATUS_UNSPECIFIED;- }-};--export type TimelineType = "success" | "error" | "warning" | "info" | "default";--/**- * Get NTimeline type from TaskRun_Status.- */-export const getTimelineType = (status: TaskRun_Status): TimelineType => {- switch (status) {- case TaskRun_Status.DONE:- return "success";- case TaskRun_Status.FAILED:- return "error";- case TaskRun_Status.RUNNING:- return "info";- case TaskRun_Status.PENDING:- return "warning";- case TaskRun_Status.CANCELED:- return "default";- default:- return "default";- }-};--/**- * Format duration in milliseconds to human-readable string.- * - >= 1h: "Xh Ym"- * - >= 1m: "Xm Ys"- * - >= 1s: "Xs"- * - > 0ms: "Xms"- * - <= 0: "< 1s"- */-export const formatDuration = (durationMs: number): string => {- const seconds = Math.floor(durationMs / 1000);- const minutes = Math.floor(seconds / 60);- const hours = Math.floor(minutes / 60);-- if (hours > 0) {- const remainingMinutes = minutes % 60;- return `${hours}h ${remainingMinutes}m`;- }-- if (minutes > 0) {- const remainingSeconds = seconds % 60;- return `${minutes}m ${remainingSeconds}s`;- }-- if (seconds > 0) {- return `${seconds}s`;- }-- if (durationMs > 0) {- return `${Math.round(durationMs)}ms`;- }-- return "< 1s";-};--/**- * Get duration display string for a task run.- * - PENDING: empty (not started yet)- * - RUNNING: elapsed time from startTime to now- * - Completed (DONE/FAILED/CANCELED): total duration from startTime to updateTime- */-export const getTaskRunDuration = (taskRun: TaskRun): string => {- const { startTime, status, updateTime } = taskRun;-- // PENDING tasks are scheduled/queued, not running - no duration to show- if (status === TaskRun_Status.PENDING) {- return "";- }-- if (!startTime) {- return "";- }-- if (status === TaskRun_Status.RUNNING) {- // Show elapsed time for running tasks- const elapsedMs = Date.now() - Number(startTime.seconds) * 1000;- return formatDuration(elapsedMs);- }-- // For completed tasks (DONE, FAILED, CANCELED), show total duration- if (!updateTime) {- return "";- }-- const durationMs =- (Number(updateTime.seconds) - Number(startTime.seconds)) * 1000;- return formatDuration(durationMs);-};diff --git a/frontend/src/components/RolloutV1/components/shared/reactivity.ts b/frontend/src/components/RolloutV1/components/shared/reactivity.tsdeleted file mode 100644index 76dcea0fd5..0000000000--- a/frontend/src/components/RolloutV1/components/shared/reactivity.ts+++ /dev/null@@ -1,45 +0,0 @@-import type { Ref } from "vue";--/**- * Trigger reactivity for a Set ref by creating a new Set instance.- * This is necessary because Vue's reactivity system doesn't automatically track Set mutations.- * By creating a new Set instance, we trigger Vue's reactive system to detect the change.- */-export const triggerSetReactivity = <T>(setRef: Ref<Set<T>>): void => {- setRef.value = new Set(setRef.value);-};--/**- * Add an item to a reactive Set and trigger reactivity- */-export const addToSet = <T>(setRef: Ref<Set<T>>, item: T): void => {- setRef.value.add(item);- triggerSetReactivity(setRef);-};--/**- * Delete an item from a reactive Set and trigger reactivity- */-export const deleteFromSet = <T>(setRef: Ref<Set<T>>, item: T): void => {- setRef.value.delete(item);- triggerSetReactivity(setRef);-};--/**- * Clear a reactive Set and trigger reactivity- */-export const clearSet = <T>(setRef: Ref<Set<T>>): void => {- setRef.value.clear();- triggerSetReactivity(setRef);-};--/**- * Toggle an item in a reactive Set and trigger reactivity- */-export const toggleInSet = <T>(setRef: Ref<Set<T>>, item: T): void => {- if (setRef.value.has(item)) {- deleteFromSet(setRef, item);- } else {- addToSet(setRef, item);- }-};diff --git a/frontend/src/components/RolloutV1/components/shared/rolloutRouteHelpers.ts b/frontend/src/components/RolloutV1/components/shared/rolloutRouteHelpers.tsdeleted file mode 100644index d2976ddb64..0000000000--- a/frontend/src/components/RolloutV1/components/shared/rolloutRouteHelpers.ts+++ /dev/null@@ -1,21 +0,0 @@-import type { RouteLocationRaw } from "vue-router";-import {- buildStageRoute as buildPlanDetailStageRoute,- buildTaskDetailRoute as buildPlanDetailTaskRoute,-} from "@/router/dashboard/projectV1RouteHelpers";--/**- * Build a route location for the task detail view.- * Task name format: projects/{project}/plans/{plan}/rollout/stages/{stage}/tasks/{task}- */-export const buildTaskDetailRoute = (taskName: string): RouteLocationRaw => {- return buildPlanDetailTaskRoute(taskName);-};--/**- * Build a route location for the stage view.- * Stage name format: projects/{project}/plans/{plan}/rollout/stages/{stage}- */-export const buildStageRoute = (stageName: string): RouteLocationRaw => {- return buildPlanDetailStageRoute(stageName);-};diff --git a/frontend/src/components/RolloutV1/components/shared/taskStatus.ts b/frontend/src/components/RolloutV1/components/shared/taskStatus.tsdeleted file mode 100644index 9f11b2cac0..0000000000--- a/frontend/src/components/RolloutV1/components/shared/taskStatus.ts+++ /dev/null@@ -1,75 +0,0 @@-import { TASK_STATUS_FILTERS } from "@/components/RolloutV1/constants/task";-import { getTimeForPbTimestampProtoEs } from "@/types";-import type { Task } from "@/types/proto-es/v1/rollout_service_pb";-import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";--/**- * Task statuses that are considered "actionable" - not yet completed successfully.- * Used for filtering unfinished tasks and determining if bulk actions are available.- */-const ACTIONABLE_STATUSES = new Set<Task_Status>([- Task_Status.NOT_STARTED,- Task_Status.PENDING,- Task_Status.RUNNING,- Task_Status.FAILED,- Task_Status.CANCELED,-]);--/**- * Priority map for task status sorting.- * Built from TASK_STATUS_FILTERS to maintain single source of truth.- */-const STATUS_PRIORITY = new Map<Task_Status, number>(- TASK_STATUS_FILTERS.map((status, index) => [status, index])-);--/**- * Check if a task status is actionable (not completed).- */-const isActionableStatus = (status: Task_Status): boolean =>- ACTIONABLE_STATUSES.has(status);--/**- * Check if a task is in an unfinished/actionable state.- */-export const isTaskUnfinished = (task: Task): boolean =>- isActionableStatus(task.status);--/**- * Check if a task is selectable for bulk actions.- * Currently same as unfinished - tasks that aren't done can be acted upon.- */-export const isTaskSelectable = (task: Task): boolean =>- isActionableStatus(task.status);--/**- * Check if a task is currently running.- */-export const isTaskRunning = (task: Task): boolean =>- task.status === Task_Status.RUNNING;--/**- * Get the sort priority for a task status.- * Lower values = higher priority in display order.- */-export const getTaskStatusPriority = (status: Task_Status): number =>- STATUS_PRIORITY.get(status) ?? Number.MAX_SAFE_INTEGER;--/**- * Compare tasks for sorting: first by status priority, then by update time.- * Tasks with same status are sorted most recently updated first.- *- * @example- * const sorted = [...tasks].sort(compareTasksByStatus);- */-export const compareTasksByStatus = (a: Task, b: Task): number => {- // Primary: status priority (lower = first)- const statusDiff =- getTaskStatusPriority(a.status) - getTaskStatusPriority(b.status);- if (statusDiff !== 0) return statusDiff;-- // Secondary: update time (newer = first)- const timeA = getTimeForPbTimestampProtoEs(a.updateTime, 0);- const timeB = getTimeForPbTimestampProtoEs(b.updateTime, 0);- return timeB - timeA;-};diff --git a/frontend/src/components/RolloutV1/components/shared/useTaskRunsForTask.ts b/frontend/src/components/RolloutV1/components/shared/useTaskRunsForTask.tsdeleted file mode 100644index 61f9412905..0000000000--- a/frontend/src/components/RolloutV1/components/shared/useTaskRunsForTask.ts+++ /dev/null@@ -1,14 +0,0 @@-import type { ComputedRef } from "vue";-import { computed } from "vue";-import type { TaskRun } from "@/types/proto-es/v1/rollout_service_pb";--export const useTaskRunsForTask = (- taskName: () => string,- allTaskRuns: () => TaskRun[]-): ComputedRef<TaskRun[]> => {- return computed(() => {- const name = taskName();- const prefix = `${name}/taskRuns/`;- return allTaskRuns().filter((run) => run.name.startsWith(prefix));- });-};diff --git a/frontend/src/components/RolloutV1/index.ts b/frontend/src/components/RolloutV1/index.tsindex 43ce2899f9..04aef1a889 100644--- a/frontend/src/components/RolloutV1/index.ts+++ b/frontend/src/components/RolloutV1/index.ts@@ -1,21 +1 @@-// Stage-export { default as StageContentView } from "./components/Stage/StageContentView.vue";-export { default as StageNavigationBar } from "./components/Stage/StageNavigationBar.vue";-export { default as StageTimeline } from "./components/Stage/StageTimeline.vue";--// Task-export { default as TaskItem } from "./components/Task/TaskItem.vue";-export { default as TaskList } from "./components/Task/TaskList.vue";-export { default as TaskTable } from "./components/Task/TaskTable.vue";-export { default as TaskView } from "./components/Task/TaskView.vue";-export { default as TaskFilter } from "./components/Task/TaskFilter.vue";-export { default as TaskToolbar } from "./components/Task/TaskToolbar.vue";-export { default as TaskRolloutActionPanel } from "./components/Task/TaskRolloutActionPanel.vue";-export { default as TaskStatusActions } from "./components/Task/TaskStatusActions.vue";--// TaskRun-export { default as TaskRunTable } from "./components/TaskRun/TaskRunTable.vue";-export * from "./components/TaskRun/TaskRunLogViewer";--// Constantsexport * from "./constants/task";diff --git a/frontend/src/components/TableDetailDrawer.vue b/frontend/src/components/TableDetailDrawer.vueindex 1cce98434a..2bf492566a 100644--- a/frontend/src/components/TableDetailDrawer.vue+++ b/frontend/src/components/TableDetailDrawer.vue@@ -63,14 +63,15 @@><DatabaseV1Name :database="database" /></dd>- <SQLEditorButtonV1+ <buttonv-if="allowQuery"- class="text-sm md:mr-4"- :database="database"- :schema="schemaName"- :table="tableName"- :label="true"- />+ type="button"+ class="flex items-center text-sm textlabel cursor-pointer hover:text-accent md:mr-4 border-0 bg-transparent p-0"+ @click.stop.prevent="gotoSQLEditor"+ >+ <span class="mr-1">{{ $t("sql-editor.self") }}</span>+ <heroicons-solid:terminal class="w-5 h-5" />+ </button><NPopovertrigger="click"placement="bottom"@@ -310,6 +311,7 @@ import { CodeIcon } from "lucide-vue-next";import { NButton, NInput, NPopover } from "naive-ui";import { computed, reactive, ref, watch } from "vue";import { useI18n } from "vue-i18n";+import { useRouter } from "vue-router";import ClassificationCell from "@/components/ColumnDataTable/ClassificationCell.vue";import TableSchemaViewer from "@/components/TableSchemaViewer.vue";import {@@ -355,7 +357,7 @@ import {supportGetStringSchema,} from "@/utils";import ColumnDataTable from "./ColumnDataTable/index.vue";-import { SQLEditorButtonV1 } from "./DatabaseDetail";+import { openSQLEditorForDatabase } from "./DatabaseDetail/sqlEditor";import IndexTable from "./IndexTable.vue";import MaskSpinner from "./misc/MaskSpinner.vue";import PartitionTablesDataTable from "./PartitionTablesDataTable.vue";@@ -386,6 +388,7 @@ const { t } = useI18n();const databaseV1Store = useDatabaseV1Store();const dbSchemaStore = useDBSchemaV1Store();const catalogStore = useDatabaseCatalogV1Store();+const router = useRouter();const databaseCatalog = useDatabaseCatalog(props.databaseName, false);const tableCatalog = computed(() =>@@ -531,6 +534,15 @@ const allowQuery = computed(() => {return isDatabaseV1Queryable(database.value);});+const gotoSQLEditor = () => {+ openSQLEditorForDatabase({+ router,+ database: database.value,+ schema: props.schemaName,+ table: props.tableName,+ });+};+const hasPartitionTables = computed(() => {return (// Only show partition tables for PostgreSQL.diff --git a/frontend/src/components/WorkspaceInstanceLicenseStats.vue b/frontend/src/components/WorkspaceInstanceLicenseStats.vueindex 98e26693a5..a946a48685 100644--- a/frontend/src/components/WorkspaceInstanceLicenseStats.vue+++ b/frontend/src/components/WorkspaceInstanceLicenseStats.vue@@ -21,38 +21,28 @@<template #icon><PencilIconclass="h-8 w-8"- @click="state.showInstanceAssignmentDrawer = true"+ @click="gotoInstanceAssignment"/></template></NButton></template></div></div>-- <InstanceAssignment- :show="state.showInstanceAssignmentDrawer"- @dismiss="state.showInstanceAssignmentDrawer = false"- /></template><script lang="ts" setup>import { PencilIcon } from "lucide-vue-next";import { NButton } from "naive-ui";import { storeToRefs } from "pinia";-import { computed, reactive } from "vue";+import { computed } from "vue";import { useI18n } from "vue-i18n";-import InstanceAssignment from "@/components/InstanceAssignment.vue";+import { useRouter } from "vue-router";+import { INSTANCE_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";import { useActuatorV1Store, useSubscriptionV1Store } from "@/store";import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";-interface LocalState {- showInstanceAssignmentDrawer: boolean;-}-const { t } = useI18n();-const state = reactive<LocalState>({- showInstanceAssignmentDrawer: false,-});+const router = useRouter();const subscriptionStore = useSubscriptionV1Store();const actuatorStore = useActuatorV1Store();@@ -68,4 +58,13 @@ const totalLicenseCount = computed((): string => {const activateLicenseCount = computed((): string => {return `${actuatorStore.activatedInstanceCount}`;});++const gotoInstanceAssignment = () => {+ router.push({+ name: INSTANCE_ROUTE_DASHBOARD,+ query: {+ assignLicense: "1",+ },+ });+};</script>diff --git a/frontend/src/components/v2/Model/Instance/InstanceV1Table/InstanceOperations.vue b/frontend/src/components/v2/Model/Instance/InstanceV1Table/InstanceOperations.vueindex effaccff1a..27ec0fad96 100644--- a/frontend/src/components/v2/Model/Instance/InstanceV1Table/InstanceOperations.vue+++ b/frontend/src/components/v2/Model/Instance/InstanceV1Table/InstanceOperations.vue@@ -34,12 +34,6 @@</PermissionGuardWrapper></div></div>- <InstanceAssignment- :show="state.showAssignLicenseDrawer"- :selected-instance-list="instanceList.map((ins) => ins.name)"- @dismiss="state.showAssignLicenseDrawer = false"- />-<EditEnvironmentDrawer:show="state.showEditEnvironmentDrawer"@dismiss="state.showEditEnvironmentDrawer = false"@@ -55,10 +49,11 @@ import { NButton } from "naive-ui";import type { VNode } from "vue";import { computed, h, reactive } from "vue";import { useI18n } from "vue-i18n";+import { useRouter } from "vue-router";import EditEnvironmentDrawer from "@/components/EditEnvironmentDrawer.vue";import InstanceSyncButton from "@/components/Instance/InstanceSyncButton.vue";-import InstanceAssignment from "@/components/InstanceAssignment.vue";import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";+import { INSTANCE_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";import {pushNotification,useInstanceV1Store,@@ -80,7 +75,6 @@ interface Action {interface LocalState {loading: boolean;- showAssignLicenseDrawer: boolean;showEditEnvironmentDrawer: boolean;}@@ -93,11 +87,11 @@ const emit = defineEmits<{}>();const { t } = useI18n();+const router = useRouter();const instanceStore = useInstanceV1Store();const subscriptionStore = useSubscriptionV1Store();const state = reactive<LocalState>({loading: false,- showAssignLicenseDrawer: false,showEditEnvironmentDrawer: false,});@@ -135,7 +129,16 @@ const actions = computed((): Action[] => {list.push({icon: h(GraduationCapIcon),text: t("subscription.instance-assignment.assign-license"),- click: () => (state.showAssignLicenseDrawer = true),+ click: () =>+ router.push({+ name: INSTANCE_ROUTE_DASHBOARD,+ query: {+ assignLicense: "1",+ instances: props.instanceList+ .map((instance) => instance.name)+ .join(","),+ },+ }),requiredPermissions: ["bb.instances.update", "bb.settings.get"],});}diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex eb533a0fc5..6c83ade0e6 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -335,7 +335,6 @@"labels": "Labels","language": "Language","lark": "Lark",- "latest": "Latest","learn-more": "Learn more","leave": "Leave","leave-without-saving": "Leave without saving?",@@ -357,11 +356,9 @@"no-data": "No data","no-license": "No license","not-started": "Not Started",- "notices": "Notices","off": "Off","ok": "OK","on": "On",- "only-creator-allowed-action": "Only the creator is allowed to take action","only-creator-allowed-export": "Only the creator is allowed to export","operation": "Operation","operations": "Operations",@@ -460,7 +457,6 @@"untitled": "Untitled","update": "Update","updated": "Updated",- "updated-at": "Updated","upload": "Upload","user": "User","username": "Username",@@ -521,8 +517,7 @@"approved-issue": "approved issue","disallow-approve-reason": {"some-task-checks-are-still-running": "Some task checks are still running.",- "some-task-checks-didnt-pass": "Some task checks didn't pass.",- "x-field-is-required": "{field} is required"+ "some-task-checks-didnt-pass": "Some task checks didn't pass."},"generating-approval-flow": "Generating approval flow","re-request-review": "Re-request review",@@ -646,7 +641,6 @@"edit-labels": "Edit Labels","edit-schema": "Edit Schema","engine": "Engine",- "engine-not-supported-for-backup": "Prior backup is not supported for: {databases}","export-schema": "Export Schema","export-schema-multi-file": "Multi-File (ZIP)","export-schema-single-file": "Single File",@@ -1172,9 +1166,6 @@"search": "Input title or id to search","self": "Advanced search"},- "approval": {- "approved-and-waiting-for-rollout": "This issue has been approved and is ready to rollout."- },"approval-flow": {"self": "Approval flow"},@@ -1207,17 +1198,9 @@"limits": "Limits","options": "Options"},- "error": {- "statement-cannot-be-modified": "Statement cannot be modified after the issue is created"- },"issue-name": "Issue name","labels": "Issue Labels","leave-a-comment": "Leave a comment...",- "migration-mode": {- "online": {- "description": "Based on gh-ost. For large tables, it can reduce the table lock duration from hours to seconds {link}."- }- },"my-issues": "My Issues","no-description-provided": "No description provided","options-disabled-due-to-oversize": "Options are disabled because the SQL is oversized.",@@ -1255,8 +1238,6 @@},"sql-check": {"back-to-edit": "Back to edit",- "not-executed-yet": "Not executed yet",- "sql-checks": "SQL checks","sql-review-violations": "SQL Review Violations","statement-is-required": "SQL statement is required","statement-is-too-large": "As the current statement size exceeds 2MB, the SQL check will be skipped."@@ -1281,18 +1262,7 @@},"task-run": {"logs": "Logs",- "session": "Session",- "task-run-session": {- "blocked-sessions": {- "description": "The sessions that are blocked by the current session",- "self": "Blocked sessions"- },- "blocking-sessions": {- "description": "The sessions that are blocking the current session",- "self": "Blocking sessions"- },- "no-session-found": "No session found."- }+ "session": "Session"},"title": {"change-database": "Change database",@@ -1303,10 +1273,7 @@"request-specific-role": "Request \"{role}\" role"},"transaction-mode": {- "execution-order-note": "Non-transactional statements will be executed last.",- "label": "Transaction Mode",- "off-tooltip": "Executes statements individually in auto-commit mode. Statements are committed immediately and cannot be rolled back if a later statement fails.",- "on-tooltip": "Wraps all statements in a single transaction (BEGIN/COMMIT)."+ "label": "Transaction Mode"},"unfinished-resolved-issue-tips": "This issue is marked as \"Done\" but some of its tasks are not executed successfully.","upload-sql": "Upload SQL",@@ -1385,16 +1352,8 @@"unsaved-changes": "Unsaved Changes","unsaved-changes-message": "You have unsaved changes. Are you sure you want to leave?"},- "ghost": {- "configuration-has-issues": "Configuration has {count} issue | Configuration has {count} issues",- "missing-backup-database": "Create database 'bbdataarchive' on instance '{instance}', then sync the instance and database",- "only-some-databases-checked": "Only some databases are checked",- "some-databases-have-issues": "{count} database has issues | {count} databases have issues",- "some-databases-not-meeting-requirements": "Some databases ({databases}) don't meet requirements"- },"go-to-plan-page": "Go to Plan page","isolation-level": {- "description": "Controls how transactions interact with concurrent changes. Only applicable when Transaction Mode is ON.","self": "Isolation Level"},"labels-required-for-review": "Labels are required before requesting review",@@ -1432,19 +1391,7 @@"show-details": "Show details ↓"},"plans": "Plans",- "pre-backup": {- "configuration-has-issues": "Configuration has {count} issue | Configuration has {count} issues",- "missing-backup-database": "Create database 'bbdataarchive' on instance '{instance}', then sync the instance and database",- "missing-backup-database-oracle": "Create database 'BBDATAARCHIVE' on instance '{instance}', then sync the instance and database",- "missing-backup-schema-postgres": "Create schema 'bbdataarchive' in database '{database}'. If using SET ROLE, grant USAGE and CREATE on the schema to that role. Then sync the database",- "only-some-databases-checked": "Only some databases are checked",- "some-databases-have-issues": "{count} database has issues | {count} databases have issues",- "some-databases-not-meeting-requirements": "Some databases ({databases}) don't meet requirements"- },"ready-for-review": "Ready for Review",- "refresh-indicator": {- "last-refresh": "Last refresh: {time}"- },"run": "Run checks","select-isolation-level": "Select isolation level","select-targets": "Select Targets",@@ -1454,15 +1401,6 @@},"spec": {"change": "Change",- "delete-change": {- "content": "Are you sure you want to delete this change?",- "title": "Delete Change"- },- "role-selection": {- "description": "Choose which PostgreSQL role to execute this statement as.",- "technical-note": "Adds \"SET ROLE {role};\" to your SQL statement.",- "title": "Database Role Selection"- },"type": {"create-database": "Create Database","database-change": "Database Change",@@ -1759,7 +1697,6 @@"files": "Files","not-found": "Not found","releases": "Releases",- "title": "Release","total-files": "Total {count} files","usage-description": "A release is a versioned application artifact whose deployment to an environment is triggered by a GitOps workflow.","vcs-source": "VCS Source",@@ -1876,7 +1813,6 @@"self": "Stage | Stages"},"task": {- "no-statement": "No SQL statement","no-tasks": "No tasks in this stage","selected-count": "{count} task selected | {count} tasks selected","statement-truncated-hint": "Statement truncated due to large size."@@ -1937,7 +1873,6 @@"indexes": "Indexes","unique": "Unique"},- "insert-sql": "Insert SQL","message": {"cannot-drop-the-last-column": "Cannot drop the last column","duplicated-function-name": "Duplicated function name",@@ -1960,7 +1895,6 @@"select": "Select schema"},"search-database-and-table": "Search database and table",- "self": "Schema Editor","table": {"name": "Table Name","select": "Select table"@@ -1974,7 +1908,6 @@"value": "Value"},"tables": "Tables",- "template-database": "Template database","views": "Views"},"schema-template": {@@ -2764,8 +2697,7 @@"rule-detail": "Rule detail","select-all": "Select all","select-review-rules": "Select SQL review rules",- "title": "SQL Review",- "view-definition": "View definition"+ "title": "SQL Review"},"subscription": {"button": {@@ -2891,7 +2823,6 @@"summary-report": "Summary report"},"checking": "Checking...",- "comment": "Comment","created": "Created","data-export-creator-only": "Only the issue creator can execute data export tasks","error": {@@ -2899,7 +2830,6 @@},"executed-by": "Executed by","execution-time": "Execution time",- "no-cancellable-tasks": "No cancellable tasks","no-permission": "No permission to perform this action","no-runnable-tasks": "No runnable tasks","no-selectable-tasks": "No tasks can be selected",@@ -2907,20 +2837,10 @@"no-tasks-selected": "No tasks selected","online-migration": {"advice-split-statement-to-single-online-migration-issue": "Advice splitting this statement to single online migration issue.",- "configure": "Configure",- "configure-ghost-parameters": "Configure gh-ost parameters",- "error": {- "not-applicable": {- "database-doesnt-meet-ghost-requirement": "Database {database} doesn't meet gh-ost's requirement"- },- "nothing-changed": "Nothing changed"- },- "ghost-parameters": "gh-ost parameters","self": "Online migration"},"only-showing-latest-n-runs": "Only showing latest {n} runs","prior-backup": "Prior backup",- "prior-backup-tips": "Backup affected data ahead of time. Only applies to data changes (UPDATE, DELETE), not schema changes.","run-checks": "Run checks","run-history": "Run History","run-immediately": {@@ -2932,7 +2852,6 @@"description": "Set a specific date and time for tasks to automatically start running. Useful for maintenance windows or off-peak hours.","self": "Schedule for later"},- "scheduled-at": "Scheduled at","scheduled-time": "Scheduled time","select-scheduled-time": "Select scheduled time","select-task": "Select task | Select tasks",@@ -2949,17 +2868,9 @@"pending": "Pending","running": "Running","skipped": "Skipped"- },- "task-checks": "Task checks",- "type": {- "database-create": "Create Database",- "database-export": "Data Export",- "general": "General",- "migrate": "Migrate"}},"task-run": {- "failed-runs": "Failed Tasks - Latest Execution Logs","history": "Execution History","latest": "Latest Execution","latest-logs": "Latest Logs",@@ -2992,8 +2903,7 @@"available": "Rollback available for {n} task | Rollback available for {n} tasks","no-statement-generated": "No rollback statement generated","preview-statement": {- "description": "Bytebase generates a rollback statement based on the task run. You can review the statement before executing the rollback.",- "self": "Preview Statement"+ "description": "Bytebase generates a rollback statement based on the task run. You can review the statement before executing the rollback."}},"status": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 3b315ea285..5d5d934eea 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -335,7 +335,6 @@"labels": "Etiquetas","language": "Idioma","lark": "Lark",- "latest": "Último","learn-more": "Aprender más","leave": "Dejar","leave-without-saving": "¿Salir sin guardar?",@@ -357,11 +356,9 @@"no-data": "Sin datos","no-license": "Sin licencia","not-started": "No iniciado",- "notices": "Avisos","off": "Apagado","ok": "OK","on": "Encendido",- "only-creator-allowed-action": "Solo el creador puede realizar esta acción","only-creator-allowed-export": "Solo el creador puede exportar","operation": "Operación","operations": "Operaciones",@@ -460,7 +457,6 @@"untitled": "Sin título","update": "Actualizar","updated": "Actualizado",- "updated-at": "Actualizado","upload": "Subir","user": "Usuario","username": "Nombre de usuario",@@ -521,8 +517,7 @@"approved-issue": "incidencia aprobada","disallow-approve-reason": {"some-task-checks-are-still-running": "Algunas comprobaciones de tareas aún se están ejecutando",- "some-task-checks-didnt-pass": "Algunas comprobaciones de tareas no pasaron",- "x-field-is-required": "{field} se requiere"+ "some-task-checks-didnt-pass": "Algunas comprobaciones de tareas no pasaron"},"generating-approval-flow": "Generando flujo de aprobación","re-request-review": "Volver a solicitar revisión",@@ -646,7 +641,6 @@"edit-labels": "Editar etiquetas","edit-schema": "Modificar esquema","engine": "Motor",- "engine-not-supported-for-backup": "No se admite la copia de seguridad previa para: {databases}","export-schema": "Exportar esquema","export-schema-multi-file": "Multi-archivo (ZIP)","export-schema-single-file": "Archivo único",@@ -1172,9 +1166,6 @@"search": "Ingrese título o id para buscar","self": "Búsqueda Avanzada"},- "approval": {- "approved-and-waiting-for-rollout": "Este problema ha sido aprobado y está listo para implementarse."- },"approval-flow": {"self": "Flujo de aprobación"},@@ -1207,17 +1198,9 @@"limits": "Límites","options": "Opciones de exportación"},- "error": {- "statement-cannot-be-modified": "La declaración no se puede modificar una vez creado el problema"- },"issue-name": "Nombre de la incidencia","labels": "Etiquetas de problema","leave-a-comment": "Dejar un comentario...",- "migration-mode": {- "online": {- "description": "Basado en gh-ost. Para tablas grandes, puede reducir la duración del bloqueo de la tabla de horas a segundos {link}."- }- },"my-issues": "Mis Incidencias","no-description-provided": "No se proporcionó ninguna descripción","options-disabled-due-to-oversize": "Las opciones están deshabilitadas porque el SQL es demasiado grande.",@@ -1255,8 +1238,6 @@},"sql-check": {"back-to-edit": "Volver a editar",- "not-executed-yet": "Aún no ejecutado",- "sql-checks": "Comprobaciones SQL","sql-review-violations": "Infracciones de revisión de SQL","statement-is-required": "Se requiere una declaración SQL","statement-is-too-large": "Como el tamaño de la declaración actual supera 2MB, se omitirá la comprobación de SQL."@@ -1281,18 +1262,7 @@},"task-run": {"logs": "Registros",- "session": "Sesión",- "task-run-session": {- "blocked-sessions": {- "description": "Las sesiones que están bloqueadas por la sesión actual.",- "self": "Sesiones bloqueadas"- },- "blocking-sessions": {- "description": "Las sesiones que están bloqueando la sesión actual.",- "self": "Sesiones de bloqueo"- },- "no-session-found": "No se encontró ninguna sesión."- }+ "session": "Sesión"},"title": {"change-database": "Modificar base de datos",@@ -1303,10 +1273,7 @@"request-specific-role": "Solicitar rol \"{role}\""},"transaction-mode": {- "execution-order-note": "Las declaraciones no transaccionales se ejecutarán en último lugar.",- "label": "Modo de transacción",- "off-tooltip": "Ejecuta declaraciones individualmente en modo de confirmación automática. Las declaraciones se confirman inmediatamente y no se pueden revertir si una declaración posterior falla.",- "on-tooltip": "Envuelve todas las declaraciones en una sola transacción (BEGIN/COMMIT)."+ "label": "Modo de transacción"},"unfinished-resolved-issue-tips": "Este problema está marcado como \"Aprobado\", pero algunas de sus tareas no se ejecutan correctamente.","upload-sql": "Cargar SQL",@@ -1385,16 +1352,8 @@"unsaved-changes": "Cambios no guardados","unsaved-changes-message": "Tienes cambios sin guardar. ¿Estás seguro de que quieres salir?"},- "ghost": {- "configuration-has-issues": "La configuración tiene {count} problemas | La configuración tiene {count} problemas",- "missing-backup-database": "Cree la base de datos 'bbdataarchive' en la instancia '{instance}', luego sincronice la instancia y la base de datos",- "only-some-databases-checked": "Sólo se comprueban algunas bases de datos",- "some-databases-have-issues": "{count} la base de datos tiene problemas | {count} las bases de datos tienen problemas",- "some-databases-not-meeting-requirements": "Algunas bases de datos ({databases}) no cumplen los requisitos"- },"go-to-plan-page": "Ir a la página del plan","isolation-level": {- "description": "Controla cómo las transacciones interactúan con cambios concurrentes. Solo aplica cuando el Modo de Transacción está activado.","self": "Nivel de Aislamiento"},"labels-required-for-review": "Se requieren etiquetas antes de solicitar revisión",@@ -1432,19 +1391,7 @@"show-details": "Mostrar detalles ↓"},"plans": "Planes",- "pre-backup": {- "configuration-has-issues": "La configuración tiene {count} problemas | La configuración tiene {count} problemas",- "missing-backup-database": "Cree la base de datos 'bbdataarchive' en la instancia '{instance}', luego sincronice la instancia y la base de datos",- "missing-backup-database-oracle": "Cree la base de datos 'BBDATAARCHIVE' en la instancia '{instance}', luego sincronice la instancia y la base de datos",- "missing-backup-schema-postgres": "Cree el esquema 'bbdataarchive' en la base de datos '{database}'. Si usa SET ROLE, otorgue USAGE y CREATE en el esquema a ese rol. Luego sincronice la base de datos",- "only-some-databases-checked": "Sólo se comprueban algunas bases de datos",- "some-databases-have-issues": "{count} la base de datos tiene problemas | {count} las bases de datos tienen problemas",- "some-databases-not-meeting-requirements": "Algunas bases de datos ({databases}) no cumplen los requisitos"- },"ready-for-review": "Listo para revisión",- "refresh-indicator": {- "last-refresh": "Última actualización: {time}"- },"run": "Volver a verificar","select-isolation-level": "Seleccionar nivel de aislamiento","select-targets": "Seleccionar objetivos",@@ -1454,15 +1401,6 @@},"spec": {"change": "Cambiar",- "delete-change": {- "content": "¿Está seguro de que desea eliminar este cambio?",- "title": "Eliminar cambio"- },- "role-selection": {- "description": "Elija qué rol de PostgreSQL desea ejecutar como esta declaración.",- "technical-note": "Agrega \"SET ROLE {role};\" a su declaración SQL.",- "title": "Selección de roles de base de datos"- },"type": {"create-database": "Crear base de datos","database-change": "Cambio de base de datos",@@ -1759,7 +1697,6 @@"files": "Archivos","not-found": "Extraviado","releases": "Lanzamientos",- "title": "Liberar","total-files": "Total de {count} archivos","usage-description": "Un lanzamiento es un artefacto de aplicación versionado cuyo despliegue a un entorno es activado por un flujo de trabajo GitOps.","vcs-source": "Fuente VCS",@@ -1876,7 +1813,6 @@"self": "Etapa | Etapas"},"task": {- "no-statement": "Declaración sin SQL","no-tasks": "No hay tareas en esta etapa","selected-count": "{count} tarea seleccionada | {count} tareas seleccionadas","statement-truncated-hint": "Declaración truncada debido al gran tamaño."@@ -1937,7 +1873,6 @@"indexes": "Índices","unique": "Único"},- "insert-sql": "Insert SQL","message": {"cannot-drop-the-last-column": "No se puede eliminar la última columna","duplicated-function-name": "Nombre de función duplicado",@@ -1960,7 +1895,6 @@"select": "Seleccionar esquema"},"search-database-and-table": "Buscar base de datos y tabla",- "self": "Editor de esquema","table": {"name": "Nombre de la tabla","select": "Seleccionar tabla"@@ -1974,7 +1908,6 @@"value": "Valor"},"tables": "Tablas",- "template-database": "Template database","views": "Vistas"},"schema-template": {@@ -2764,8 +2697,7 @@"rule-detail": "Detalle de la regla","select-all": "Seleccionar todo","select-review-rules": "Seleccionar reglas de revisión de SQL",- "title": "Revisión de SQL",- "view-definition": "Ver definición"+ "title": "Revisión de SQL"},"subscription": {"button": {@@ -2891,7 +2823,6 @@"summary-report": "Informe resumido"},"checking": "Comprobando...",- "comment": "Comentario","created": "Creado","data-export-creator-only": "Sólo el creador del problema puede ejecutar tareas de exportación de datos","error": {@@ -2899,7 +2830,6 @@},"executed-by": "Ejecutado por","execution-time": "Tiempo de ejecución",- "no-cancellable-tasks": "No hay tareas cancelables","no-permission": "No hay permiso para realizar esta acción","no-runnable-tasks": "No hay tareas ejecutables","no-selectable-tasks": "No se puede seleccionar ninguna tarea.",@@ -2907,20 +2837,10 @@"no-tasks-selected": "No hay tareas seleccionadas","online-migration": {"advice-split-statement-to-single-online-migration-issue": "Se recomienda dividir esta declaración en un único problema de migración en línea.",- "configure": "Configurar",- "configure-ghost-parameters": "Configurar los parámetros de gh-ost",- "error": {- "not-applicable": {- "database-doesnt-meet-ghost-requirement": "La base de datos {database} no cumple con el requisito de gh-ost"- },- "nothing-changed": "nada ha cambiado"- },- "ghost-parameters": "parámetros de gh-ost","self": "Migración en línea"},"only-showing-latest-n-runs": "Solo se muestran las últimas {n} ejecuciones","prior-backup": "Respaldo previo",- "prior-backup-tips": "Copia de seguridad de los datos afectados con anticipación. Solo aplica a cambios de datos (UPDATE, DELETE), no a cambios de esquema.","run-checks": "Ejecutar comprobaciones","run-history": "Historial de ejecución","run-immediately": {@@ -2932,7 +2852,6 @@"description": "Establezca una fecha y hora específicas para que las tareas comiencen a ejecutarse automáticamente. Útil para periodos de mantenimiento o horas de baja demanda.","self": "Programar para más tarde"},- "scheduled-at": "Programado en","scheduled-time": "Hora programada","select-scheduled-time": "Seleccionar hora programada","select-task": "Seleccionar tarea | Seleccionar tareas",@@ -2949,17 +2868,9 @@"pending": "Pendiente","running": "Ejecutándose","skipped": "Omitido"- },- "task-checks": "Comprobaciones de tarea",- "type": {- "database-create": "Crear base de datos",- "database-export": "Exportar datos",- "general": "General",- "migrate": "Migrar"}},"task-run": {- "failed-runs": "Tareas fallidas: últimos registros de ejecución","history": "Historial de ejecución de tareas","latest": "Última ejecución","latest-logs": "Últimos registros",@@ -2992,8 +2903,7 @@"available": "Reversión disponible para {n} tarea | Reversión disponible para {n} tareas","no-statement-generated": "No se generó ninguna declaración de reversión","preview-statement": {- "description": "Bytebase genera una sentencia de reversión según la ejecución de la tarea. Puede revisar la sentencia antes de ejecutar la reversión.",- "self": "Declaración de vista previa"+ "description": "Bytebase genera una sentencia de reversión según la ejecución de la tarea. Puede revisar la sentencia antes de ejecutar la reversión."}},"status": {diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 01309b5447..b089cf88df 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -335,7 +335,6 @@"labels": "ラベル","language": "言語","lark": "Lark",- "latest": "最新の","learn-more": "もっと詳しく知る","leave": "離れる","leave-without-saving": "変更を保存していませんか?",@@ -357,11 +356,9 @@"no-data": "データなし","no-license": "ライセンスがありません","not-started": "未開始",- "notices": "注意事項","off": "オフ","ok": "わかりました","on": "オン",- "only-creator-allowed-action": "この操作は作成者のみが実行できます","only-creator-allowed-export": "エクスポートは作成者のみが実行できます","operation": "操作","operations": "操作",@@ -460,7 +457,6 @@"untitled": "名前のない","update": "更新する","updated": "更新しました",- "updated-at": "更新日時","upload": "アップロード","user": "ユーザー","username": "ユーザー名",@@ -521,8 +517,7 @@"approved-issue": "イシューを承認する","disallow-approve-reason": {"some-task-checks-are-still-running": "確認すべき実行中のタスクがまだあります",- "some-task-checks-didnt-pass": "失敗したタスクチェックがまだあります",- "x-field-is-required": "{field}は必須です"+ "some-task-checks-didnt-pass": "失敗したタスクチェックがまだあります"},"generating-approval-flow": "承認フローが生成されています","re-request-review": "再度承認をリクエストする",@@ -646,7 +641,6 @@"edit-labels": "タグを編集する","edit-schema": "スキーマの変更","engine": "エンジン",- "engine-not-supported-for-backup": "以前のバックアップはサポートされていません: {databases}","export-schema": "スキーマをエクスポート","export-schema-multi-file": "複数ファイル (ZIP)","export-schema-single-file": "単一ファイル",@@ -1172,9 +1166,6 @@"search": "検索するにはタイトルまたはIDを入力してください","self": "高度な検索"},- "approval": {- "approved-and-waiting-for-rollout": "このイシューは承認されており、展開する準備ができています。"- },"approval-flow": {"self": "承認の流れ"},@@ -1207,17 +1198,9 @@"limits": "制限","options": "設定項目"},- "error": {- "statement-cannot-be-modified": "イシューの作成後にステートメントを変更することはできません"- },"issue-name": "イシュー名","labels": "イシューラベル","leave-a-comment": "コメントを残す…",- "migration-mode": {- "online": {- "description": "gh-ostをベースにしています。大規模なテーブルの場合、テーブルのロック時間を数時間から数秒 {link} に短縮できます。"- }- },"my-issues": "マイイシュー","no-description-provided": "説明なし","options-disabled-due-to-oversize": "SQL が大きすぎるため、オプションは無効になっています。",@@ -1255,8 +1238,6 @@},"sql-check": {"back-to-edit": "編集に戻る",- "not-executed-yet": "まだ実行されていません",- "sql-checks": "SQLチェック項目","sql-review-violations": "SQL レビュールール違反","statement-is-required": "SQL文が必要です","statement-is-too-large": "現在のステートメント サイズが 1MB を超えているため、SQL チェックはスキップされます。"@@ -1281,18 +1262,7 @@},"task-run": {"logs": "ログ",- "session": "セッション",- "task-run-session": {- "blocked-sessions": {- "description": "現在のセッションによってブロックされているセッション",- "self": "ブロックされたセッション"- },- "blocking-sessions": {- "description": "現在のセッションをブロックしているセッション",- "self": "セッションのブロック"- },- "no-session-found": "セッションが見つかりません。"- }+ "session": "セッション"},"title": {"change-database": "データベースの変更",@@ -1303,10 +1273,7 @@"request-specific-role": "「{role}」ロールをリクエスト"},"transaction-mode": {- "execution-order-note": "非トランザクション ステートメントは最後に実行されます。",- "label": "トランザクションモード",- "off-tooltip": "自動コミットモードで個別にステートメントを実行します。ステートメントは即座にコミットされ、後続のステートメントが失敗してもロールバックできません。",- "on-tooltip": "すべてのステートメントを単一のトランザクション(BEGIN/COMMIT)でラップします。"+ "label": "トランザクションモード"},"unfinished-resolved-issue-tips": "イシューは「承認済み」とマークされましたが、一部のタスクは正常に実行されませんでした。","upload-sql": "SQLのアップロード",@@ -1385,16 +1352,8 @@"unsaved-changes": "保存されていない変更","unsaved-changes-message": "保存されていない変更があります。終了してもよろしいですか?"},- "ghost": {- "configuration-has-issues": "構成に {count} 個の問題があります | 構成に {count} 個の問題があります",- "missing-backup-database": "インスタンス '{instance}' にデータベース 'bbdataarchive' を作成し、インスタンスとデータベースを同期してください",- "only-some-databases-checked": "一部のデータベースのみがチェックされます",- "some-databases-have-issues": "{count} データベースに問題があります | {count} データベースに問題があります",- "some-databases-not-meeting-requirements": "一部のデータベース ({databases}) は要件を満たしていません"- },"go-to-plan-page": "プランページへ移動","isolation-level": {- "description": "トランザクションが並行変更とどのように相互作用するかを制御します。トランザクションモードがオンの場合のみ適用されます。","self": "分離レベル"},"labels-required-for-review": "レビューをリクエストする前にラベルが必要です",@@ -1432,19 +1391,7 @@"show-details": "詳細を表示 ↓"},"plans": "プラン",- "pre-backup": {- "configuration-has-issues": "構成に {count} 個の問題があります | 構成に {count} 個の問題があります",- "missing-backup-database": "インスタンス '{instance}' にデータベース 'bbdataarchive' を作成し、インスタンスとデータベースを同期してください",- "missing-backup-database-oracle": "インスタンス '{instance}' にデータベース 'BBDATAARCHIVE' を作成し、インスタンスとデータベースを同期してください",- "missing-backup-schema-postgres": "データベース '{database}' にスキーマ 'bbdataarchive' を作成してください。SET ROLE を使用している場合は、そのロールにスキーマの USAGE と CREATE 権限を付与してください。その後、データベースを同期してください",- "only-some-databases-checked": "一部のデータベースのみがチェックされます",- "some-databases-have-issues": "{count} データベースに問題があります | {count} データベースに問題があります",- "some-databases-not-meeting-requirements": "一部のデータベース ({databases}) は要件を満たしていません"- },"ready-for-review": "レビュー準備完了",- "refresh-indicator": {- "last-refresh": "最終更新: {time}"- },"run": "再チェック","select-isolation-level": "分離レベルを選択","select-targets": "ターゲットを選択",@@ -1454,15 +1401,6 @@},"spec": {"change": "変化",- "delete-change": {- "content": "この変更を削除してもよろしいですか?",- "title": "削除変更"- },- "role-selection": {- "description": "このステートメントを実行する PostgreSQL ロールを選択します。",- "technical-note": "SQL ステートメントに「SET ROLE {role};」を追加します。",- "title": "データベースロールの選択"- },"type": {"create-database": "データベースの作成","database-change": "データベースの変更",@@ -1759,7 +1697,6 @@"files": "ファイル","not-found": "配信パケットが到着していません","releases": "リリース",- "title": "リリース","total-files": "合計 {count} ファイル","usage-description": "リリースは、GitOpsワークフローによって環境へのデプロイがトリガーされるバージョン管理されたアプリケーションアーティファクトです。","vcs-source": "VCSソース",@@ -1876,7 +1813,6 @@"self": "ステージ | ステージ"},"task": {- "no-statement": "SQL文なし","no-tasks": "このステージにはタスクはありません","selected-count": "{count} 個のタスクが選択されました | {count} 個のタスクが選択されました","statement-truncated-hint": "サイズが大きいため、ステートメントは切り捨てられました。"@@ -1937,7 +1873,6 @@"indexes": "索引","unique": "唯一"},- "insert-sql": "Insert SQL","message": {"cannot-drop-the-last-column": "最後の列は削除できません","duplicated-function-name": "関数名が重複しています",@@ -1960,7 +1895,6 @@"select": "スキーマの選択"},"search-database-and-table": "データベースとテーブルを検索する",- "self": "スキーマエディタ","table": {"name": "テーブル名","select": "テーブルの選択"@@ -1974,7 +1908,6 @@"value": "値"},"tables": "テーブル",- "template-database": "Template database","views": "ビュー"},"schema-template": {@@ -2764,8 +2697,7 @@"rule-detail": "ルールの詳細","select-all": "すべて選択","select-review-rules": "SQL レビュールールを選択",- "title": "SQL レビューポリシー",- "view-definition": "ビューの定義"+ "title": "SQL レビューポリシー"},"subscription": {"button": {@@ -2891,7 +2823,6 @@"summary-report": "概略報告"},"checking": "検査中…",- "comment": "コメント","created": "内蔵","data-export-creator-only": "イシュー作成者のみがデータエクスポートタスクを実行できます","error": {@@ -2899,7 +2830,6 @@},"executed-by": "実行者","execution-time": "実行時間",- "no-cancellable-tasks": "キャンセル可能なタスクはありません","no-permission": "この操作を実行する権限がありません","no-runnable-tasks": "実行可能なタスクはありません","no-selectable-tasks": "タスクを選択できません",@@ -2907,20 +2837,10 @@"no-tasks-selected": "タスクが選択されていません","online-migration": {"advice-split-statement-to-single-online-migration-issue": "このステートメントを 1 つのオンライン移行イシューに分割することをアドバイスします。",- "configure": "設定",- "configure-ghost-parameters": "gh-ost パラメータを設定する",- "error": {- "not-applicable": {- "database-doesnt-meet-ghost-requirement": "データベース {database} は gh-ost の要件を満たしていません"- },- "nothing-changed": "変化なし"- },- "ghost-parameters": "gh-ostパラメータ","self": "オンラインでの大規模なテーブル変更"},"only-showing-latest-n-runs": "最新の {n} 実行のみを表示","prior-backup": "影響を受けるデータの事前バックアップ",- "prior-backup-tips": "影響を受けるデータを事前にバックアップします。データ変更(UPDATE、DELETE)のみに適用され、スキーマ変更には適用されません。","run-checks": "実行チェック","run-history": "実行履歴","run-immediately": {@@ -2932,7 +2852,6 @@"description": "タスクを自動的に実行開始する日時を指定します。メンテナンス期間やオフピーク時に便利です。","self": "後でスケジュールする"},- "scheduled-at": "予定日時","scheduled-time": "予定時刻","select-scheduled-time": "予定時刻を選択してください","select-task": "タスクを選択 | タスクを選択",@@ -2949,17 +2868,9 @@"pending": "保留中","running": "ランニング","skipped": "スキップ"- },- "task-checks": "タスクのチェック項目",- "type": {- "database-create": "データベース作成",- "database-export": "データエクスポート",- "general": "一般",- "migrate": "マイグレーション"}},"task-run": {- "failed-runs": "失敗したタスク - 最新の実行ログ","history": "タスク実行履歴","latest": "最新の実行","latest-logs": "最新のログ",@@ -2992,8 +2903,7 @@"available": "{n} タスクのロールバックが利用可能 | {n} タスクのロールバックが利用可能","no-statement-generated": "ロールバックステートメントは生成されません","preview-statement": {- "description": "Bytebaseはタスク実行に基づいてロールバックステートメントを生成します。ロールバックを実行する前にステートメントを確認できます。",- "self": "プレビューステートメント"+ "description": "Bytebaseはタスク実行に基づいてロールバックステートメントを生成します。ロールバックを実行する前にステートメントを確認できます。"}},"status": {diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 91ba44162e..af1d4c888b 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -335,7 +335,6 @@"labels": "Nhãn","language": "Ngôn ngữ","lark": "Lark",- "latest": "Mới nhất","learn-more": "Tìm hiểu thêm","leave": "Rời khỏi","leave-without-saving": "Thoát mà không lưu?",@@ -357,11 +356,9 @@"no-data": "Không có dữ liệu","no-license": "Không có giấy phép","not-started": "Chưa bắt đầu",- "notices": "Thông báo","off": "Tắt","ok": "OK","on": "Bật",- "only-creator-allowed-action": "Chỉ người tạo mới được phép thực hiện hành động này","only-creator-allowed-export": "Chỉ người tạo mới được phép xuất","operation": "Thao tác","operations": "Các thao tác",@@ -460,7 +457,6 @@"untitled": "Không tiêu đề","update": "Cập nhật","updated": "Đã cập nhật",- "updated-at": "Thời gian cập nhật","upload": "Tải lên","user": "Người dùng","username": "Tên người dùng",@@ -521,8 +517,7 @@"approved-issue": "đã phê duyệt vấn đề","disallow-approve-reason": {"some-task-checks-are-still-running": "Một số kiểm tra tác vụ vẫn đang chạy",- "some-task-checks-didnt-pass": "Một số kiểm tra tác vụ không vượt qua",- "x-field-is-required": "{field} là bắt buộc"+ "some-task-checks-didnt-pass": "Một số kiểm tra tác vụ không vượt qua"},"generating-approval-flow": "Đang tạo quy trình phê duyệt","re-request-review": "Yêu cầu xem xét lại",@@ -646,7 +641,6 @@"edit-labels": "Chỉnh sửa nhãn","edit-schema": "Chỉnh sửa lược đồ","engine": "Engine",- "engine-not-supported-for-backup": "Sao lưu trước đó không được hỗ trợ cho: {databases}","export-schema": "Xuất schema","export-schema-multi-file": "Nhiều tệp (ZIP)","export-schema-single-file": "Tệp đơn",@@ -1172,9 +1166,6 @@"search": "Nhập tiêu đề hoặc id để tìm kiếm","self": "Tìm kiếm nâng cao"},- "approval": {- "approved-and-waiting-for-rollout": "Phiên bản này đã được chấp thuận và sẵn sàng triển khai."- },"approval-flow": {"self": "Quy trình phê duyệt"},@@ -1207,17 +1198,9 @@"limits": "Giới hạn","options": "Tùy chọn"},- "error": {- "statement-cannot-be-modified": "Không thể sửa đổi câu lệnh sau khi vấn đề được tạo"- },"issue-name": "Tên vấn đề","labels": "Nhãn vấn đề","leave-a-comment": "Để lại bình luận...",- "migration-mode": {- "online": {- "description": "Dựa trên gh-ost. Đối với các bảng lớn, nó có thể giảm thời gian khóa bảng từ hàng giờ xuống còn vài giây {link}."- }- },"my-issues": "Vấn đề của tôi","no-description-provided": "Không có mô tả nào được cung cấp","options-disabled-due-to-oversize": "Các tùy chọn bị vô hiệu hóa vì SQL quá lớn.",@@ -1255,8 +1238,6 @@},"sql-check": {"back-to-edit": "Quay lại chỉnh sửa",- "not-executed-yet": "Chưa được thực hiện",- "sql-checks": "Kiểm tra SQL","sql-review-violations": "Vi phạm đánh giá SQL","statement-is-required": "Câu lệnh SQL là bắt buộc","statement-is-too-large": "Vì kích thước câu lệnh hiện tại vượt quá 2MB, việc kiểm tra SQL sẽ bị bỏ qua."@@ -1281,18 +1262,7 @@},"task-run": {"logs": "Nhật ký",- "session": "Phiên",- "task-run-session": {- "blocked-sessions": {- "description": "Các phiên bị chặn bởi phiên hiện tại",- "self": "Phiên bị chặn"- },- "blocking-sessions": {- "description": "Các phiên đang chặn phiên hiện tại",- "self": "Phiên chặn"- },- "no-session-found": "Không tìm thấy phiên."- }+ "session": "Phiên"},"title": {"change-database": "Thay đổi cơ sở dữ liệu",@@ -1303,10 +1273,7 @@"request-specific-role": "Yêu cầu vai trò \"{role}\""},"transaction-mode": {- "execution-order-note": "Các câu lệnh không liên quan đến giao dịch sẽ được thực hiện cuối cùng.",- "label": "Chế độ giao dịch",- "off-tooltip": "Thực thi các câu lệnh riêng lẻ trong chế độ tự động commit. Các câu lệnh được commit ngay lập tức và không thể khôi phục nếu câu lệnh sau đó thất bại.",- "on-tooltip": "Gói tất cả các câu lệnh trong một giao dịch duy nhất (BEGIN/COMMIT)."+ "label": "Chế độ giao dịch"},"unfinished-resolved-issue-tips": "Vấn đề này được đánh dấu là \"Đã phê duyệt\" nhưng một số tác vụ của nó không được thực hiện thành công.","upload-sql": "Tải lên SQL",@@ -1385,16 +1352,8 @@"unsaved-changes": "Những thay đổi chưa lưu","unsaved-changes-message": "Bạn chưa lưu thay đổi. Bạn có chắc chắn muốn thoát không?"},- "ghost": {- "configuration-has-issues": "Cấu hình có vấn đề {count} | Cấu hình có vấn đề {count}",- "missing-backup-database": "Tạo cơ sở dữ liệu 'bbdataarchive' trên phiên bản '{instance}', sau đó đồng bộ phiên bản và cơ sở dữ liệu",- "only-some-databases-checked": "Chỉ một số cơ sở dữ liệu được kiểm tra",- "some-databases-have-issues": "{count} cơ sở dữ liệu có vấn đề | {count} cơ sở dữ liệu có vấn đề",- "some-databases-not-meeting-requirements": "Một số cơ sở dữ liệu ({databases}) không đáp ứng được yêu cầu"- },"go-to-plan-page": "Đi tới trang kế hoạch","isolation-level": {- "description": "Kiểm soát cách các giao dịch tương tác với các thay đổi đồng thời. Chỉ áp dụng khi Chế độ Giao dịch được bật.","self": "Mức Độ Cô Lập"},"labels-required-for-review": "Cần có nhãn trước khi yêu cầu xem xét",@@ -1432,19 +1391,7 @@"show-details": "Hiển thị chi tiết ↓"},"plans": "Kế hoạch",- "pre-backup": {- "configuration-has-issues": "Cấu hình có vấn đề {count} | Cấu hình có vấn đề {count}",- "missing-backup-database": "Tạo cơ sở dữ liệu 'bbdataarchive' trên instance '{instance}', sau đó đồng bộ instance và cơ sở dữ liệu",- "missing-backup-database-oracle": "Tạo cơ sở dữ liệu 'BBDATAARCHIVE' trên instance '{instance}', sau đó đồng bộ instance và cơ sở dữ liệu",- "missing-backup-schema-postgres": "Tạo schema 'bbdataarchive' trong cơ sở dữ liệu '{database}'. Nếu sử dụng SET ROLE, hãy cấp quyền USAGE và CREATE trên schema cho role đó. Sau đó đồng bộ cơ sở dữ liệu",- "only-some-databases-checked": "Chỉ một số cơ sở dữ liệu được kiểm tra",- "some-databases-have-issues": "{count} cơ sở dữ liệu có vấn đề | {count} cơ sở dữ liệu có vấn đề",- "some-databases-not-meeting-requirements": "Một số cơ sở dữ liệu ({databases}) không đáp ứng được yêu cầu"- },"ready-for-review": "Sẵn sàng để xem xét",- "refresh-indicator": {- "last-refresh": "Làm mới lần cuối: {time}"- },"run": "Kiểm tra lại","select-isolation-level": "Chọn mức độ cô lập","select-targets": "Chọn mục tiêu",@@ -1454,15 +1401,6 @@},"spec": {"change": "Thay đổi",- "delete-change": {- "content": "Bạn có chắc chắn muốn xóa thay đổi này không?",- "title": "Xóa thay đổi"- },- "role-selection": {- "description": "Chọn vai trò PostgreSQL để thực thi câu lệnh này.",- "technical-note": "Thêm \"SET ROLE {role};\" vào câu lệnh SQL của bạn.",- "title": "Lựa chọn vai trò cơ sở dữ liệu"- },"type": {"create-database": "Tạo cơ sở dữ liệu","database-change": "Thay đổi cơ sở dữ liệu",@@ -1759,7 +1697,6 @@"files": "Tệp","not-found": "Không tìm thấy","releases": "Bản phát hành",- "title": "Phát hành","total-files": "Tổng số {count} tệp","usage-description": "Bản phát hành là một artifact ứng dụng có phiên bản mà việc triển khai vào môi trường được kích hoạt bởi quy trình GitOps.","vcs-source": "Nguồn VCS",@@ -1876,7 +1813,6 @@"self": "Giai đoạn | Các giai đoạn"},"task": {- "no-statement": "Không có câu lệnh SQL","no-tasks": "Không có nhiệm vụ nào ở giai đoạn này","selected-count": "{count} nhiệm vụ đã chọn | {count} nhiệm vụ đã chọn","statement-truncated-hint": "Câu lệnh bị cắt bớt do kích thước lớn."@@ -1937,7 +1873,6 @@"indexes": "Chỉ mục","unique": "Duy nhất"},- "insert-sql": "Insert SQL","message": {"cannot-drop-the-last-column": "Không thể xóa cột cuối cùng","duplicated-function-name": "Tên hàm trùng lặp",@@ -1960,7 +1895,6 @@"select": "Chọn lược đồ"},"search-database-and-table": "Tìm kiếm cơ sở dữ liệu và bảng",- "self": "Trình soạn thảo lược đồ","table": {"name": "Tên bảng","select": "Chọn bảng"@@ -1974,7 +1908,6 @@"value": "Giá trị"},"tables": "Bảng",- "template-database": "Template database","views": "Khung nhìn"},"schema-template": {@@ -2764,8 +2697,7 @@"rule-detail": "Chi tiết quy tắc","select-all": "Chọn tất cả","select-review-rules": "Chọn quy tắc đánh giá SQL",- "title": "Đánh giá SQL",- "view-definition": "Xem định nghĩa"+ "title": "Đánh giá SQL"},"subscription": {"button": {@@ -2891,7 +2823,6 @@"summary-report": "Báo cáo tổng hợp"},"checking": "Đang kiểm tra...",- "comment": "Bình luận","created": "Đã tạo","data-export-creator-only": "Chỉ người tạo sự cố mới có thể thực hiện tác vụ xuất dữ liệu","error": {@@ -2899,7 +2830,6 @@},"executed-by": "Được thực hiện bởi","execution-time": "Thời gian thực thi",- "no-cancellable-tasks": "Không có nhiệm vụ nào có thể hủy bỏ","no-permission": "Không có quyền thực hiện hành động này","no-runnable-tasks": "Không có tác vụ nào có thể chạy được","no-selectable-tasks": "Không thể chọn bất kỳ tác vụ nào",@@ -2907,20 +2837,10 @@"no-tasks-selected": "Không có nhiệm vụ nào được chọn","online-migration": {"advice-split-statement-to-single-online-migration-issue": "Đề nghị chia câu lệnh này thành một vấn đề di chuyển trực tuyến.",- "configure": "Cấu hình",- "configure-ghost-parameters": "Cấu hình tham số gh-ost",- "error": {- "not-applicable": {- "database-doesnt-meet-ghost-requirement": "Cơ sở dữ liệu {database} không đáp ứng được yêu cầu của gh-ost"- },- "nothing-changed": "Không có gì thay đổi"- },- "ghost-parameters": "Tham số gh-ost","self": "Di chuyển trực tuyến"},"only-showing-latest-n-runs": "Chỉ hiển thị các lần chạy {n} mới nhất","prior-backup": "Sao lưu trước",- "prior-backup-tips": "Sao lưu dữ liệu bị ảnh hưởng trước thời hạn. Chỉ áp dụng cho thay đổi dữ liệu (UPDATE, DELETE), không áp dụng cho thay đổi cấu trúc.","run-checks": "Chạy kiểm tra","run-history": "Lịch sử chạy","run-immediately": {@@ -2932,7 +2852,6 @@"description": "Đặt ngày và giờ cụ thể để các tác vụ tự động bắt đầu chạy. Hữu ích cho các khung giờ bảo trì hoặc ngoài giờ cao điểm.","self": "Lên lịch cho sau"},- "scheduled-at": "Đã lên lịch tại","scheduled-time": "Thời gian đã lên lịch","select-scheduled-time": "Chọn thời gian đã lên lịch","select-task": "Chọn nhiệm vụ | Chọn nhiệm vụ",@@ -2949,17 +2868,9 @@"pending": "Đang chờ","running": "Đang chạy","skipped": "Đã bỏ qua"- },- "task-checks": "Kiểm tra tác vụ",- "type": {- "database-create": "Tạo cơ sở dữ liệu",- "database-export": "Xuất dữ liệu",- "general": "Chung",- "migrate": "Di chuyển"}},"task-run": {- "failed-runs": "Nhiệm vụ thất bại - Nhật ký thực thi mới nhất","history": "Lịch sử thực hiện nhiệm vụ","latest": "Thực hiện mới nhất","latest-logs": "Nhật ký mới nhất",@@ -2992,8 +2903,7 @@"available": "Có thể khôi phục lại cho tác vụ {n} | Có thể khôi phục lại cho tác vụ {n}","no-statement-generated": "Không có câu lệnh khôi phục nào được tạo ra","preview-statement": {- "description": "Bytebase tạo ra một câu lệnh khôi phục dựa trên tác vụ đang chạy. Bạn có thể xem lại câu lệnh này trước khi thực hiện khôi phục.",- "self": "Xem trước câu lệnh"+ "description": "Bytebase tạo ra một câu lệnh khôi phục dựa trên tác vụ đang chạy. Bạn có thể xem lại câu lệnh này trước khi thực hiện khôi phục."}},"status": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 442b9cc32b..3ecbbd29dc 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -335,7 +335,6 @@"labels": "标签","language": "语言","lark": "Lark",- "latest": "最新","learn-more": "了解更多","leave": "离开","leave-without-saving": "不保存变动?",@@ -357,11 +356,9 @@"no-data": "无数据","no-license": "无证书","not-started": "未开始",- "notices": "注意事项","off": "关","ok": "OK","on": "开",- "only-creator-allowed-action": "只有创建者才能执行此操作","only-creator-allowed-export": "只有创建者才能执行导出","operation": "操作","operations": "操作",@@ -460,7 +457,6 @@"untitled": "未命名","update": "更新","updated": "已更新",- "updated-at": "更新于","upload": "上传","user": "用户","username": "用户名",@@ -521,8 +517,7 @@"approved-issue": "批准工单","disallow-approve-reason": {"some-task-checks-are-still-running": "尚有运行中的任务检查项。",- "some-task-checks-didnt-pass": "尚有未通过的任务检查项。",- "x-field-is-required": "{field}为必填项"+ "some-task-checks-didnt-pass": "尚有未通过的任务检查项。"},"generating-approval-flow": "正在生成审批流","re-request-review": "请求再次审批",@@ -646,7 +641,6 @@"edit-labels": "编辑标签","edit-schema": "变更 Schema","engine": "引擎",- "engine-not-supported-for-backup": "引擎不支持预备份:{databases}","export-schema": "导出 Schema","export-schema-multi-file": "多文件 (ZIP)","export-schema-single-file": "单文件",@@ -1172,9 +1166,6 @@"search": "输入名称或 ID 来搜索","self": "高级搜索"},- "approval": {- "approved-and-waiting-for-rollout": "该工单已批准,等待发布。"- },"approval-flow": {"self": "审批流"},@@ -1207,17 +1198,9 @@"limits": "限制","options": "配置项"},- "error": {- "statement-cannot-be-modified": "工单创建后,语句将无法修改"- },"issue-name": "工单名称","labels": "工单标签","leave-a-comment": "发表一条评论…",- "migration-mode": {- "online": {- "description": "基于 gh-ost。对于大表,可以把锁表的时间从小时级降低到秒级 {link}。"- }- },"my-issues": "我的工单","no-description-provided": "未提供描述","options-disabled-due-to-oversize": "由于 SQL 文件过大,选项已禁用。",@@ -1255,8 +1238,6 @@},"sql-check": {"back-to-edit": "返回编辑",- "not-executed-yet": "尚未执行",- "sql-checks": "SQL 检查项","sql-review-violations": "违反的 SQL 审核规则","statement-is-required": "SQL 语句不能为空","statement-is-too-large": "当前语句大小超过 2MB,将跳过 SQL 检查。"@@ -1281,18 +1262,7 @@},"task-run": {"logs": "日志",- "session": "会话",- "task-run-session": {- "blocked-sessions": {- "description": "当前会话阻塞了以下会话",- "self": "被阻塞会话"- },- "blocking-sessions": {- "description": "当前会话被以下会话阻塞",- "self": "阻塞会话"- },- "no-session-found": "未找到会话。"- }+ "session": "会话"},"title": {"change-database": "变更数据库",@@ -1303,10 +1273,7 @@"request-specific-role": "请求“{role}”角色"},"transaction-mode": {- "execution-order-note": "非事务性语句将最后执行。",- "label": "事务模式",- "off-tooltip": "以自动提交模式单独执行语句。语句立即提交,如果后续语句失败则无法回滚。",- "on-tooltip": "将所有语句包装在单个事务中(BEGIN/COMMIT)。"+ "label": "事务模式"},"unfinished-resolved-issue-tips": "该工单被标记为「已完成」,但其中部分任务并未成功执行。","upload-sql": "上传 SQL",@@ -1385,16 +1352,8 @@"unsaved-changes": "未保存的更改","unsaved-changes-message": "有未保存的更改。您确定要离开吗?"},- "ghost": {- "configuration-has-issues": "配置存在 {count} 个问题 | 配置存在 {count} 个问题",- "missing-backup-database": "请在实例 '{instance}' 上创建数据库 'bbdataarchive',然后同步实例和数据库",- "only-some-databases-checked": "仅检查部分数据库",- "some-databases-have-issues": "{count} 个数据库有问题 | {count} 个数据库有问题",- "some-databases-not-meeting-requirements": "部分数据库({databases})不符合要求"- },"go-to-plan-page": "前往变更计划页","isolation-level": {- "description": "控制事务如何处理并发更改。仅在事务模式开启时适用。","self": "隔离级别"},"labels-required-for-review": "提交审批前需要选择标签",@@ -1432,19 +1391,7 @@"show-details": "展开详情 ↓"},"plans": "变更计划",- "pre-backup": {- "configuration-has-issues": "配置存在 {count} 个问题 | 配置存在 {count} 个问题",- "missing-backup-database": "在实例 '{instance}' 上创建数据库 'bbdataarchive',然后同步实例和数据库",- "missing-backup-database-oracle": "在实例 '{instance}' 上创建数据库 'BBDATAARCHIVE',然后同步实例和数据库",- "missing-backup-schema-postgres": "在数据库 '{database}' 中创建 schema 'bbdataarchive'。如果使用了 SET ROLE,请将该 schema 的 USAGE 和 CREATE 权限授予对应角色。然后同步数据库",- "only-some-databases-checked": "仅检查部分数据库",- "some-databases-have-issues": "{count} 个数据库有问题 | {count} 个数据库有问题",- "some-databases-not-meeting-requirements": "部分数据库({databases})不符合要求"- },"ready-for-review": "提交审批",- "refresh-indicator": {- "last-refresh": "上次刷新:{time}"- },"run": "重新检查","select-isolation-level": "选择隔离级别","select-targets": "选择目标库",@@ -1454,15 +1401,6 @@},"spec": {"change": "变更项",- "delete-change": {- "content": "您确定要删除该变更项吗?",- "title": "删除变更项"- },- "role-selection": {- "description": "选择以哪个 PostgreSQL 角色来执行此语句。",- "technical-note": "将“SET ROLE {role};”添加到您的 SQL 语句中。",- "title": "数据库角色选择"- },"type": {"create-database": "创建数据库","database-change": "数据库变更",@@ -1759,7 +1697,6 @@"files": "文件","not-found": "未找到","releases": "发布包",- "title": "发布包","total-files": "共 {count} 个文件","usage-description": "发布包是版本化的应用制品。GitOps 工作流将发布包部署到环境。","vcs-source": "VCS 源",@@ -1876,7 +1813,6 @@"self": "阶段 | 阶段"},"task": {- "no-statement": "没有 SQL 语句","no-tasks": "此阶段没有任务","selected-count": "已选择 {count} 个任务","statement-truncated-hint": "由于语句过长,已被截断。"@@ -1937,7 +1873,6 @@"indexes": "索引","unique": "唯一"},- "insert-sql": "插入 SQL","message": {"cannot-drop-the-last-column": "不能删除最后一列","duplicated-function-name": "重复的函数名称",@@ -1960,7 +1895,6 @@"select": "选择 schema"},"search-database-and-table": "搜索数据库和表",- "self": "Schema 编辑器","table": {"name": "表名","select": "选择表"@@ -1974,7 +1908,6 @@"value": "值"},"tables": "表",- "template-database": "模板数据库","views": "视图"},"schema-template": {@@ -2764,8 +2697,7 @@"rule-detail": "规则详情","select-all": "选择全部","select-review-rules": "选择 SQL 审核规则",- "title": "SQL 审核策略",- "view-definition": "查看定义"+ "title": "SQL 审核策略"},"subscription": {"button": {@@ -2891,7 +2823,6 @@"summary-report": "概要报告"},"checking": "检查中…",- "comment": "评论","created": "创建于","data-export-creator-only": "只有工单创建者可以执行数据导出任务","error": {@@ -2899,7 +2830,6 @@},"executed-by": "执行者","execution-time": "执行时间",- "no-cancellable-tasks": "没有可取消的任务","no-permission": "无权限执行该操作","no-runnable-tasks": "没有可运行的任务","no-selectable-tasks": "没有可选择的任务",@@ -2907,20 +2837,10 @@"no-tasks-selected": "未选择任何任务","online-migration": {"advice-split-statement-to-single-online-migration-issue": "建议将该语句拆分成单独的在线大表变更工单。",- "configure": "配置",- "configure-ghost-parameters": "配置 gh-ost 参数",- "error": {- "not-applicable": {- "database-doesnt-meet-ghost-requirement": "数据库 {database} 不符合 gh-ost 的要求"- },- "nothing-changed": "无任何改变"- },- "ghost-parameters": "gh-ost 参数","self": "在线大表变更"},"only-showing-latest-n-runs": "仅显示最近 {n} 条记录","prior-backup": "预备份受影响数据",- "prior-backup-tips": "提前备份受影响的数据。仅适用于数据变更(UPDATE、DELETE),不适用于结构变更。","run-checks": "运行检查","run-history": "执行历史","run-immediately": {@@ -2932,7 +2852,6 @@"description": "设置任务自动开始运行的特定时间。","self": "定时运行"},- "scheduled-at": "计划于","scheduled-time": "计划时间","select-scheduled-time": "选择计划时间","select-task": "选择任务 | 选择任务",@@ -2949,17 +2868,9 @@"pending": "待执行","running": "运行中","skipped": "已跳过"- },- "task-checks": "任务检查项",- "type": {- "database-create": "创建数据库",- "database-export": "导出数据",- "general": "通用",- "migrate": "变更"}},"task-run": {- "failed-runs": "失败的任务 - 最新的执行日志","history": "执行记录","latest": "最新执行","latest-logs": "执行日志",@@ -2992,8 +2903,7 @@"available": "可回滚 {n} 个任务","no-statement-generated": "生成的回滚语句为空","preview-statement": {- "description": "Bytebase 根据任务运行情况生成回滚语句,您可以在执行回滚前查看该语句。",- "self": "预览语句"+ "description": "Bytebase 根据任务运行情况生成回滚语句,您可以在执行回滚前查看该语句。"}},"status": {diff --git a/frontend/src/react/SubscriptionPageMount.vue b/frontend/src/react/SubscriptionPageMount.vuedeleted file mode 100644index 8290f8f602..0000000000--- a/frontend/src/react/SubscriptionPageMount.vue+++ /dev/null@@ -1,25 +0,0 @@-<template>- <ReactPageMount page="SubscriptionPage" v-bind="pageProps" />- <InstanceAssignment- :show="showInstanceAssignmentDrawer"- @dismiss="showInstanceAssignmentDrawer = false"- />-</template>--<script lang="ts" setup>-import { ref } from "vue";-import InstanceAssignment from "@/components/InstanceAssignment.vue";-import { ENTERPRISE_INQUIRE_LINK } from "@/types";-import ReactPageMount from "./ReactPageMount.vue";--const showInstanceAssignmentDrawer = ref(false);--const pageProps = {- onRequireEnterprise: () => {- window.open(ENTERPRISE_INQUIRE_LINK, "_blank");- },- onManageInstanceLicenses: () => {- showInstanceAssignmentDrawer.value = true;- },-};-</script>diff --git a/frontend/src/react/components/DashboardSidebar.test.tsx b/frontend/src/react/components/DashboardSidebar.test.tsxnew file mode 100644index 0000000000..a3c2a13fa4--- /dev/null+++ b/frontend/src/react/components/DashboardSidebar.test.tsx@@ -0,0 +1,244 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";+import {+ DATABASE_ROUTE_DASHBOARD,+ SQL_EDITOR_HOME_MODULE,+ WORKSPACE_ROUTE_LANDING,+ WORKSPACE_ROUTE_MEMBERS,+} from "@/react/router";+import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ currentRoute: {+ name: "workspace.landing",+ fullPath: "/",+ params: {},+ query: {},+ },+ databaseChangeMode: 1,+ isSaaSMode: false,+ workspaceLogo: "",+ record: vi.fn(),+ push: vi.fn(),+ resolve: vi.fn(({ name }: { name: string }) => ({+ fullPath: `/${name}`,+ })),+}));++const t = vi.hoisted(+ () => (key: string) =>+ ({+ "common.home": "Home",+ "common.projects": "Projects",+ "common.instances": "Instances",+ "common.databases": "Databases",+ "common.environments": "Environments",+ "common.users": "Users",+ "common.settings": "Settings",+ "settings.sidebar.iam-and-admin": "IAM & Admin",+ "settings.members.service-accounts": "Service Accounts",+ "settings.members.workload-identities": "Workload Identities",+ "settings.sidebar.members": "Members",+ "settings.members.groups.self": "Groups",+ "settings.sidebar.custom-roles": "Custom Roles",+ "settings.sidebar.sso": "SSO",+ "settings.sidebar.audit-log": "Audit Log",+ "sql-review.title": "SQL Review",+ "custom-approval.risk.self": "Risk Assessment",+ "custom-approval.self": "Custom Approval",+ "settings.sidebar.data-access": "Data Access",+ "settings.sensitive-data.semantic-types.self": "Semantic Types",+ "settings.sidebar.data-classification": "Data Classification",+ "settings.sidebar.global-masking": "Global Masking",+ "settings.sidebar.integration": "Integration",+ "settings.sidebar.im-integration": "IM Integration",+ "settings.sidebar.mcp": "MCP",+ "settings.sidebar.general": "General",+ "settings.sidebar.subscription": "Subscription",+ })[key] ?? key+);++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t,+ }),+}));++vi.mock("@/react/hooks/useAppState", () => ({+ useAppFeature: () => mocks.databaseChangeMode,+ useIsSaaSMode: () => mocks.isSaaSMode,+ useWorkspace: () => ({+ logo: mocks.workspaceLogo,+ }),+ useRecentVisit: () => ({+ record: mocks.record,+ }),+}));++vi.mock("@/react/router", () => ({+ useCurrentRoute: () => mocks.currentRoute,+ useNavigate: () => ({+ push: mocks.push,+ resolve: mocks.resolve,+ }),+ DATABASE_ROUTE_DASHBOARD: "workspace.database",+ ENVIRONMENT_V1_ROUTE_DASHBOARD: "workspace.environment",+ INSTANCE_ROUTE_DASHBOARD: "workspace.instance",+ PROJECT_V1_ROUTE_DASHBOARD: "workspace.project",+ SETTING_ROUTE_WORKSPACE_GENERAL: "setting.workspace.general",+ SETTING_ROUTE_WORKSPACE_SUBSCRIPTION: "setting.workspace.subscription",+ SQL_EDITOR_HOME_MODULE: "sql-editor.home",+ WORKSPACE_ROUTE_AUDIT_LOG: "workspace.audit-log",+ WORKSPACE_ROUTE_CUSTOM_APPROVAL: "workspace.custom-approval",+ WORKSPACE_ROUTE_DATA_CLASSIFICATION: "workspace.data-classification",+ WORKSPACE_ROUTE_GLOBAL_MASKING: "workspace.global-masking",+ WORKSPACE_ROUTE_GROUPS: "workspace.groups",+ WORKSPACE_ROUTE_IDENTITY_PROVIDERS: "workspace.identity-providers",+ WORKSPACE_ROUTE_IM: "workspace.integration.im",+ WORKSPACE_ROUTE_LANDING: "workspace.landing",+ WORKSPACE_ROUTE_MCP: "workspace.integration.mcp",+ WORKSPACE_ROUTE_MEMBERS: "workspace.members",+ WORKSPACE_ROUTE_RISK_ASSESSMENT: "workspace.risk-assessment",+ WORKSPACE_ROUTE_ROLES: "workspace.roles",+ WORKSPACE_ROUTE_SEMANTIC_TYPES: "workspace.semantic-types",+ WORKSPACE_ROUTE_SERVICE_ACCOUNTS: "workspace.service-accounts",+ WORKSPACE_ROUTE_SQL_REVIEW: "workspace.sql-review",+ WORKSPACE_ROUTE_USER_PROFILE: "workspace.user-profile",+ WORKSPACE_ROUTE_USERS: "workspace.users",+ WORKSPACE_ROUTE_WORKLOAD_IDENTITIES: "workspace.workload-identities",+}));++vi.mock("@/assets/logo-full.svg", () => ({+ default: "/assets/logo-full.svg",+}));++vi.mock("./WorkspaceSwitcher", () => ({+ WorkspaceSwitcher: () => <div data-testid="workspace-switcher" />,+}));++let DashboardSidebar: typeof import("./DashboardSidebar").DashboardSidebar;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () =>+ act(() => {+ root.unmount();+ container.remove();+ }),+ };+};++beforeEach(async () => {+ vi.clearAllMocks();+ mocks.currentRoute.name = WORKSPACE_ROUTE_LANDING;+ mocks.currentRoute.fullPath = "/";+ mocks.databaseChangeMode = DatabaseChangeMode.PIPELINE;+ mocks.isSaaSMode = false;+ mocks.workspaceLogo = "";+ ({ DashboardSidebar } = await import("./DashboardSidebar"));+});++describe("DashboardSidebar", () => {+ test("renders non-SaaS IAM routes and hides SaaS-only exclusions", () => {+ mocks.currentRoute.name = WORKSPACE_ROUTE_MEMBERS;+ const { container, render, unmount } = renderIntoContainer(+ <DashboardSidebar />+ );+ render();++ expect(container.textContent).toContain("Users");+ expect(container.textContent).toContain("Service Accounts");+ expect(container.textContent).toContain("Workload Identities");++ unmount();++ mocks.isSaaSMode = true;+ const saas = renderIntoContainer(<DashboardSidebar />);+ saas.render();++ expect(saas.container.textContent).not.toContain("Users");+ expect(saas.container.textContent).not.toContain("Service Accounts");+ expect(saas.container.textContent).not.toContain("Workload Identities");+ expect(saas.container.textContent).toContain("Members");++ saas.unmount();+ });++ test("uses database-change mode for the logo route and records visits", () => {+ mocks.databaseChangeMode = DatabaseChangeMode.EDITOR;+ mocks.workspaceLogo = "https://example.com/logo.png";+ const { container, render, unmount } = renderIntoContainer(+ <DashboardSidebar />+ );+ render();++ const logoLink = container.querySelector<HTMLAnchorElement>("nav > a");+ expect(logoLink?.getAttribute("href")).toBe(`/${SQL_EDITOR_HOME_MODULE}`);+ expect(logoLink?.querySelector("img")?.getAttribute("src")).toBe(+ "https://example.com/logo.png"+ );++ act(() => {+ logoLink?.dispatchEvent(+ new MouseEvent("click", { bubbles: true, cancelable: true })+ );+ });++ expect(mocks.record).toHaveBeenCalledWith(`/${SQL_EDITOR_HOME_MODULE}`);+ expect(mocks.push).toHaveBeenCalledWith({ name: SQL_EDITOR_HOME_MODULE });++ unmount();+ });++ test("highlights the active route", () => {+ mocks.currentRoute.name = DATABASE_ROUTE_DASHBOARD;+ const { container, render, unmount } = renderIntoContainer(+ <DashboardSidebar />+ );+ render();++ const databaseLink = Array.from(container.querySelectorAll("a")).find(+ (link) => link.textContent?.includes("Databases")+ );+ expect(databaseLink?.className).toContain("router-link-active");++ unmount();+ });++ test("leaves modifier-click navigation to the browser", () => {+ const { container, render, unmount } = renderIntoContainer(+ <DashboardSidebar />+ );+ render();++ const projectsLink = Array.from(container.querySelectorAll("a")).find(+ (link) => link.textContent?.includes("Projects")+ );+ projectsLink?.addEventListener("click", (event) => event.preventDefault());+ const event = new MouseEvent("click", {+ bubbles: true,+ cancelable: true,+ ctrlKey: true,+ });+ projectsLink?.dispatchEvent(event);++ expect(mocks.push).not.toHaveBeenCalled();++ unmount();+ });+});diff --git a/frontend/src/react/components/DashboardSidebar.tsx b/frontend/src/react/components/DashboardSidebar.tsxindex 7970d38ce7..b829013607 100644--- a/frontend/src/react/components/DashboardSidebar.tsx+++ b/frontend/src/react/components/DashboardSidebar.tsx@@ -15,15 +15,23 @@ import {import type { ElementType } from "react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";-import { effectScope } from "vue";import logoFull from "@/assets/logo-full.svg";-import { useVueState } from "@/react/hooks/useVueState";-import { router } from "@/router";+import {+ useAppFeature,+ useIsSaaSMode,+ useRecentVisit,+ useWorkspace,+} from "@/react/hooks/useAppState";import {DATABASE_ROUTE_DASHBOARD,ENVIRONMENT_V1_ROUTE_DASHBOARD,INSTANCE_ROUTE_DASHBOARD,PROJECT_V1_ROUTE_DASHBOARD,+ SETTING_ROUTE_WORKSPACE_GENERAL,+ SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,+ SQL_EDITOR_HOME_MODULE,+ useCurrentRoute,+ useNavigate,WORKSPACE_ROUTE_AUDIT_LOG,WORKSPACE_ROUTE_CUSTOM_APPROVAL,WORKSPACE_ROUTE_DATA_CLASSIFICATION,@@ -42,18 +50,7 @@ import {WORKSPACE_ROUTE_USER_PROFILE,WORKSPACE_ROUTE_USERS,WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,-} from "@/router/dashboard/workspaceRoutes";-import {- SETTING_ROUTE_WORKSPACE_GENERAL,- SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,-} from "@/router/dashboard/workspaceSetting";-import { SQL_EDITOR_HOME_MODULE } from "@/router/sqlEditor";-import { useRecentVisit } from "@/router/useRecentVisit";-import {- useActuatorV1Store,- useAppFeature,- useWorkspaceV1Store,-} from "@/store";+} from "@/react/router";import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";import { WorkspaceSwitcher } from "./WorkspaceSwitcher";@@ -98,7 +95,7 @@ function getItemClass(item: SidebarItem, currentRouteName: string): string[] {function useSidebarItems(): SidebarItem[] {const { t } = useTranslation();- const isSaaSMode = useVueState(() => useActuatorV1Store().isSaaSMode);+ const isSaaSMode = useIsSaaSMode();return useMemo((): SidebarItem[] => [@@ -300,28 +297,12 @@ const childRouteClass =export function DashboardSidebar() {const rawItems = useSidebarItems();const filteredItems = useMemo(() => filterSidebarList(rawItems), [rawItems]);-- const currentRouteName = useVueState(- () => router.currentRoute.value.name?.toString() ?? ""- );- const databaseChangeMode = useVueState(- () => useAppFeature("bb.feature.database-change-mode").value- );- const customLogo = useVueState(- () => useWorkspaceV1Store().currentWorkspace?.logo ?? ""- );- const recordVisitRef = useRef<((path: string) => void) | null>(null);-- useEffect(() => {- // TODO(steven): Replace this Vue composable bridge with a shared framework-agnostic- // recent-visit helper so React components don't need a Vue effect scope.- const scope = effectScope();- scope.run(() => {- const { record } = useRecentVisit();- recordVisitRef.current = record;- });- return () => scope.stop();- }, []);+ const navigate = useNavigate();+ const currentRoute = useCurrentRoute();+ const databaseChangeMode = useAppFeature("bb.feature.database-change-mode");+ const workspace = useWorkspace();+ const { record } = useRecentVisit();+ const currentRouteName = currentRoute.name ?? "";// -- Expand / collapse state -----------------------------------------------const [expandedSet, setExpandedSet] = useState<Set<string>>(new Set());@@ -387,8 +368,11 @@ export function DashboardSidebar() {databaseChangeMode === DatabaseChangeMode.EDITOR? SQL_EDITOR_HOME_MODULE: WORKSPACE_ROUTE_LANDING;- return router.resolve({ name: target });- }, [databaseChangeMode]);+ return {+ name: target,+ route: navigate.resolve({ name: target }),+ };+ }, [databaseChangeMode, navigate]);const onGroupClick = useCallback((item: SidebarItem, key: string) => {if (item.children && item.children.length > 0) {@@ -407,34 +391,37 @@ export function DashboardSidebar() {}, []);const resolveHref = useCallback(- (name: string) => router.resolve({ name }).fullPath,- []+ (name: string) => navigate.resolve({ name }).fullPath,+ [navigate]);- const handleRouteClick = useCallback((e: React.MouseEvent, name: string) => {- // Allow Ctrl/Meta+click to open in new tab naturally- if (e.ctrlKey || e.metaKey) return;- e.preventDefault();- router.push({ name });- }, []);+ const handleRouteClick = useCallback(+ (e: React.MouseEvent, name: string) => {+ // Allow Ctrl/Meta+click to open in new tab naturally.+ if (e.ctrlKey || e.metaKey) return;+ e.preventDefault();+ void navigate.push({ name });+ },+ [navigate]+ );const handleHomeClick = useCallback((e: React.MouseEvent<HTMLAnchorElement>) => {- const route = resolveHomeRoute();- recordVisitRef.current?.(route.fullPath);+ const { name, route } = resolveHomeRoute();+ record(route.fullPath);if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {return;}e.preventDefault();- router.push(route);+ void navigate.push({ name });},- [resolveHomeRoute]+ [navigate, record, resolveHomeRoute]);// -- Logo ------------------------------------------------------------------- const logoSrc = customLogo || logoFull;- const homeHref = resolveHomeRoute().fullPath;+ const logoSrc = workspace?.logo || logoFull;+ const homeHref = resolveHomeRoute().route.fullPath;// -- Render ----------------------------------------------------------------diff --git a/frontend/src/react/components/FeatureAttention.test.tsx b/frontend/src/react/components/FeatureAttention.test.tsxindex 7bfd010f40..adcf6b5b14 100644--- a/frontend/src/react/components/FeatureAttention.test.tsx+++ b/frontend/src/react/components/FeatureAttention.test.tsx@@ -34,8 +34,8 @@ vi.mock("@/react/hooks/useVueState", () => ({useVueState: mocks.useVueState,}));-vi.mock("@/react/components/InstanceAssignmentBridge", () => ({- InstanceAssignmentBridge: () => null,+vi.mock("@/react/components/InstanceAssignmentSheet", () => ({+ InstanceAssignmentSheet: () => null,}));vi.mock("@/router", () => ({diff --git a/frontend/src/react/components/FeatureAttention.tsx b/frontend/src/react/components/FeatureAttention.tsxindex 4ac3ce5910..a3e8c0bf1a 100644--- a/frontend/src/react/components/FeatureAttention.tsx+++ b/frontend/src/react/components/FeatureAttention.tsx@@ -20,7 +20,7 @@ import {} from "@/types/proto-es/v1/subscription_service_pb";import { autoSubscriptionRoute, hasWorkspacePermissionV2 } from "@/utils";import { useVueState } from "../hooks/useVueState";-import { InstanceAssignmentBridge } from "./InstanceAssignmentBridge";+import { InstanceAssignmentSheet } from "./InstanceAssignmentSheet";export function FeatureAttention({feature,@@ -143,10 +143,10 @@ export function FeatureAttention({)}</div></Alert>- <InstanceAssignmentBridge+ <InstanceAssignmentSheetopen={showInstanceAssignment}selectedInstanceList={instance ? [instance.name] : []}- onDismiss={() => setShowInstanceAssignment(false)}+ onOpenChange={setShowInstanceAssignment}/></>);diff --git a/frontend/src/react/components/InstanceAssignmentBridge.tsx b/frontend/src/react/components/InstanceAssignmentBridge.tsxdeleted file mode 100644index 1703f3ecce..0000000000--- a/frontend/src/react/components/InstanceAssignmentBridge.tsx+++ /dev/null@@ -1,47 +0,0 @@-import { useEffect, useRef } from "react";-import { createApp, h } from "vue";-import InstanceAssignment from "@/components/InstanceAssignment.vue";-import i18n from "@/plugins/i18n";-import NaiveUI from "@/plugins/naive-ui";-import { router } from "@/router";-import { pinia } from "@/store";--export function InstanceAssignmentBridge({- open,- selectedInstanceList,- onDismiss,-}: {- open: boolean;- selectedInstanceList?: string[];- onDismiss: () => void;-}) {- const containerRef = useRef<HTMLDivElement>(null);-- useEffect(() => {- if (!open || !containerRef.current) {- return;- }-- const app = createApp({- render() {- return h(InstanceAssignment as never, {- show: open,- selectedInstanceList,- onDismiss,- });- },- });- app.use(router).use(pinia).use(i18n).use(NaiveUI);- app.mount(containerRef.current);-- return () => {- app.unmount();- };- }, [onDismiss, open, selectedInstanceList]);-- if (!open) {- return null;- }-- return <div ref={containerRef} />;-}diff --git a/frontend/src/react/components/InstanceAssignmentSheet.tsx b/frontend/src/react/components/InstanceAssignmentSheet.tsxnew file mode 100644index 0000000000..d8d63625de--- /dev/null+++ b/frontend/src/react/components/InstanceAssignmentSheet.tsx@@ -0,0 +1,360 @@+import { create } from "@bufbuild/protobuf";+import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";+import { Check } from "lucide-react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";+import { LearnMoreLink } from "@/react/components/LearnMoreLink";+import { Button } from "@/react/components/ui/button";+import { EllipsisText } from "@/react/components/ui/ellipsis-text";+import {+ Sheet,+ SheetBody,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetTitle,+} from "@/react/components/ui/sheet";+import { PagedTableFooter } from "@/react/hooks/usePagedData";+import { useVueState } from "@/react/hooks/useVueState";+import {+ pushNotification,+ useActuatorV1Store,+ useDatabaseV1Store,+ useInstanceV1Store,+ useSubscriptionV1Store,+} from "@/store";+import { isValidInstanceName } from "@/types";+import type {+ Instance,+ UpdateInstanceRequest,+} from "@/types/proto-es/v1/instance_service_pb";+import { UpdateInstanceRequestSchema } from "@/types/proto-es/v1/instance_service_pb";+import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";+import { extractInstanceResourceName, hasWorkspacePermissionV2 } from "@/utils";++const PAGE_SIZE = 50;++export interface InstanceAssignmentSheetProps {+ open: boolean;+ selectedInstanceList?: string[];+ onOpenChange: (open: boolean) => void;+ onUpdated?: () => void;+}++export function InstanceAssignmentSheet({+ open,+ selectedInstanceList,+ onOpenChange,+ onUpdated,+}: InstanceAssignmentSheetProps) {+ const { t } = useTranslation();+ const instanceStore = useInstanceV1Store();+ const databaseStore = useDatabaseV1Store();+ const subscriptionStore = useSubscriptionV1Store();+ const actuatorStore = useActuatorV1Store();++ const instanceLicenseCount = useVueState(+ () => subscriptionStore.instanceLicenseCount+ );+ const currentPlan = useVueState(() => subscriptionStore.currentPlan);+ const activatedInstanceCount = useVueState(+ () => actuatorStore.activatedInstanceCount+ );+ const workspaceResourceName = useVueState(+ () => actuatorStore.workspaceResourceName+ );++ const [instances, setInstances] = useState<Instance[]>([]);+ const [selectedNames, setSelectedNames] = useState<Set<string>>(new Set());+ const [nextPageToken, setNextPageToken] = useState("");+ const [loading, setLoading] = useState(false);+ const [fetchingMore, setFetchingMore] = useState(false);+ const [processing, setProcessing] = useState(false);+ const fetchIdRef = useRef(0);+ const selectedInstanceKey = useMemo(+ () => (selectedInstanceList ?? []).join("\n"),+ [selectedInstanceList]+ );++ const canManageSubscription =+ hasWorkspacePermissionV2("bb.instances.update") &&+ currentPlan !== PlanType.FREE;++ const totalLicenseCount =+ instanceLicenseCount === Number.MAX_VALUE+ ? t("common.unlimited")+ : `${instanceLicenseCount}`;++ const applyActivatedSelection = useCallback((list: Instance[]) => {+ setSelectedNames((prev) => {+ const next = new Set(prev);+ for (const instance of list) {+ if (instance.activation) {+ next.add(instance.name);+ }+ }+ return next;+ });+ }, []);++ const fetchInstances = useCallback(+ async (refresh: boolean, pageToken = "") => {+ const fetchId = ++fetchIdRef.current;+ if (refresh) {+ setLoading(true);+ } else {+ setFetchingMore(true);+ }+ try {+ const result = await instanceStore.fetchInstanceList({+ pageSize: PAGE_SIZE,+ pageToken: refresh ? "" : pageToken,+ });+ if (fetchId !== fetchIdRef.current) {+ return;+ }+ setInstances((prev) =>+ refresh ? result.instances : [...prev, ...result.instances]+ );+ setNextPageToken(result.nextPageToken ?? "");+ applyActivatedSelection(result.instances);+ } finally {+ if (fetchId === fetchIdRef.current) {+ setLoading(false);+ setFetchingMore(false);+ }+ }+ },+ [applyActivatedSelection, instanceStore]+ );++ useEffect(() => {+ if (!open) {+ setInstances([]);+ setSelectedNames(new Set());+ setNextPageToken("");+ setProcessing(false);+ return;+ }++ setSelectedNames(+ new Set(selectedInstanceKey ? selectedInstanceKey.split("\n") : [])+ );+ fetchInstances(true);+ }, [fetchInstances, open, selectedInstanceKey]);++ const toggleSelection = useCallback((name: string) => {+ setSelectedNames((prev) => {+ const next = new Set(prev);+ if (next.has(name)) {+ next.delete(name);+ } else {+ next.add(name);+ }+ return next;+ });+ }, []);++ const handleConfirm = useCallback(async () => {+ if (processing || !canManageSubscription) {+ return;+ }+ setProcessing(true);+ try {+ const requests: UpdateInstanceRequest[] = [];+ for (const instanceName of selectedNames) {+ const instance =+ (await instanceStore.getOrFetchInstanceByName(instanceName)) ??+ instanceStore.getInstanceByName(instanceName);+ if (!isValidInstanceName(instance.name)) {+ continue;+ }+ if (instance.activation) {+ continue;+ }+ requests.push(+ create(UpdateInstanceRequestSchema, {+ instance: {+ ...instance,+ activation: true,+ },+ updateMask: create(FieldMaskSchema, { paths: ["activation"] }),+ })+ );+ }++ for (const instance of instances) {+ if (instance.activation && !selectedNames.has(instance.name)) {+ requests.push(+ create(UpdateInstanceRequestSchema, {+ instance: {+ ...instance,+ activation: false,+ },+ updateMask: create(FieldMaskSchema, { paths: ["activation"] }),+ })+ );+ }+ }++ const updated = await instanceStore.batchUpdateInstances(requests);+ for (const instance of updated) {+ databaseStore.updateDatabaseInstance(instance);+ }+ await actuatorStore.fetchServerInfo(workspaceResourceName);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("subscription.instance-assignment.success-notification"),+ });+ onUpdated?.();+ onOpenChange(false);+ } finally {+ setProcessing(false);+ }+ }, [+ actuatorStore,+ canManageSubscription,+ databaseStore,+ instanceStore,+ instances,+ onOpenChange,+ onUpdated,+ processing,+ selectedNames,+ t,+ workspaceResourceName,+ ]);++ const confirmDisabled =+ !canManageSubscription ||+ processing ||+ selectedNames.size > instanceLicenseCount;++ return (+ <Sheet open={open} onOpenChange={onOpenChange}>+ <SheetContent width="standard">+ <SheetHeader>+ <SheetTitle>+ {t("subscription.instance-assignment.manage-license")}+ </SheetTitle>+ </SheetHeader>+ <SheetBody className="gap-y-5">+ <div>+ <div className="flex gap-x-2 text-control-light">+ <span>+ {t("subscription.instance-assignment.used-and-total-license")}+ </span>+ <LearnMoreLink+ href="https://docs.bytebase.com/administration/license?source=console"+ className="text-sm"+ />+ </div>+ <div className="mt-1 flex items-center gap-x-2 text-4xl">+ <span>{activatedInstanceCount}</span>+ <span className="text-xl text-control-light">/</span>+ <span>{totalLicenseCount}</span>+ </div>+ </div>++ <div className="overflow-x-auto rounded-sm border border-control-border">+ <table className="w-full min-w-[36rem] text-sm">+ <thead>+ <tr className="border-b border-control-border bg-control-bg text-left">+ {canManageSubscription && <th className="w-12 px-4 py-2" />}+ <th className="px-4 py-2 font-medium">{t("common.name")}</th>+ <th className="px-4 py-2 font-medium">+ {t("common.environment")}+ </th>+ <th className="px-4 py-2 font-medium">+ {t("subscription.instance-assignment.license")}+ </th>+ </tr>+ </thead>+ <tbody>+ {loading && instances.length === 0 ? (+ <tr>+ <td+ colSpan={canManageSubscription ? 4 : 3}+ className="px-4 py-8 text-center text-control-light"+ >+ {t("common.loading")}+ </td>+ </tr>+ ) : instances.length === 0 ? (+ <tr>+ <td+ colSpan={canManageSubscription ? 4 : 3}+ className="px-4 py-8 text-center text-control-light"+ >+ {t("common.no-data")}+ </td>+ </tr>+ ) : (+ instances.map((instance) => {+ const checked = selectedNames.has(instance.name);+ return (+ <tr+ key={instance.name}+ className="border-b border-control-border last:border-b-0"+ >+ {canManageSubscription && (+ <td className="px-4 py-2">+ <input+ type="checkbox"+ checked={checked}+ onChange={() => toggleSelection(instance.name)}+ className="rounded-xs border-control-border"+ />+ </td>+ )}+ <td className="px-4 py-2">+ <EllipsisText+ text={+ instance.title ||+ extractInstanceResourceName(instance.name)+ }+ />+ </td>+ <td className="px-4 py-2">+ <EnvironmentLabel+ environmentName={instance.environment}+ />+ </td>+ <td className="px-4 py-2">+ {checked ? (+ <Check className="size-4 text-success" />+ ) : (+ "-"+ )}+ </td>+ </tr>+ );+ })+ )}+ </tbody>+ </table>+ </div>++ <PagedTableFooter+ pageSize={PAGE_SIZE}+ pageSizeOptions={[PAGE_SIZE]}+ onPageSizeChange={() => {}}+ hasMore={Boolean(nextPageToken)}+ isFetchingMore={fetchingMore}+ onLoadMore={() => fetchInstances(false, nextPageToken)}+ />+ </SheetBody>+ <SheetFooter>+ <Button variant="outline" onClick={() => onOpenChange(false)}>+ {t("common.cancel")}+ </Button>+ <Button disabled={confirmDisabled} onClick={handleConfirm}>+ {t("common.confirm")}+ </Button>+ </SheetFooter>+ </SheetContent>+ </Sheet>+ );+}diff --git a/frontend/src/react/components/header/ProfileMenuTrigger.test.tsx b/frontend/src/react/components/header/ProfileMenuTrigger.test.tsxindex e71a444425..4b4c3cb4ac 100644--- a/frontend/src/react/components/header/ProfileMenuTrigger.test.tsx+++ b/frontend/src/react/components/header/ProfileMenuTrigger.test.tsx@@ -23,6 +23,7 @@ const mocks = vi.hoisted(() => ({},resetQuickstart: vi.fn(),hideQuickStart: false,+ isDev: false,}));vi.mock("react-i18next", () => ({@@ -133,7 +134,7 @@ vi.mock("@/react/stores/app", () => ({}));vi.mock("@/utils/util", () => ({- isDev: () => false,+ isDev: () => mocks.isDev,}));let ProfileMenuTrigger: typeof import("./ProfileMenuTrigger").ProfileMenuTrigger;@@ -160,6 +161,7 @@ const renderIntoContainer = (element: ReactElement) => {beforeEach(async () => {vi.clearAllMocks();mocks.hideQuickStart = false;+ mocks.isDev = false;window.open = vi.fn();({ ProfileMenuTrigger } = await import("./ProfileMenuTrigger"));});@@ -214,4 +216,24 @@ describe("ProfileMenuTrigger", () => {expect(container.textContent).not.toContain("Quick Start");unmount();});++ test("uploads a development license from the dev license menu", () => {+ mocks.isDev = true;+ const { container, render, unmount } = renderIntoContainer(+ <ProfileMenuTrigger size="medium" link />+ );++ render();++ const teamButton = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.includes("Team")+ );+ expect(teamButton).not.toBeUndefined();+ act(() => {+ teamButton?.click();+ });++ expect(mocks.uploadLicense).toHaveBeenCalledTimes(1);+ unmount();+ });});diff --git a/frontend/src/react/components/header/ProjectSwitchPanel.test.tsx b/frontend/src/react/components/header/ProjectSwitchPanel.test.tsxindex d352ed05a7..532036b41c 100644--- a/frontend/src/react/components/header/ProjectSwitchPanel.test.tsx+++ b/frontend/src/react/components/header/ProjectSwitchPanel.test.tsx@@ -1,4 +1,4 @@-import type { ReactElement } from "react";+import type { ChangeEvent, InputHTMLAttributes, ReactElement } from "react";import { act } from "react";import { createRoot } from "react-dom/client";import { beforeEach, describe, expect, test, vi } from "vitest";@@ -20,12 +20,22 @@ const allProject = {labels: {},};+const otherRecentProject = {+ name: "projects/other-recent",+ title: "Other Project",+ labels: {},+};+const mocks = vi.hoisted(() => ({record: vi.fn(),push: vi.fn(),- resolve: vi.fn(({ params }: { params: { projectId: string } }) => ({- fullPath: `/projects/${params.projectId}`,- })),+ resolve: vi.fn(+ ({ name, params }: { name: string; params?: { projectId: string } }) => ({+ fullPath: params?.projectId+ ? `/projects/${params.projectId}`+ : `/${name}`,+ })+ ),currentRoute: {name: "workspace.project.detail",fullPath: "/projects/recent-project",@@ -36,6 +46,14 @@ const mocks = vi.hoisted(() => ({},requestCreate: vi.fn(),close: vi.fn(),+ recentProjects: [] as Array<typeof recentProject>,+ allProjects: [] as Array<typeof allProject>,+ hasMore: false,+ loadMore: vi.fn(),+ onPageSizeChange: vi.fn(),+ inputOnChange: undefined as+ | ((event: ChangeEvent<HTMLInputElement>) => void)+ | undefined,}));vi.mock("react-i18next", () => ({@@ -62,21 +80,22 @@ vi.mock("@/react/hooks/useAppState", () => ({}),useProject: () => recentProject,useRecentProjects: () => ({- projects: [recentProject],+ projects: mocks.recentProjects,}),useProjectList: () => ({- projects: [allProject],+ projects: mocks.allProjects,isLoading: false,isFetchingMore: false,- hasMore: false,- loadMore: vi.fn(),+ hasMore: mocks.hasMore,+ loadMore: mocks.loadMore,pageSize: 50,pageSizeOptions: [50],- onPageSizeChange: vi.fn(),+ onPageSizeChange: mocks.onPageSizeChange,}),useWorkspacePermission: () => true,projectMatchesKeyword: (project: typeof recentProject, keyword: string) =>- project.title.toLowerCase().includes(keyword.toLowerCase()),+ project.title.toLowerCase().includes(keyword.toLowerCase()) ||+ project.name.toLowerCase().includes(keyword.toLowerCase()),}));vi.mock("@/react/router", () => ({@@ -89,6 +108,13 @@ vi.mock("@/react/router", () => ({WORKSPACE_ROUTE_LANDING: "workspace.landing",}));+vi.mock("@/react/components/ui/input", () => ({+ Input: (props: InputHTMLAttributes<HTMLInputElement>) => {+ mocks.inputOnChange = props.onChange;+ return <input {...props} />;+ },+}));+vi.mock("@/react/components/ui/tabs", () => ({Tabs: ({ children }: { children: ReactElement[] }) => <div>{children}</div>,TabsList: ({ children }: { children: ReactElement[] }) => (@@ -135,6 +161,11 @@ const renderIntoContainer = (element: ReactElement) => {beforeEach(async () => {vi.clearAllMocks();+ mocks.recentProjects = [recentProject];+ mocks.allProjects = [allProject];+ mocks.hasMore = false;+ mocks.inputOnChange = undefined;+ window.open = vi.fn();({ ProjectSwitchPanel } = await import("./ProjectSwitchPanel"));});@@ -187,4 +218,103 @@ describe("ProjectSwitchPanel", () => {expect(mocks.requestCreate).toHaveBeenCalled();unmount();});++ test("loads more projects from the all tab", () => {+ mocks.hasMore = true;+ const { container, render, unmount } = renderIntoContainer(+ <ProjectSwitchPanel+ onClose={mocks.close}+ onRequestCreate={mocks.requestCreate}+ />+ );++ render();++ const loadMoreButton = Array.from(+ container.querySelectorAll("button")+ ).find((button) => button.textContent?.includes("Load more"));+ expect(loadMoreButton).not.toBeUndefined();+ act(() => {+ loadMoreButton?.click();+ });++ expect(mocks.loadMore).toHaveBeenCalledTimes(1);+ unmount();+ });++ test("filters recent projects by keyword", () => {+ mocks.recentProjects = [recentProject, otherRecentProject];+ mocks.allProjects = [];+ const { container, render, unmount } = renderIntoContainer(+ <ProjectSwitchPanel+ onClose={mocks.close}+ onRequestCreate={mocks.requestCreate}+ />+ );++ render();++ act(() => {+ mocks.inputOnChange?.({+ target: { value: "recent project" },+ } as ChangeEvent<HTMLInputElement>);+ });++ expect(container.textContent).toContain("Recent Project");+ expect(container.textContent).not.toContain("Other Project");+ unmount();+ });++ test("closes after selecting the current project", () => {+ const { container, render, unmount } = renderIntoContainer(+ <ProjectSwitchPanel+ onClose={mocks.close}+ onRequestCreate={mocks.requestCreate}+ />+ );++ render();++ const currentProjectRow = Array.from(+ container.querySelectorAll("button")+ ).find((button) => button.textContent?.includes("Recent Project"));+ act(() => {+ currentProjectRow?.click();+ });++ expect(mocks.close).toHaveBeenCalledTimes(1);+ unmount();+ });++ test("opens project selection in a new window for ctrl-click", () => {+ const { container, render, unmount } = renderIntoContainer(+ <ProjectSwitchPanel+ onClose={mocks.close}+ onRequestCreate={mocks.requestCreate}+ />+ );++ render();++ const row = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.includes("Recent Project")+ );+ act(() => {+ row?.dispatchEvent(+ new MouseEvent("click", {+ bubbles: true,+ cancelable: true,+ ctrlKey: true,+ })+ );+ });++ expect(window.open).toHaveBeenCalledWith(+ "/projects/recent-project",+ "_blank"+ );+ expect(mocks.push).not.toHaveBeenCalled();+ expect(mocks.close).toHaveBeenCalled();+ unmount();+ });});diff --git a/frontend/src/react/components/header/VersionMenuItem.test.tsx b/frontend/src/react/components/header/VersionMenuItem.test.tsxnew file mode 100644index 0000000000..809f57e6dc--- /dev/null+++ b/frontend/src/react/components/header/VersionMenuItem.test.tsx@@ -0,0 +1,195 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { SETTING_ROUTE_WORKSPACE_SUBSCRIPTION } from "@/react/router";+import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";+import { STORAGE_KEY_RELEASE } from "@/utils/storage-keys";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ canManageSettings: true,+ serverInfo: {+ version: "1.0.0",+ gitCommit: "backend123",+ saas: false,+ demo: false,+ },+ subscription: {+ plan: 1,+ },+ push: vi.fn(),+ closeMenu: vi.fn(),+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, params?: Record<string, string>) =>+ ({+ "common.demo-mode": "Demo Mode",+ "subscription.plan.free.title": "Free",+ "subscription.plan.team.title": "Team",+ "subscription.plan.enterprise.title": "Enterprise",+ "remind.release.new-version-available-with-tag": `New version ${params?.tag}`,+ "common.dismiss": "Dismiss",+ "common.learn-more": "Learn more",+ })[key] ?? key,+ }),+}));++vi.mock("@/react/hooks/useAppState", () => ({+ useServerInfo: () => mocks.serverInfo,+ useSubscription: () => ({+ subscription: mocks.subscription,+ }),+ useWorkspacePermission: () => mocks.canManageSettings,+}));++vi.mock("@/react/router", () => ({+ SETTING_ROUTE_WORKSPACE_SUBSCRIPTION: "setting.workspace.subscription",+ useNavigate: () => ({+ push: mocks.push,+ }),+}));++vi.mock("@/react/components/ui/badge", () => ({+ Badge: ({ children }: { children: ReactElement | string }) => (+ <span>{children}</span>+ ),+}));++vi.mock("@/react/components/ui/button", () => ({+ Button: ({+ children,+ onClick,+ }: {+ children: ReactElement | string;+ onClick?: () => void;+ }) => <button onClick={onClick}>{children}</button>,+}));++vi.mock("@/react/components/ui/dialog", () => ({+ Dialog: ({+ children,+ open,+ }: {+ children: ReactElement | ReactElement[];+ open: boolean;+ }) => (open ? <div>{children}</div> : null),+ DialogContent: ({+ children,+ }: {+ children: ReactElement | ReactElement[];+ }) => <div>{children}</div>,+ DialogDescription: ({ children }: { children: ReactElement | string }) => (+ <div>{children}</div>+ ),+ DialogTitle: ({ children }: { children: ReactElement | string }) => (+ <h2>{children}</h2>+ ),+}));++let VersionMenuItem: typeof import("./VersionMenuItem").VersionMenuItem;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () =>+ act(() => {+ root.unmount();+ container.remove();+ }),+ };+};++beforeEach(async () => {+ vi.clearAllMocks();+ localStorage.clear();+ mocks.canManageSettings = true;+ mocks.serverInfo = {+ version: "1.0.0",+ gitCommit: "backend123",+ saas: false,+ demo: false,+ };+ mocks.subscription = {+ plan: PlanType.TEAM,+ };+ window.open = vi.fn();+ ({ VersionMenuItem } = await import("./VersionMenuItem"));+});++describe("VersionMenuItem", () => {+ test("links subscription when the user can manage settings", () => {+ const { container, render, unmount } = renderIntoContainer(+ <VersionMenuItem onCloseMenu={mocks.closeMenu} />+ );+ render();++ const planButton = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.includes("Team")+ );+ expect(planButton).not.toBeUndefined();+ act(() => {+ planButton?.click();+ });++ expect(mocks.push).toHaveBeenCalledWith({+ name: SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,+ });+ expect(mocks.closeMenu).toHaveBeenCalled();+ unmount();+ });++ test("opens the release dialog and learn-more link for new releases", () => {+ localStorage.setItem(+ STORAGE_KEY_RELEASE,+ JSON.stringify({+ latest: {+ tag_name: "2.0.0",+ html_url: "https://example.com/release",+ },+ ignoreRemindModalTillNextRelease: false,+ nextCheckTs: 0,+ })+ );+ const { container, render, unmount } = renderIntoContainer(+ <VersionMenuItem onCloseMenu={mocks.closeMenu} />+ );+ render();++ const versionButton = Array.from(container.querySelectorAll("button")).find(+ (button) => button.textContent?.includes("v1.0.0")+ );+ act(() => {+ versionButton?.click();+ });++ expect(container.textContent).toContain("New version 2.0.0");+ expect(mocks.closeMenu).toHaveBeenCalled();++ const learnMoreButton = Array.from(+ container.querySelectorAll("button")+ ).find((button) => button.textContent?.includes("Learn more"));+ act(() => {+ learnMoreButton?.click();+ });++ expect(window.open).toHaveBeenCalledWith(+ "https://example.com/release",+ "_blank"+ );+ unmount();+ });+});diff --git a/frontend/src/react/components/header/common.ts b/frontend/src/react/components/header/common.tsindex 85d0cd6d36..b9095a8c72 100644--- a/frontend/src/react/components/header/common.ts+++ b/frontend/src/react/components/header/common.ts@@ -1,4 +1,5 @@import i18n from "@/react/i18n";+import { emitReactLocaleChange } from "@/react/shell-bridge";import { STORAGE_KEY_LANGUAGE } from "@/utils/storage-keys";import { emitStorageChangedEvent } from "@/utils/util";@@ -19,7 +20,5 @@ export function setAppLocale(lang: string) {void i18n.changeLanguage(lang);localStorage.setItem(STORAGE_KEY_LANGUAGE, lang);emitStorageChangedEvent();- window.dispatchEvent(- new CustomEvent("bb.react-locale-change", { detail: lang })- );+ emitReactLocaleChange(lang);}diff --git a/frontend/src/react/components/header/no-vue-deps.test.ts b/frontend/src/react/components/header/no-vue-deps.test.tsindex ba64507883..b93ea2f551 100644--- a/frontend/src/react/components/header/no-vue-deps.test.ts+++ b/frontend/src/react/components/header/no-vue-deps.test.ts@@ -1,10 +1,13 @@import { describe, expect, test } from "vitest";-const sources = import.meta.glob(["./*.{ts,tsx}", "../BytebaseLogo.tsx"], {- query: "?raw",- import: "default",- eager: true,-}) as Record<string, string>;+const sources = import.meta.glob(+ ["./*.{ts,tsx}", "../BytebaseLogo.tsx", "../DashboardSidebar.tsx"],+ {+ query: "?raw",+ import: "default",+ eager: true,+ }+) as Record<string, string>;const appStateSources = import.meta.glob(["../../hooks/useAppState.ts", "../../stores/app/**/*.ts"],@@ -24,7 +27,7 @@ const forbidden = ["@/router",];-describe("React dashboard header dependencies", () => {+describe("React dashboard chrome dependencies", () => {test("does not directly depend on Vue, Pinia, or Vue Router", () => {const violations = [];for (const [file, source] of Object.entries(sources)) {diff --git a/frontend/src/react/hooks/useAppState.ts b/frontend/src/react/hooks/useAppState.tsindex d8a0b23a59..49df41a2d5 100644--- a/frontend/src/react/hooks/useAppState.ts+++ b/frontend/src/react/hooks/useAppState.ts@@ -49,6 +49,10 @@ export function useServerInfo() {return serverInfo;}+export function useIsSaaSMode() {+ return useServerInfo()?.saas ?? false;+}+export function useAppFeature<T extends keyof AppFeatures>(feature: T) {const value = useAppStore((state) => state.appFeatures[feature]);const loadWorkspaceProfile = useAppStore(diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.jsonindex cfeb4dcadb..86a22260f8 100644--- a/frontend/src/react/locales/en-US.json+++ b/frontend/src/react/locales/en-US.json@@ -727,7 +727,37 @@"partition-tables": "Partition tables","partitioned": "Partitioned","revision": {- "filename": "Filename"+ "add-more-files": "Add More",+ "available-files": "Available Files",+ "available-files-description": "Select files to import as new revisions",+ "content-preview": "Content Preview",+ "delete-confirm-dialog": "This will delete these applied revisions and the database schema will not be changed. This action cannot be undone.",+ "drag-drop-or-click": "Drag and drop files here, or click to select",+ "filename": "Filename",+ "files-already-imported": "Already Imported",+ "files-already-imported-description": "These files' versions already exist in the target database and cannot be imported again",+ "from-local-files": "From Local Files",+ "from-local-files-description": "Upload and import database revisions from local SQL files",+ "from-release": "From Release",+ "from-release-description": "Import database revisions from files in a release",+ "import-revision": "Import Revision",+ "invalid-version-format": "Version must be numeric parts separated by dots (e.g., 1.0.0)",+ "no-files-found": "No files found in this release",+ "no-releases-found": "No releases found in this project",+ "revision-type": "Revision Type",+ "select-files": "Select Files",+ "select-files-description": "Select one or more files to create revisions",+ "select-release": "Select Release",+ "select-release-description": "Select a release to import revisions from",+ "select-source": "Select Source",+ "self": "Revision",+ "supported-formats": "Supported: .sql, .txt, .md files",+ "type-declarative": "Declarative",+ "type-versioned": "Versioned",+ "upload-files": "Upload Files",+ "upload-files-description": "Upload SQL files from your local computer to create database revisions",+ "uploaded-files": "Uploaded Files",+ "version-already-exists": "This version already exists in the database"},"row-count-est": "Row count est.","row-count-estimate": "Row count estimate",@@ -3340,8 +3370,10 @@"instance-assignment": {"assign-license": "Assign License","license": "License",+ "manage-license": "Manage Instance License","missing-license-attention": "You need to assign license to the instance to enable this feature.","n-license-remain": "{{n}} remaining",+ "success-notification": "Successfully update license assignment","used-and-total-license": "Assigned / Total Instance License","used-and-total-user": "Active / Total User Limit"},diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.jsonindex f227058074..8c123b07cd 100644--- a/frontend/src/react/locales/es-ES.json+++ b/frontend/src/react/locales/es-ES.json@@ -720,7 +720,37 @@"partition-tables": "Tablas de particiones","partitioned": "Particionado","revision": {- "filename": "Nombre del archivo"+ "add-more-files": "Añadir más",+ "available-files": "Archivos disponibles",+ "available-files-description": "Seleccionar archivos para importar como nuevas revisiones",+ "content-preview": "Vista previa del contenido",+ "delete-confirm-dialog": "Esto eliminará las revisiones aplicadas y el esquema de la base de datos no se modificará. Esta acción no se puede deshacer.",+ "drag-drop-or-click": "Arrastre y suelte archivos aquí, o haga clic para seleccionar",+ "filename": "Nombre del archivo",+ "files-already-imported": "Ya importado",+ "files-already-imported-description": "Las versiones de estos archivos ya existen en la base de datos de destino y no se pueden volver a importar.",+ "from-local-files": "De archivos locales",+ "from-local-files-description": "Cargar e importar revisiones de bases de datos desde archivos SQL locales",+ "from-release": "Desde el lanzamiento",+ "from-release-description": "Importar revisiones de bases de datos desde archivos en una versión",+ "import-revision": "Revisión de importación",+ "invalid-version-format": "La versión debe tener partes numéricas separadas por puntos (por ejemplo, 1.0.0)",+ "no-files-found": "No se encontraron archivos en esta versión",+ "no-releases-found": "No se encontraron lanzamientos en este proyecto",+ "revision-type": "Tipo de revisión",+ "select-files": "Seleccionar archivos",+ "select-files-description": "Seleccione uno o más archivos para crear revisiones",+ "select-release": "Seleccionar lanzamiento",+ "select-release-description": "Seleccione una versión para importar revisiones desde",+ "select-source": "Seleccionar fuente",+ "self": "Revisión",+ "supported-formats": "Compatible con: archivos .sql, .txt, .md",+ "type-declarative": "Declarativo",+ "type-versioned": "Versionado",+ "upload-files": "Subir archivos",+ "upload-files-description": "Cargue archivos SQL desde su computadora local para crear revisiones de base de datos",+ "uploaded-files": "Archivos subidos",+ "version-already-exists": "Esta versión ya existe en la base de datos"},"row-count-est": "Conteo estimado de filas","row-count-estimate": "Estimación de la cantidad de filas",@@ -3326,8 +3356,10 @@"instance-assignment": {"assign-license": "Asignar licencia","license": "Licencia",+ "manage-license": "Administrar licencia","missing-license-attention": "Debe asignar una licencia a la instancia para habilitar esta función.","n-license-remain": "permanecer {{n}}",+ "success-notification": "Actualizar correctamente la asignación de licencia","used-and-total-license": "Licencia asignada / total","used-and-total-user": "Límite de usuarios activos/totales"},diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.jsonindex db7d5354f5..1b2210396f 100644--- a/frontend/src/react/locales/ja-JP.json+++ b/frontend/src/react/locales/ja-JP.json@@ -720,7 +720,37 @@"partition-tables": "パーティションテーブル","partitioned": "パーティション","revision": {- "filename": "ファイル名"+ "add-more-files": "さらに追加",+ "available-files": "利用可能なファイル",+ "available-files-description": "新しいリビジョンとしてインポートするファイルを選択",+ "content-preview": "コンテンツプレビュー",+ "delete-confirm-dialog": "これにより、適用されたリビジョンが削除され、データベース スキーマは変更されません。このアクションは元に戻せません。",+ "drag-drop-or-click": "ファイルをここにドラッグアンドドロップするか、クリックして選択してください",+ "filename": "ファイル名",+ "files-already-imported": "すでにインポート済み",+ "files-already-imported-description": "これらのファイルのバージョンはターゲットデータベースに既に存在するため、再度インポートすることはできません。",+ "from-local-files": "ローカルファイルから",+ "from-local-files-description": "ローカルSQLファイルからデータベースリビジョンをアップロードおよびインポートする",+ "from-release": "リリースより",+ "from-release-description": "リリース内のファイルからデータベースのリビジョンをインポートする",+ "import-revision": "インポートリビジョン",+ "invalid-version-format": "バージョンはドットで区切られた数字部分でなければなりません(例:1.0.0)",+ "no-files-found": "このリリースではファイルが見つかりません",+ "no-releases-found": "このプロジェクトにはリリースが見つかりません",+ "revision-type": "リビジョンタイプ",+ "select-files": "ファイルを選択",+ "select-files-description": "1 つ以上のファイルを選択してリビジョンを作成します",+ "select-release": "リリースを選択",+ "select-release-description": "リビジョンをインポートするリリースを選択してください",+ "select-source": "ソースを選択",+ "self": "リビジョン",+ "supported-formats": "サポート対象: .sql、.txt、.md ファイル",+ "type-declarative": "宣言的",+ "type-versioned": "バージョン管理",+ "upload-files": "ファイルをアップロードする",+ "upload-files-description": "ローカルコンピュータからSQLファイルをアップロードしてデータベースのリビジョンを作成します",+ "uploaded-files": "アップロードされたファイル",+ "version-already-exists": "このバージョンは既にデータベースに存在します"},"row-count-est": "推定行数","row-count-estimate": "推定行数",@@ -3326,8 +3356,10 @@"instance-assignment": {"assign-license": "ライセンスの割り当て","license": "ライセンス",+ "manage-license": "ライセンスの管理","missing-license-attention": "この機能のロックを解除するには、インスタンスにライセンスを割り当ててください。","n-license-remain": "残り {{n}}",+ "success-notification": "ライセンスの割り当てが正常に更新されました","used-and-total-license": "割り当てられた/合計インスタンスライセンス","used-and-total-user": "アクティブ/合計ユーザー制限"},diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.jsonindex 2b760ea697..3eb9fbc1ef 100644--- a/frontend/src/react/locales/vi-VN.json+++ b/frontend/src/react/locales/vi-VN.json@@ -720,7 +720,37 @@"partition-tables": "Bảng phân vùng","partitioned": "Đã phân vùng","revision": {- "filename": "Tên tệp"+ "add-more-files": "Thêm nữa",+ "available-files": "Các tập tin có sẵn",+ "available-files-description": "Chọn các tập tin để nhập dưới dạng bản sửa đổi mới",+ "content-preview": "Xem trước nội dung",+ "delete-confirm-dialog": "Thao tác này sẽ xóa các bản sửa đổi đã áp dụng này và lược đồ cơ sở dữ liệu sẽ không bị thay đổi. Hành động này không thể hoàn tác.",+ "drag-drop-or-click": "Kéo và thả tệp vào đây hoặc nhấp để chọn",+ "filename": "Tên tệp",+ "files-already-imported": "Đã nhập khẩu",+ "files-already-imported-description": "Các phiên bản của các tệp này đã tồn tại trong cơ sở dữ liệu đích và không thể nhập lại được",+ "from-local-files": "Từ các tập tin cục bộ",+ "from-local-files-description": "Tải lên và nhập bản sửa đổi cơ sở dữ liệu từ các tệp SQL cục bộ",+ "from-release": "Từ bản phát hành",+ "from-release-description": "Nhập bản sửa đổi cơ sở dữ liệu từ các tệp trong bản phát hành",+ "import-revision": "Nhập bản sửa đổi",+ "invalid-version-format": "Phiên bản phải là các phần số được phân tách bằng dấu chấm (ví dụ: 1.0.0)",+ "no-files-found": "Không tìm thấy tệp nào trong bản phát hành này",+ "no-releases-found": "Không tìm thấy bản phát hành nào trong dự án này",+ "revision-type": "Loại sửa đổi",+ "select-files": "Chọn tệp",+ "select-files-description": "Chọn một hoặc nhiều tệp để tạo bản sửa đổi",+ "select-release": "Chọn bản phát hành",+ "select-release-description": "Chọn bản phát hành để nhập bản sửa đổi từ",+ "select-source": "Chọn nguồn",+ "self": "Bản sửa đổi",+ "supported-formats": "Được hỗ trợ: các tệp .sql, .txt, .md",+ "type-declarative": "Khai báo",+ "type-versioned": "Phiên bản",+ "upload-files": "Tải lên tập tin",+ "upload-files-description": "Tải lên các tệp SQL từ máy tính cục bộ của bạn để tạo bản sửa đổi cơ sở dữ liệu",+ "uploaded-files": "Tệp đã tải lên",+ "version-already-exists": "Phiên bản này đã tồn tại trong cơ sở dữ liệu"},"row-count-est": "Ước tính số hàng","row-count-estimate": "Ước tính số hàng",@@ -3326,8 +3356,10 @@"instance-assignment": {"assign-license": "Gán giấy phép","license": "Giấy phép",+ "manage-license": "Quản lý giấy phép phiên bản","missing-license-attention": "Bạn cần gán giấy phép cho phiên bản để bật tính năng này.","n-license-remain": "còn lại {{n}}",+ "success-notification": "Đã cập nhật thành công gán giấy phép","used-and-total-license": "Giấy phép phiên bản đã gán / Tổng số","used-and-total-user": "Giới hạn người dùng đang hoạt động / Tổng số"},diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.jsonindex 51e1d0a292..48a02e8636 100644--- a/frontend/src/react/locales/zh-CN.json+++ b/frontend/src/react/locales/zh-CN.json@@ -720,7 +720,37 @@"partition-tables": "分区表","partitioned": "分区","revision": {- "filename": "文件名"+ "add-more-files": "添加更多",+ "available-files": "可用文件",+ "available-files-description": "选择要作为新版本导入的文件",+ "content-preview": "内容预览",+ "delete-confirm-dialog": "这将删除这些已应用的修改,但不会影响数据库 Schema。此操作无法撤消。",+ "drag-drop-or-click": "将文件拖放到此处,或单击选择",+ "filename": "文件名",+ "files-already-imported": "已导入",+ "files-already-imported-description": "这些文件的版本已存在于目标数据库中,无法再次导入",+ "from-local-files": "来自本地文件",+ "from-local-files-description": "从本地 SQL 文件上传并导入数据库版本记录",+ "from-release": "来自发布包",+ "from-release-description": "从发布包的文件中导入数据库版本记录",+ "import-revision": "导入版本",+ "invalid-version-format": "版本必须是用点分隔的数字部分(例如,1.0.0)",+ "no-files-found": "在此发布包中未找到任何文件",+ "no-releases-found": "该项目中未找到任何发布包",+ "revision-type": "类型",+ "select-files": "选择文件",+ "select-files-description": "选择一个或多个文件来创建版本记录",+ "select-release": "选择发布包",+ "select-release-description": "选择要导入发布包",+ "select-source": "选择来源",+ "self": "版本",+ "supported-formats": "支持:.sql、.txt、.md 文件",+ "type-declarative": "声明式",+ "type-versioned": "版本化",+ "upload-files": "上传文件",+ "upload-files-description": "从本地上传 SQL 文件以创建数据库版本记录",+ "uploaded-files": "已上传的文件",+ "version-already-exists": "此版本已存在于数据库中"},"row-count-est": "估算行数","row-count-estimate": "估计行数",@@ -3326,8 +3356,10 @@"instance-assignment": {"assign-license": "分配证书","license": "证书",+ "manage-license": "管理证书","missing-license-attention": "请给实例分配证书以解锁该功能。","n-license-remain": "剩余 {{n}} 个",+ "success-notification": "证书分配更新成功","used-and-total-license": "已分配 / 总实例证书","used-and-total-user": "活跃/总用户限制"},diff --git a/frontend/src/react/no-legacy-vue-deps.test.ts b/frontend/src/react/no-legacy-vue-deps.test.tsnew file mode 100644index 0000000000..31c4127079--- /dev/null+++ b/frontend/src/react/no-legacy-vue-deps.test.ts@@ -0,0 +1,44 @@+import { describe, expect, test } from "vitest";++const sources = import.meta.glob(+ [+ "./pages/project/**/*.{ts,tsx}",+ "./pages/settings/**/*.{ts,tsx}",+ "../router/dashboard/projectV1.ts",+ "../router/dashboard/workspace.ts",+ "../router/dashboard/workspaceSetting.ts",+ ],+ {+ query: "?raw",+ import: "default",+ eager: true,+ }+) as Record<string, string>;++const legacyVueImportPattern =+ /@\/components\/(?:Plan|RolloutV1|IssueV1|PlanCheckRun|DatabaseDetail)\/[^"']+\.vue/g;++const legacyImplementationPaths = [+ "@/components/Plan/components",+ "@/components/RolloutV1/components",+ "@/components/IssueV1/components/RoleGrant",+ "@/components/DatabaseDetail/Settings",+];++describe("React Project and Settings legacy Vue dependencies", () => {+ test("do not import deleted Project Vue implementation paths", () => {+ const violations: string[] = [];+ for (const [file, source] of Object.entries(sources)) {+ const vueImports = source.match(legacyVueImportPattern) ?? [];+ for (const vueImport of vueImports) {+ violations.push(`${file}: ${vueImport}`);+ }+ for (const legacyPath of legacyImplementationPaths) {+ if (source.includes(legacyPath)) {+ violations.push(`${file}: ${legacyPath}`);+ }+ }+ }+ expect(violations).toEqual([]);+ });+});diff --git a/frontend/src/react/pages/auth/MultiFactorPage.test.tsx b/frontend/src/react/pages/auth/MultiFactorPage.test.tsxindex 074eee75ab..038b215288 100644--- a/frontend/src/react/pages/auth/MultiFactorPage.test.tsx+++ b/frontend/src/react/pages/auth/MultiFactorPage.test.tsx@@ -32,10 +32,8 @@ vi.mock("@/router", () => ({},}));-vi.mock("@/utils", async () => {- const actual = await vi.importActual<typeof import("@/utils")>("@/utils");+vi.mock("@/utils", () => {return {- ...actual,resolveWorkspaceName: mocks.resolveWorkspaceName,};});diff --git a/frontend/src/react/pages/auth/OAuthCallbackPage.test.tsx b/frontend/src/react/pages/auth/OAuthCallbackPage.test.tsxindex 29fa3e6d09..8e8ba048a1 100644--- a/frontend/src/react/pages/auth/OAuthCallbackPage.test.tsx+++ b/frontend/src/react/pages/auth/OAuthCallbackPage.test.tsx@@ -46,10 +46,8 @@ vi.mock("@/utils/sso", () => ({clearOAuthState: mocks.clearOAuthState,}));-vi.mock("@/utils", async (importOriginal) => {- const actual = await importOriginal<typeof import("@/utils")>();+vi.mock("@/utils", () => {return {- ...actual,resolveWorkspaceName: mocks.resolveWorkspaceName,};});diff --git a/frontend/src/react/pages/auth/PasswordForgotPage.test.tsx b/frontend/src/react/pages/auth/PasswordForgotPage.test.tsxindex 6fdc5e2814..9d9aa4496f 100644--- a/frontend/src/react/pages/auth/PasswordForgotPage.test.tsx+++ b/frontend/src/react/pages/auth/PasswordForgotPage.test.tsx@@ -60,10 +60,9 @@ vi.mock("@/connect", () => ({},}));-vi.mock("@/utils", async () => {- const actual = await vi.importActual<typeof import("@/utils")>("@/utils");+vi.mock("@/utils", () => {return {- ...actual,+ isValidEmail: (email: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email),resolveWorkspaceName: mocks.resolveWorkspaceName,};});diff --git a/frontend/src/react/pages/auth/PasswordResetPage.test.tsx b/frontend/src/react/pages/auth/PasswordResetPage.test.tsxindex 4da3c202b2..cd3daee940 100644--- a/frontend/src/react/pages/auth/PasswordResetPage.test.tsx+++ b/frontend/src/react/pages/auth/PasswordResetPage.test.tsx@@ -66,10 +66,8 @@ vi.mock("@/connect", () => ({},}));-vi.mock("@/utils", async (importOriginal) => {- const actual = await importOriginal<typeof import("@/utils")>();+vi.mock("@/utils", () => {return {- ...actual,resolveWorkspaceName: mocks.resolveWorkspaceName,};});diff --git a/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx b/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsxindex 3234323ac5..aa080c7f87 100644--- a/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx+++ b/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx@@ -7,6 +7,7 @@ import {PROJECT_DATABASE_DETAIL_TAB_REVISION,PROJECT_DATABASE_DETAIL_TAB_SETTING,} from "./database-detail/tabs";+import { ProjectDatabaseDetailPage } from "./ProjectDatabaseDetailPage";(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }@@ -186,10 +187,6 @@ let latestTabsOnValueChange:| ((tab: string | number | null) => void)| undefined;-type ProjectDatabaseDetailPageComponent =- typeof import("./ProjectDatabaseDetailPage").ProjectDatabaseDetailPage;-let ProjectDatabaseDetailPage: ProjectDatabaseDetailPageComponent;-vi.mock("lucide-react", async (importOriginal) => {const actual = await importOriginal<typeof import("lucide-react")>();return {@@ -524,11 +521,6 @@ beforeEach(() => {latestTabsOnValueChange = undefined;});-beforeEach(async () => {- vi.resetModules();- ({ ProjectDatabaseDetailPage } = await import("./ProjectDatabaseDetailPage"));-});-describe("ProjectDatabaseDetailPage", () => {test("shows a spinner while the shared database hook is loading", async () => {mocks.useProjectDatabaseDetail.mockReturnValue({diff --git a/frontend/src/react/pages/project/database-detail/legacy/DatabaseObjectExplorer.vue b/frontend/src/react/pages/project/database-detail/legacy/DatabaseObjectExplorer.vuedeleted file mode 100644index 7e5ed073dd..0000000000--- a/frontend/src/react/pages/project/database-detail/legacy/DatabaseObjectExplorer.vue+++ /dev/null@@ -1,302 +0,0 @@-<template>- <div>- <div- v-if="hasSchemaPropertyV1"- class="mb-4 flex flex-row items-center justify-start"- >- <span class="mr-2 text-lg leading-6 font-medium text-main">- {{ $t("common.schema") }}- </span>- <NSelect- :value="selectedSchemaName"- :options="schemaNameOptions"- :disabled="loading"- :placeholder="$t('database.schema.select')"- class="w-auto! min-w-48"- @update:value="- $emit('update:selected-schema-name', (($event as string) ?? '').trim())- "- />- </div>-- <template v-if="databaseEngine !== Engine.REDIS">- <div class="mb-4 flex w-full flex-row items-center justify-between">- <div class="text-lg leading-6 font-medium text-main">- <span v-if="databaseEngine === Engine.MONGODB">- {{ $t("db.collections") }}- </span>- <span v-else>{{ $t("db.tables") }}</span>- </div>- <SearchBox- :value="tableSearchKeyword"- :placeholder="$t('common.filter-by-name')"- :disabled="loading"- @update:value="$emit('update:table-search-keyword', $event)"- />- </div>-- <TableDataTable- :database="database"- :schema-name="selectedSchemaName"- :table-list="tableList"- :search="tableSearchKeyword.trim().toLowerCase()"- :loading="loading"- />-- <div class="mb-4 mt-6 text-lg leading-6 font-medium text-main">- {{ $t("db.views") }}- </div>- <ViewDataTable- :database="database"- :schema-name="selectedSchemaName"- :view-list="viewList"- :loading="loading"- />-- <template- v-if="- databaseEngine === Engine.POSTGRES || databaseEngine === Engine.HIVE- "- >- <div class="mb-4 mt-6 flex w-full flex-row items-center justify-between">- <div class="text-lg leading-6 font-medium text-main">- {{ $t("db.external-tables") }}- </div>- <SearchBox- :value="externalTableSearchKeyword"- :placeholder="$t('common.filter-by-name')"- :disabled="loading"- @update:value="$emit('update:external-table-search-keyword', $event)"- />- </div>- <ExternalTableDataTable- :database="database"- :schema-name="selectedSchemaName"- :external-table-list="externalTableList"- :search="externalTableSearchKeyword.trim().toLowerCase()"- :loading="loading"- />- </template>-- <template v-if="databaseEngine === Engine.POSTGRES">- <div class="mb-4 mt-6 text-lg leading-6 font-medium text-main">- {{ $t("db.extensions") }}- </div>- <DBExtensionDataTable- :db-extension-list="dbExtensionList"- :loading="loading"- />- </template>-- <template- v-if="- databaseEngine === Engine.POSTGRES || databaseEngine === Engine.MSSQL- "- >- <div class="mb-4 mt-6 text-lg leading-6 font-medium text-main">- {{ $t("db.functions") }}- </div>- <FunctionDataTable- :database="database"- :schema-name="selectedSchemaName"- :function-list="functionList"- :loading="loading"- />- </template>-- <template v-if="instanceV1SupportsSequence(databaseEngine)">- <div class="mb-4 mt-6 text-lg leading-6 font-medium text-main">- {{ $t("db.sequences") }}- </div>- <SequenceDataTable- :database="database"- :schema-name="selectedSchemaName"- :sequence-list="sequenceList"- :loading="loading"- />- </template>-- <template v-if="databaseEngine === Engine.SNOWFLAKE">- <div class="mb-4 mt-6 text-lg leading-6 font-medium text-main">- {{ $t("db.streams") }}- </div>- <StreamTable- :database="database"- :schema-name="selectedSchemaName"- :stream-list="streamList"- :loading="loading"- />-- <div class="mb-4 mt-6 text-lg leading-6 font-medium text-main">- {{ $t("db.tasks") }}- </div>- <TaskTable- :database="database"- :schema-name="selectedSchemaName"- :task-list="taskList"- :loading="loading"- />- </template>-- <template v-if="instanceV1SupportsPackage(databaseEngine)">- <div class="mb-4 mt-6 text-lg leading-6 font-medium text-main">- {{ $t("db.packages") }}- </div>- <PackageDataTable- :database="database"- :schema-name="selectedSchemaName"- :package-list="packageList"- :loading="loading"- />- </template>- </template>- </div>-</template>-<script setup lang="ts">-import { NSelect } from "naive-ui";-import { computed } from "vue";-import { useI18n } from "vue-i18n";-import DBExtensionDataTable from "@/components/DBExtensionDataTable.vue";-import ExternalTableDataTable from "@/components/ExternalTableDataTable.vue";-import FunctionDataTable from "@/components/FunctionDataTable.vue";-import PackageDataTable from "@/components/PackageDataTable.vue";-import SequenceDataTable from "@/components/SequenceDataTable.vue";-import StreamTable from "@/components/StreamTable.vue";-import TableDataTable from "@/components/TableDataTable.vue";-import TaskTable from "@/components/TaskTable.vue";-import ViewDataTable from "@/components/ViewDataTable.vue";-import { SearchBox } from "@/components/v2";-import { useDBSchemaV1Store } from "@/store";-import { Engine } from "@/types/proto-es/v1/common_pb";-import type { Database } from "@/types/proto-es/v1/database_service_pb";-import {- getDatabaseEngine,- hasSchemaProperty,- instanceV1SupportsPackage,- instanceV1SupportsSequence,-} from "@/utils";--const props = defineProps<{- database: Database;- loading: boolean;- selectedSchemaName: string;- tableSearchKeyword: string;- externalTableSearchKeyword: string;-}>();--defineEmits<{- (event: "update:selected-schema-name", value: string): void;- (event: "update:table-search-keyword", value: string): void;- (event: "update:external-table-search-keyword", value: string): void;-}>();--const dbSchemaStore = useDBSchemaV1Store();-const { t } = useI18n();--const databaseEngine = computed(() => {- return getDatabaseEngine(props.database);-});--const hasSchemaPropertyV1 = computed(() => {- return hasSchemaProperty(databaseEngine.value);-});--const schemaList = computed(() => {- return dbSchemaStore.getSchemaList(props.database.name);-});--const schemaNameOptions = computed(() => {- return schemaList.value.map((schema) => ({- value: schema.name,- label: schema.name || t("db.schema.default"),- }));-});--const tableList = computed(() => {- return dbSchemaStore.getTableList({- database: props.database.name,- schema: props.selectedSchemaName,- });-});--const viewList = computed(() => {- return dbSchemaStore.getViewList({- database: props.database.name,- schema: props.selectedSchemaName,- });-});--const dbExtensionList = computed(() => {- return dbSchemaStore.getExtensionList(props.database.name);-});--const externalTableList = computed(() => {- return dbSchemaStore.getExternalTableList({- database: props.database.name,- schema: props.selectedSchemaName,- });-});--const functionList = computed(() => {- return dbSchemaStore.getFunctionList({- database: props.database.name,- schema: props.selectedSchemaName,- });-});--const streamList = computed(() => {- if (hasSchemaPropertyV1.value) {- return (- schemaList.value.find(- (schema) => schema.name === props.selectedSchemaName- )?.streams || []- );- }- return dbSchemaStore- .getDatabaseMetadata(props.database.name)- .schemas.map((schema) => schema.streams)- .flat();-});--const taskList = computed(() => {- if (hasSchemaPropertyV1.value) {- return (- schemaList.value.find(- (schema) => schema.name === props.selectedSchemaName- )?.tasks || []- );- }- return dbSchemaStore- .getDatabaseMetadata(props.database.name)- .schemas.map((schema) => schema.tasks)- .flat();-});--const packageList = computed(() => {- if (hasSchemaPropertyV1.value) {- return (- schemaList.value.find(- (schema) => schema.name === props.selectedSchemaName- )?.packages || []- );- }- return dbSchemaStore- .getDatabaseMetadata(props.database.name)- .schemas.map((schema) => schema.packages)- .flat();-});--const sequenceList = computed(() => {- if (hasSchemaPropertyV1.value) {- return (- schemaList.value.find(- (schema) => schema.name === props.selectedSchemaName- )?.sequences || []- );- }- return dbSchemaStore- .getDatabaseMetadata(props.database.name)- .schemas.map((schema) => schema.sequences)- .flat();-});-</script>diff --git a/frontend/src/react/pages/project/database-detail/panels/DatabaseRevisionPanel.tsx b/frontend/src/react/pages/project/database-detail/panels/DatabaseRevisionPanel.tsxindex b3e375b5b4..51122f7c8c 100644--- a/frontend/src/react/pages/project/database-detail/panels/DatabaseRevisionPanel.tsx+++ b/frontend/src/react/pages/project/database-detail/panels/DatabaseRevisionPanel.tsx@@ -1,14 +1,7 @@import { create } from "@bufbuild/protobuf";-import { NConfigProvider } from "naive-ui";import { useCallback, useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";-import { createApp, h, reactive } from "vue";-import { themeOverrides } from "@/../naive-ui.config";-import BBOverlayStack from "@/components/misc/OverlayStackManager.vue";-import CreateRevisionDrawer from "@/components/Revision/CreateRevisionDrawer.vue";import { revisionServiceClientConnect } from "@/connect";-import i18n from "@/plugins/i18n";-import NaiveUI from "@/plugins/naive-ui";import {AlertDialog,AlertDialogContent,@@ -18,90 +11,18 @@ import {} from "@/react/components/ui/alert-dialog";import { Button } from "@/react/components/ui/button";import { PagedTableFooter, usePagedData } from "@/react/hooks/usePagedData";-import { router } from "@/router";-import { pinia, useRevisionStore } from "@/store";+import { useRevisionStore } from "@/store";import type { Database } from "@/types/proto-es/v1/database_service_pb";import type { Revision } from "@/types/proto-es/v1/revision_service_pb";import { ListRevisionsRequestSchema } from "@/types/proto-es/v1/revision_service_pb";import { DatabaseRevisionTable } from "../revision/DatabaseRevisionTable";--function VueCreateRevisionDrawerMount({- databaseName,- open,- onCreated,- onOpenChange,-}: {- databaseName: string;- open: boolean;- onCreated: (revisions: Revision[]) => void;- onOpenChange: (open: boolean) => void;-}) {- const containerRef = useRef<HTMLDivElement>(null);- const bridgeStateRef = useRef(- reactive({- databaseName,- onCreated,- onOpenChange,- open,- })- );-- useEffect(() => {- const bridgeState = bridgeStateRef.current;- bridgeState.databaseName = databaseName;- bridgeState.onCreated = onCreated;- bridgeState.onOpenChange = onOpenChange;- bridgeState.open = open;- }, [databaseName, onCreated, onOpenChange, open]);-- useEffect(() => {- if (!containerRef.current) {- return;- }-- const bridgeState = bridgeStateRef.current;-- const app = createApp({- render() {- return h(- NConfigProvider as never,- { themeOverrides: themeOverrides.value },- {- default: () =>- h(- BBOverlayStack as never,- {},- {- default: () =>- h(CreateRevisionDrawer as never, {- database: bridgeState.databaseName,- show: bridgeState.open,- "onUpdate:show": bridgeState.onOpenChange,- onCreated: bridgeState.onCreated,- }),- }- ),- }- );- },- });- app.use(router).use(pinia).use(i18n).use(NaiveUI);- app.mount(containerRef.current);-- return () => {- app.unmount();- };- }, []);-- return <div ref={containerRef} />;-}+import { ImportRevisionSheet } from "../revision/ImportRevisionSheet";export function DatabaseRevisionPanel({ database }: { database: Database }) {const { t } = useTranslation();const revisionStore = useRevisionStore();const [showCreateRevisionDrawer, setShowCreateRevisionDrawer] =useState(false);- const [drawerEverOpened, setDrawerEverOpened] = useState(false);const [selectedNames, setSelectedNames] = useState<Set<string>>(new Set());const fetchRevisionList = useCallback(async ({@@ -168,7 +89,6 @@ export function DatabaseRevisionPanel({ database }: { database: Database }) {<div /><ButtononClick={() => {- setDrawerEverOpened(true);setShowCreateRevisionDrawer(true);}}>@@ -230,14 +150,13 @@ export function DatabaseRevisionPanel({ database }: { database: Database }) {</AlertDialogContent></AlertDialog>- {drawerEverOpened && (- <VueCreateRevisionDrawerMount- databaseName={database.name}- open={showCreateRevisionDrawer}- onCreated={handleRevisionCreated}- onOpenChange={setShowCreateRevisionDrawer}- />- )}+ <ImportRevisionSheet+ databaseName={database.name}+ projectName={database.project}+ open={showCreateRevisionDrawer}+ onCreated={handleRevisionCreated}+ onOpenChange={setShowCreateRevisionDrawer}+ /></>);}diff --git a/frontend/src/react/pages/project/database-detail/revision/ImportRevisionSheet.tsx b/frontend/src/react/pages/project/database-detail/revision/ImportRevisionSheet.tsxnew file mode 100644index 0000000000..5002cd3cde--- /dev/null+++ b/frontend/src/react/pages/project/database-detail/revision/ImportRevisionSheet.tsx@@ -0,0 +1,879 @@+import { create } from "@bufbuild/protobuf";+import { File, FolderOpen, Package, Plus, X } from "lucide-react";+import {+ type ChangeEvent,+ type DragEvent,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { useTranslation } from "react-i18next";+import { revisionServiceClientConnect } from "@/connect";+import { ReleaseFileTable } from "@/react/components/release/ReleaseFileTable";+import { Button } from "@/react/components/ui/button";+import { Input } from "@/react/components/ui/input";+import {+ Sheet,+ SheetBody,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetTitle,+} from "@/react/components/ui/sheet";+import { cn } from "@/react/lib/utils";+import {+ pushNotification,+ useReleaseStore,+ useRevisionStore,+ useSheetV1Store,+} from "@/store";+import type {+ Release,+ Release_File,+} from "@/types/proto-es/v1/release_service_pb";+import { Release_Type } from "@/types/proto-es/v1/release_service_pb";+import type {+ CreateRevisionRequest,+ Revision,+} from "@/types/proto-es/v1/revision_service_pb";+import {+ BatchCreateRevisionsRequestSchema,+ CreateRevisionRequestSchema,+ Revision_Type,+} from "@/types/proto-es/v1/revision_service_pb";++enum Step {+ SELECT_SOURCE = 1,+ SELECT_RELEASE = 2,+ SELECT_FILES = 3,+ UPLOAD_FILES = 4,+}++interface LocalFile {+ name: string;+ size: number;+ content: string;+ version: string;+ type: Revision_Type;+}++export function ImportRevisionSheet({+ databaseName,+ projectName,+ open,+ onOpenChange,+ onCreated,+}: {+ databaseName: string;+ projectName: string;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onCreated: (revisions: Revision[]) => void;+}) {+ const { t } = useTranslation();+ const releaseStore = useReleaseStore();+ const revisionStore = useRevisionStore();+ const sheetStore = useSheetV1Store();+ const fileInputRef = useRef<HTMLInputElement>(null);++ const [selectedSource, setSelectedSource] = useState<"release" | "local">(+ "release"+ );+ const [currentStep, setCurrentStep] = useState(Step.SELECT_SOURCE);+ const [loadingReleases, setLoadingReleases] = useState(false);+ const [creating, setCreating] = useState(false);+ const [releaseList, setReleaseList] = useState<Release[]>([]);+ const [selectedRelease, setSelectedRelease] = useState<Release | null>(null);+ const [selectedFiles, setSelectedFiles] = useState<Release_File[]>([]);+ const [existingVersions, setExistingVersions] = useState<Set<string>>(+ new Set()+ );+ const [localFiles, setLocalFiles] = useState<LocalFile[]>([]);++ const loadExistingRevisions = useCallback(async () => {+ try {+ const revisions = await revisionStore.fetchAllRevisionsByDatabase(+ databaseName,+ { pageSize: 1000 }+ );+ setExistingVersions(+ new Set(revisions.map((revision) => revision.version).filter(Boolean))+ );+ } catch (error) {+ console.error("Failed to load existing revisions:", error);+ }+ }, [databaseName, revisionStore]);++ const loadReleases = useCallback(async () => {+ setLoadingReleases(true);+ try {+ const { releases } = await releaseStore.fetchReleasesByProject(+ projectName,+ { pageSize: 100 }+ );+ setReleaseList(releases);+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.error"),+ description: error instanceof Error ? error.message : String(error),+ });+ } finally {+ setLoadingReleases(false);+ }+ }, [projectName, releaseStore, t]);++ useEffect(() => {+ if (!open) {+ return;+ }+ setSelectedSource("release");+ setCurrentStep(Step.SELECT_SOURCE);+ setCreating(false);+ setReleaseList([]);+ setSelectedRelease(null);+ setSelectedFiles([]);+ setLocalFiles([]);+ setExistingVersions(new Set());+ loadExistingRevisions();+ }, [loadExistingRevisions, open]);++ const selectableFiles = useMemo(() => {+ return selectedRelease+ ? selectedRelease.files.filter(+ (file) => !existingVersions.has(file.version)+ )+ : [];+ }, [existingVersions, selectedRelease]);++ const filesWithExistingVersions = useMemo(() => {+ return selectedRelease+ ? selectedRelease.files.filter((file) =>+ existingVersions.has(file.version)+ )+ : [];+ }, [existingVersions, selectedRelease]);++ const validateVersion = (version: string): boolean => {+ if (!version) {+ return false;+ }+ return /^(\d+)(\.(\d+))*$/.test(version);+ };++ const isVersionDuplicate = useCallback(+ (version: string): boolean => existingVersions.has(version),+ [existingVersions]+ );++ const canProceedToNextStep =+ currentStep === Step.SELECT_SOURCE ||+ (currentStep === Step.SELECT_RELEASE && !!selectedRelease);+ const isLastStep =+ selectedSource === "local"+ ? currentStep === Step.UPLOAD_FILES+ : currentStep === Step.SELECT_FILES;+ const canSubmit =+ selectedSource === "local"+ ? localFiles.length > 0 &&+ localFiles.every(+ (file) =>+ validateVersion(file.version) &&+ !isVersionDuplicate(file.version) &&+ file.content+ )+ : selectedFiles.length > 0;++ const handleNextStep = useCallback(async () => {+ if (currentStep === Step.SELECT_SOURCE) {+ if (selectedSource === "local") {+ setCurrentStep(Step.UPLOAD_FILES);+ } else {+ setCurrentStep(Step.SELECT_RELEASE);+ await loadReleases();+ }+ return;+ }+ if (currentStep === Step.SELECT_RELEASE && selectedRelease) {+ setSelectedFiles([]);+ setCurrentStep(Step.SELECT_FILES);+ }+ }, [currentStep, loadReleases, selectedRelease, selectedSource]);++ const handlePrevStep = useCallback(() => {+ if (+ currentStep === Step.SELECT_RELEASE ||+ currentStep === Step.UPLOAD_FILES+ ) {+ setCurrentStep(Step.SELECT_SOURCE);+ return;+ }+ if (currentStep === Step.SELECT_FILES) {+ setCurrentStep(Step.SELECT_RELEASE);+ }+ }, [currentStep]);++ const readFileContent = (file: globalThis.File): Promise<string> =>+ new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = (event) => resolve(event.target?.result as string);+ reader.onerror = reject;+ reader.readAsText(file);+ });++ const processFiles = useCallback(+ async (files: globalThis.File[]) => {+ const nextFiles: LocalFile[] = [];+ for (const file of files) {+ const extension = file.name.split(".").pop()?.toLowerCase();+ if (!["sql", "txt", "md"].includes(extension || "")) {+ pushNotification({+ module: "bytebase",+ style: "WARN",+ title: t("common.warning"),+ description: file.name,+ });+ continue;+ }+ if (+ localFiles.some((localFile) => localFile.name === file.name) ||+ nextFiles.some((localFile) => localFile.name === file.name)+ ) {+ continue;+ }+ try {+ const content = await readFileContent(file);+ nextFiles.push({+ name: file.name,+ size: file.size,+ content,+ version: extractVersionFromFilename(file.name),+ type: Revision_Type.VERSIONED,+ });+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.error"),+ description: error instanceof Error ? error.message : String(error),+ });+ }+ }+ if (nextFiles.length > 0) {+ setLocalFiles((prev) => [...prev, ...nextFiles]);+ }+ },+ [localFiles, t]+ );++ const handleFileSelect = async (event: ChangeEvent<HTMLInputElement>) => {+ if (event.target.files) {+ await processFiles(Array.from(event.target.files));+ }+ event.target.value = "";+ };++ const handleFileDrop = async (event: DragEvent<HTMLDivElement>) => {+ event.preventDefault();+ if (event.dataTransfer.files) {+ await processFiles(Array.from(event.dataTransfer.files));+ }+ };++ const handleConfirm = useCallback(async () => {+ if (!canSubmit || creating) {+ return;+ }+ setCreating(true);+ try {+ let requests: CreateRevisionRequest[] = [];+ if (selectedSource === "local") {+ for (const file of localFiles) {+ const sheet = await sheetStore.createSheet(projectName, {+ content: new TextEncoder().encode(file.content),+ });+ requests.push(+ create(CreateRevisionRequestSchema, {+ parent: databaseName,+ revision: {+ version: file.version,+ sheet: sheet.name,+ type: file.type,+ },+ })+ );+ }+ } else if (selectedRelease) {+ requests = selectedFiles.map((file) =>+ create(CreateRevisionRequestSchema, {+ parent: databaseName,+ revision: {+ release: selectedRelease.name,+ version: file.version,+ file: `${selectedRelease.name}/files/${encodeURIComponent(file.path)}`,+ sheet: file.sheet,+ type: mapReleaseTypeToRevisionType(selectedRelease.type),+ },+ })+ );+ }+ if (requests.length === 0) {+ return;+ }+ const response = await revisionServiceClientConnect.batchCreateRevisions(+ create(BatchCreateRevisionsRequestSchema, {+ parent: databaseName,+ requests,+ })+ );+ onCreated(response.revisions);+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.created"),+ });+ onOpenChange(false);+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.error"),+ description: error instanceof Error ? error.message : String(error),+ });+ } finally {+ setCreating(false);+ }+ }, [+ canSubmit,+ creating,+ databaseName,+ localFiles,+ onCreated,+ onOpenChange,+ projectName,+ selectedFiles,+ selectedRelease,+ selectedSource,+ sheetStore,+ t,+ ]);++ return (+ <Sheet open={open} onOpenChange={onOpenChange}>+ <SheetContent width="wide" className="max-w-[90vw]">+ <SheetHeader>+ <SheetTitle>{t("database.revision.import-revision")}</SheetTitle>+ </SheetHeader>+ <SheetBody className="gap-y-4">+ <StepIndicator source={selectedSource} currentStep={currentStep} />+ {currentStep === Step.SELECT_SOURCE && (+ <SourceSelector+ selectedSource={selectedSource}+ onSelectedSourceChange={setSelectedSource}+ />+ )}+ {currentStep === Step.SELECT_RELEASE && (+ <ReleaseSelector+ releases={releaseList}+ selectedRelease={selectedRelease}+ loading={loadingReleases}+ onSelectedReleaseChange={setSelectedRelease}+ />+ )}+ {currentStep === Step.SELECT_FILES && selectedRelease && (+ <div className="flex flex-col gap-y-4">+ <div className="text-sm text-control-light">+ {t("database.revision.select-files-description")}+ </div>+ {selectableFiles.length > 0 && (+ <div className="flex flex-col gap-y-3">+ <div>+ <h4 className="font-medium text-control">+ {t("database.revision.available-files")}+ {selectableFiles.length > 1+ ? ` (${selectableFiles.length})`+ : ""}+ </h4>+ <p className="mt-1 text-sm text-control-light">+ {t("database.revision.available-files-description")}+ </p>+ </div>+ <ReleaseFileTable+ files={selectableFiles}+ releaseType={selectedRelease.type}+ showSelection+ selectedFiles={selectedFiles}+ onSelectedFilesChange={setSelectedFiles}+ />+ </div>+ )}+ {filesWithExistingVersions.length > 0 && (+ <div className="mt-4 flex flex-col gap-y-3">+ <div>+ <h4 className="font-medium text-control">+ {t("database.revision.files-already-imported")}+ {filesWithExistingVersions.length > 1+ ? ` (${filesWithExistingVersions.length})`+ : ""}+ </h4>+ <p className="mt-1 text-sm text-control-light">+ {t(+ "database.revision.files-already-imported-description"+ )}+ </p>+ </div>+ <ReleaseFileTable+ files={filesWithExistingVersions}+ releaseType={selectedRelease.type}+ showSelection={false}+ rowClickable={false}+ />+ </div>+ )}+ {selectedRelease.files.length === 0 && (+ <EmptyState+ icon={<Package className="size-12 text-control-light" />}+ text={t("database.revision.no-files-found")}+ />+ )}+ </div>+ )}+ {currentStep === Step.UPLOAD_FILES && (+ <LocalFileUpload+ files={localFiles}+ fileInputRef={fileInputRef}+ isVersionDuplicate={isVersionDuplicate}+ validateVersion={validateVersion}+ onFileDrop={handleFileDrop}+ onFileSelect={handleFileSelect}+ onAddFiles={() => fileInputRef.current?.click()}+ onFilesChange={setLocalFiles}+ />+ )}+ </SheetBody>+ <SheetFooter>+ {currentStep === Step.SELECT_SOURCE ? (+ <Button variant="ghost" onClick={() => onOpenChange(false)}>+ {t("common.close")}+ </Button>+ ) : (+ <Button variant="ghost" onClick={handlePrevStep}>+ {t("common.back")}+ </Button>+ )}+ {!isLastStep ? (+ <Button disabled={!canProceedToNextStep} onClick={handleNextStep}>+ {t("common.next")}+ </Button>+ ) : (+ <Button disabled={!canSubmit || creating} onClick={handleConfirm}>+ {t("common.confirm")}+ </Button>+ )}+ </SheetFooter>+ </SheetContent>+ </Sheet>+ );+}++function StepIndicator({+ source,+ currentStep,+}: {+ source: "release" | "local";+ currentStep: Step;+}) {+ const { t } = useTranslation();+ const steps =+ source === "release"+ ? [+ [Step.SELECT_SOURCE, t("database.revision.select-source")],+ [Step.SELECT_RELEASE, t("database.revision.select-release")],+ [Step.SELECT_FILES, t("database.revision.select-files")],+ ]+ : [+ [Step.SELECT_SOURCE, t("database.revision.select-source")],+ [Step.UPLOAD_FILES, t("database.revision.upload-files")],+ ];+ return (+ <ol className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">+ {steps.map(([step, label], index) => (+ <li key={step} className="flex items-center gap-x-2">+ <span+ className={cn(+ "inline-flex size-6 items-center justify-center rounded-full border text-xs",+ step === currentStep+ ? "border-accent bg-accent text-accent-text"+ : "border-control-border text-control-light"+ )}+ >+ {index + 1}+ </span>+ <span+ className={+ step === currentStep ? "text-control" : "text-control-light"+ }+ >+ {label}+ </span>+ </li>+ ))}+ </ol>+ );+}++function SourceSelector({+ selectedSource,+ onSelectedSourceChange,+}: {+ selectedSource: "release" | "local";+ onSelectedSourceChange: (source: "release" | "local") => void;+}) {+ const { t } = useTranslation();+ return (+ <div role="radiogroup" className="flex flex-col gap-y-4">+ <SourceOption+ value="release"+ selected={selectedSource === "release"}+ icon={<Package className="mt-1 size-6 shrink-0" strokeWidth={1.5} />}+ title={t("database.revision.from-release")}+ description={t("database.revision.from-release-description")}+ onSelect={onSelectedSourceChange}+ />+ <SourceOption+ value="local"+ selected={selectedSource === "local"}+ icon={<FolderOpen className="mt-1 size-6 shrink-0" strokeWidth={1.5} />}+ title={t("database.revision.from-local-files")}+ description={t("database.revision.from-local-files-description")}+ onSelect={onSelectedSourceChange}+ />+ </div>+ );+}++function SourceOption({+ value,+ selected,+ icon,+ title,+ description,+ onSelect,+}: {+ value: "release" | "local";+ selected: boolean;+ icon: React.ReactNode;+ title: string;+ description: string;+ onSelect: (source: "release" | "local") => void;+}) {+ return (+ <button+ type="button"+ role="radio"+ aria-checked={selected}+ className={cn(+ "w-full rounded-sm border border-control-border p-4 text-left transition-colors",+ selected && "border-accent bg-control-bg"+ )}+ onClick={() => onSelect(value)}+ >+ <div className="flex items-start gap-x-3">+ <span+ className={cn(+ "mt-1 flex size-4 items-center justify-center rounded-full border border-control-border",+ selected && "border-[5px] border-accent"+ )}+ />+ {icon}+ <div className="flex-1">+ <div className="text-lg font-medium text-control">{title}</div>+ <p className="mt-1 text-sm text-control-light">{description}</p>+ </div>+ </div>+ </button>+ );+}++function ReleaseSelector({+ releases,+ selectedRelease,+ loading,+ onSelectedReleaseChange,+}: {+ releases: Release[];+ selectedRelease: Release | null;+ loading: boolean;+ onSelectedReleaseChange: (release: Release | null) => void;+}) {+ const { t } = useTranslation();+ if (loading) {+ return <EmptyState text={t("common.loading")} />;+ }+ if (releases.length === 0) {+ return (+ <EmptyState+ icon={<Package className="size-12 text-control-light" />}+ text={t("database.revision.no-releases-found")}+ />+ );+ }+ return (+ <div className="flex flex-col gap-y-4">+ <div className="text-sm text-control-light">+ {t("database.revision.select-release-description")}+ </div>+ <div className="overflow-x-auto rounded-sm border border-control-border">+ <table className="w-full text-sm">+ <thead>+ <tr className="border-b border-control-border bg-control-bg text-left">+ <th className="w-10 px-4 py-2" />+ <th className="px-4 py-2 font-medium">{t("common.name")}</th>+ <th className="px-4 py-2 font-medium">{t("release.files")}</th>+ </tr>+ </thead>+ <tbody>+ {releases.map((release) => (+ <tr+ key={release.name}+ className="cursor-pointer border-b border-control-border last:border-b-0 hover:bg-control-bg"+ onClick={() => onSelectedReleaseChange(release)}+ >+ <td className="px-4 py-2">+ <input+ type="radio"+ checked={selectedRelease?.name === release.name}+ onChange={() => onSelectedReleaseChange(release)}+ className="border-control-border"+ />+ </td>+ <td className="px-4 py-2">{release.name.split("/").pop()}</td>+ <td className="px-4 py-2">{release.files.length}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ );+}++function LocalFileUpload({+ files,+ fileInputRef,+ isVersionDuplicate,+ validateVersion,+ onFileDrop,+ onFileSelect,+ onAddFiles,+ onFilesChange,+}: {+ files: LocalFile[];+ fileInputRef: React.RefObject<HTMLInputElement | null>;+ isVersionDuplicate: (version: string) => boolean;+ validateVersion: (version: string) => boolean;+ onFileDrop: (event: DragEvent<HTMLDivElement>) => void;+ onFileSelect: (event: ChangeEvent<HTMLInputElement>) => void;+ onAddFiles: () => void;+ onFilesChange: (files: LocalFile[]) => void;+}) {+ const { t } = useTranslation();+ return (+ <div className="flex flex-col gap-y-4">+ <div className="text-sm text-control-light">+ {t("database.revision.upload-files-description")}+ </div>+ <input+ ref={fileInputRef}+ type="file"+ multiple+ accept=".sql,.txt,.md,text/plain,text/markdown,text/x-sql"+ className="hidden"+ onChange={onFileSelect}+ />+ {files.length === 0 && (+ <div+ className="cursor-pointer rounded-sm border-2 border-dashed border-control-border p-6 text-center transition-colors hover:border-accent"+ onClick={onAddFiles}+ onDragOver={(event) => event.preventDefault()}+ onDrop={onFileDrop}+ >+ <FolderOpen className="mx-auto mb-3 size-12 text-control-light" />+ <p className="text-sm text-control-light">+ {t("database.revision.drag-drop-or-click")}+ </p>+ <p className="mt-1 text-xs text-control-placeholder">+ {t("database.revision.supported-formats")}+ </p>+ </div>+ )}+ {files.length > 0 && (+ <div className="flex flex-col gap-y-3">+ <div className="flex items-center justify-between">+ <h4 className="font-medium text-control">+ {t("database.revision.uploaded-files")}+ {files.length > 1 ? ` (${files.length})` : ""}+ </h4>+ <Button size="sm" variant="outline" onClick={onAddFiles}>+ <Plus className="size-4" />+ {t("database.revision.add-more-files")}+ </Button>+ </div>+ {files.map((file, index) => (+ <div+ key={file.name}+ className="flex flex-col gap-y-3 rounded-sm border border-control-border p-4"+ >+ <div className="flex items-start justify-between gap-x-3">+ <div className="flex flex-1 flex-col gap-y-3">+ <div className="flex items-center gap-x-2">+ <File className="size-4 text-control-light" />+ <span className="text-sm font-medium">{file.name}</span>+ <span className="text-xs text-control-light">+ ({formatFileSize(file.size)})+ </span>+ </div>+ <div className="grid grid-cols-4 gap-x-3">+ <label className="col-span-3 flex flex-col gap-y-1">+ <span className="text-xs text-control-light">+ {t("common.version")} *+ </span>+ <Input+ value={file.version}+ onChange={(event) => {+ const next = [...files];+ next[index] = {+ ...file,+ version: event.target.value,+ };+ onFilesChange(next);+ }}+ />+ {file.version && !validateVersion(file.version) && (+ <span className="text-xs text-error">+ {t("database.revision.invalid-version-format")}+ </span>+ )}+ {file.version && isVersionDuplicate(file.version) && (+ <span className="text-xs text-error">+ {t("database.revision.version-already-exists")}+ </span>+ )}+ </label>+ <label className="flex flex-col gap-y-1">+ <span className="text-xs text-control-light">+ {t("database.revision.revision-type")}+ </span>+ <select+ className="h-9 rounded-xs border border-control-border bg-background px-2 text-sm"+ value={file.type}+ onChange={(event) => {+ const next = [...files];+ next[index] = {+ ...file,+ type: Number(event.target.value) as Revision_Type,+ };+ onFilesChange(next);+ }}+ >+ <option value={Revision_Type.VERSIONED}>+ {t("database.revision.type-versioned")}+ </option>+ <option value={Revision_Type.DECLARATIVE}>+ {t("database.revision.type-declarative")}+ </option>+ </select>+ </label>+ </div>+ {file.content && (+ <div>+ <span className="mb-1 block text-xs text-control-light">+ {t("database.revision.content-preview")}+ </span>+ <pre className="max-h-32 overflow-auto rounded-sm bg-control-bg p-2 text-xs text-control">+ {file.content.substring(0, 500)}+ {file.content.length > 500 ? "..." : ""}+ </pre>+ </div>+ )}+ </div>+ <Button+ variant="ghost"+ size="icon"+ onClick={() =>+ onFilesChange(files.filter((_, i) => i !== index))+ }+ >+ <X className="size-4" />+ </Button>+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ );+}++function EmptyState({ icon, text }: { icon?: React.ReactNode; text: string }) {+ return (+ <div className="flex flex-col items-center justify-center gap-y-3 py-8 text-control-light">+ {icon}+ <p>{text}</p>+ </div>+ );+}++function extractVersionFromFilename(filename: string): string {+ const patterns = [+ /[Vv]?(\d+\.\d+\.\d+)/,+ /[Vv]?(\d+\.\d+)/,+ /[Vv]?(\d+)[_](\d+)(?:[_](\d+))?/,+ /[Vv]?(\d{3,})/,+ /[Vv]?(\d+)/,+ ];+ for (const pattern of patterns) {+ const match = filename.match(pattern);+ if (!match) {+ continue;+ }+ const version = pattern.source.includes("_")+ ? [match[1], match[2], match[3]].filter(Boolean).join(".")+ : match[1];+ if (/^\d{3}$/.test(version)) {+ return version.split("").join(".");+ }+ return version;+ }+ return "";+}++function formatFileSize(bytes: number): string {+ if (bytes < 1024) {+ return `${bytes} B`;+ }+ const kb = bytes / 1024;+ if (kb < 1024) {+ return `${kb.toFixed(1)} KB`;+ }+ return `${(kb / 1024).toFixed(1)} MB`;+}++function mapReleaseTypeToRevisionType(+ releaseType: Release_Type+): Revision_Type {+ switch (releaseType) {+ case Release_Type.VERSIONED:+ return Revision_Type.VERSIONED;+ case Release_Type.DECLARATIVE:+ return Revision_Type.DECLARATIVE;+ case Release_Type.TYPE_UNSPECIFIED:+ return Revision_Type.TYPE_UNSPECIFIED;+ default:+ releaseType satisfies never;+ return Revision_Type.TYPE_UNSPECIFIED;+ }+}diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.test.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.test.tsxindex a7d0cdb63d..bd641317d5 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.test.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.test.tsx@@ -117,6 +117,15 @@ vi.mock("@/store/modules/v1/issueComment", () => ({useIssueCommentStore: () => mocks.issueCommentStore,}));+vi.mock("@/utils", () => ({+ displayRoleTitle: (role: { title?: string; name?: string }) =>+ role.title ?? role.name ?? "",+ ensureUserFullName: (user: { title?: string; name?: string }) =>+ user.title ?? user.name ?? "",+ isBindingPolicyExpired: () => false,+ memberMapToRolesInProjectIAM: () => new Map(),+}));+const renderIntoContainer = (element: ReactElement) => {const container = document.createElement("div");const root = createRoot(container);diff --git a/frontend/src/react/pages/settings/InstancesPage.tsx b/frontend/src/react/pages/settings/InstancesPage.tsxindex 7a3c95104e..0301ba126c 100644--- a/frontend/src/react/pages/settings/InstancesPage.tsx+++ b/frontend/src/react/pages/settings/InstancesPage.tsx@@ -20,6 +20,7 @@ import {type SearchParams,} from "@/react/components/AdvancedSearch";import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";+import { InstanceAssignmentSheet } from "@/react/components/InstanceAssignmentSheet";import { PermissionGuard } from "@/react/components/PermissionGuard";import {Alert,@@ -90,7 +91,9 @@ import {supportedEngineV1List,} from "@/utils";-// ============================================================+const ASSIGN_LICENSE_QUERY = "assignLicense";+const ASSIGN_LICENSE_INSTANCES_QUERY = "instances";+// Shared hooks// ============================================================@@ -576,12 +579,14 @@ function BatchOperationsBar({syncing,onSync,onEditEnvironment,+ onAssignLicense,showAssignLicense,}: {selectedInstances: Instance[];syncing: boolean;onSync: (enableFullSync: boolean) => void;onEditEnvironment: () => void;+ onAssignLicense: () => void;showAssignLicense?: boolean;}) {const { t } = useTranslation();@@ -609,7 +614,12 @@ function BatchOperationsBar({{t("database.edit-environment")}</Button>{showAssignLicense && (- <Button variant="ghost" size="md" disabled={!canUpdate}>+ <Button+ variant="ghost"+ size="md"+ disabled={!canUpdate}+ onClick={onAssignLicense}+ ><GraduationCap className="h-4 w-4 mr-1" />{t("subscription.instance-assignment.assign-license")}</Button>@@ -800,9 +810,16 @@ export function InstancesPage() {}if (searchParams.query) parts.push(searchParams.query);const queryString = parts.join(" ");- const currentQuery = router.currentRoute.value.query.q as string;- if (queryString !== (currentQuery ?? "")) {- router.replace({ query: queryString ? { q: queryString } : {} });+ const currentQuery = router.currentRoute.value.query;+ const currentQueryString = currentQuery.q as string;+ if (queryString !== (currentQueryString ?? "")) {+ const nextQuery = { ...currentQuery };+ if (queryString) {+ nextQuery.q = queryString;+ } else {+ delete nextQuery.q;+ }+ router.replace({ query: nextQuery });}}, [searchParams]);@@ -955,6 +972,8 @@ export function InstancesPage() {// Batch operations — all mutation logic lives here in the parentconst [syncing, setSyncing] = useState(false);const [showEditEnvDrawer, setShowEditEnvDrawer] = useState(false);+ const [showAssignLicenseSheet, setShowAssignLicenseSheet] = useState(false);+ const [assignLicenseNames, setAssignLicenseNames] = useState<string[]>([]);const handleSync = useCallback(async (enableFullSync: boolean) => {@@ -1011,6 +1030,34 @@ export function InstancesPage() {setSelectedNames(new Set());}, [fetchInstances]);+ const handleAssignLicense = useCallback((names: string[]) => {+ setAssignLicenseNames(names);+ setShowAssignLicenseSheet(true);+ }, []);++ useEffect(() => {+ const query = router.currentRoute.value.query;+ if (query[ASSIGN_LICENSE_QUERY] !== "1") {+ return;+ }++ const rawInstances = query[ASSIGN_LICENSE_INSTANCES_QUERY];+ const names =+ typeof rawInstances === "string"+ ? rawInstances.split(",").filter(Boolean)+ : Array.isArray(rawInstances)+ ? rawInstances.filter(+ (name): name is string => typeof name === "string"+ )+ : [];+ handleAssignLicense(names);++ const nextQuery = { ...query };+ delete nextQuery[ASSIGN_LICENSE_QUERY];+ delete nextQuery[ASSIGN_LICENSE_INSTANCES_QUERY];+ router.replace({ query: nextQuery });+ }, [handleAssignLicense]);+// Data source toggleconst [expandedDataSources, setExpandedDataSources] = useState<Set<string>>(new Set()@@ -1113,6 +1160,11 @@ export function InstancesPage() {syncing={syncing}onSync={handleSync}onEditEnvironment={() => setShowEditEnvDrawer(true)}+ onAssignLicense={() =>+ handleAssignLicense(+ selectedInstanceList.map((instance) => instance.name)+ )+ }showAssignLicense={subscriptionStore.currentPlan !== PlanType.FREE}/>@@ -1121,6 +1173,12 @@ export function InstancesPage() {onClose={() => setShowEditEnvDrawer(false)}onUpdate={handleEnvironmentUpdate}/>+ <InstanceAssignmentSheet+ open={showAssignLicenseSheet}+ selectedInstanceList={assignLicenseNames}+ onOpenChange={setShowAssignLicenseSheet}+ onUpdated={handleRowAction}+ />{/* Table */}<div className="border rounded-sm">diff --git a/frontend/src/react/pages/settings/SubscriptionPage.tsx b/frontend/src/react/pages/settings/SubscriptionPage.tsxindex 1e69d5fabb..1c059aa8d7 100644--- a/frontend/src/react/pages/settings/SubscriptionPage.tsx+++ b/frontend/src/react/pages/settings/SubscriptionPage.tsx@@ -1,6 +1,7 @@import { Copy, Pencil } from "lucide-react";import { type ChangeEvent, useState } from "react";import { useTranslation } from "react-i18next";+import { InstanceAssignmentSheet } from "@/react/components/InstanceAssignmentSheet";import { Badge } from "@/react/components/ui/badge";import { Button } from "@/react/components/ui/button";import { Input } from "@/react/components/ui/input";@@ -12,18 +13,19 @@ import {useActuatorV1Store,useSubscriptionV1Store,} from "@/store";+import { ENTERPRISE_INQUIRE_LINK } from "@/types";import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";import { hasWorkspacePermissionV2 } from "@/utils";import { PurchaseSection } from "./PurchaseSection";interface SubscriptionPageProps {- onRequireEnterprise: () => void;- onManageInstanceLicenses: () => void;+ onRequireEnterprise?: () => void;+ onManageInstanceLicenses?: () => void;}export function SubscriptionPage({- onRequireEnterprise,- onManageInstanceLicenses,+ onRequireEnterprise: onRequireEnterpriseProp,+ onManageInstanceLicenses: onManageInstanceLicensesProp,}: SubscriptionPageProps) {const { t } = useTranslation();const subscriptionStore = useSubscriptionV1Store();@@ -63,8 +65,16 @@ export function SubscriptionPage({const [license, setLicense] = useState("");const [loading, setLoading] = useState(false);const [copied, setCopied] = useState(false);+ const [showInstanceAssignmentSheet, setShowInstanceAssignmentSheet] =+ useState(false);const disabled = loading || !license;+ const onRequireEnterprise =+ onRequireEnterpriseProp ??+ (() => window.open(ENTERPRISE_INQUIRE_LINK, "_blank"));+ const onManageInstanceLicenses =+ onManageInstanceLicensesProp ??+ (() => setShowInstanceAssignmentSheet(true));let planType: "FREE" | "TEAM" | "ENTERPRISE" = "FREE";let planLabel = t("subscription.plan.free.title");@@ -297,6 +307,10 @@ export function SubscriptionPage({</div></div>)}+ <InstanceAssignmentSheet+ open={showInstanceAssignmentSheet}+ onOpenChange={setShowInstanceAssignmentSheet}+ /></div>);}diff --git a/frontend/src/react/router/index.ts b/frontend/src/react/router/index.tsindex 9f19f66f80..1b5c7a7366 100644--- a/frontend/src/react/router/index.ts+++ b/frontend/src/react/router/index.ts@@ -7,11 +7,33 @@ import {PROJECT_V1_ROUTE_DETAIL,} from "@/router/dashboard/projectV1";import {+ DATABASE_ROUTE_DASHBOARD,+ ENVIRONMENT_V1_ROUTE_DASHBOARD,+ INSTANCE_ROUTE_DASHBOARD,+ PROJECT_V1_ROUTE_DASHBOARD,+ WORKSPACE_ROUTE_AUDIT_LOG,+ WORKSPACE_ROUTE_CUSTOM_APPROVAL,+ WORKSPACE_ROUTE_DATA_CLASSIFICATION,+ WORKSPACE_ROUTE_GLOBAL_MASKING,+ WORKSPACE_ROUTE_GROUPS,+ WORKSPACE_ROUTE_IDENTITY_PROVIDERS,+ WORKSPACE_ROUTE_IM,WORKSPACE_ROUTE_LANDING,+ WORKSPACE_ROUTE_MCP,+ WORKSPACE_ROUTE_MEMBERS,WORKSPACE_ROUTE_MY_ISSUES,+ WORKSPACE_ROUTE_RISK_ASSESSMENT,+ WORKSPACE_ROUTE_ROLES,+ WORKSPACE_ROUTE_SEMANTIC_TYPES,+ WORKSPACE_ROUTE_SERVICE_ACCOUNTS,+ WORKSPACE_ROUTE_SQL_REVIEW,+ WORKSPACE_ROUTE_USER_PROFILE,+ WORKSPACE_ROUTE_USERS,+ WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,} from "@/router/dashboard/workspaceRoutes";import {SETTING_ROUTE_PROFILE,+ SETTING_ROUTE_WORKSPACE_GENERAL,SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,} from "@/router/dashboard/workspaceSetting";import {@@ -22,15 +44,37 @@ import {export {AUTH_SIGNIN_MODULE,+ DATABASE_ROUTE_DASHBOARD,+ ENVIRONMENT_V1_ROUTE_DASHBOARD,+ INSTANCE_ROUTE_DASHBOARD,+ PROJECT_V1_ROUTE_DASHBOARD,PROJECT_V1_ROUTE_DATABASE_DETAIL,PROJECT_V1_ROUTE_DETAIL,SETTING_ROUTE_PROFILE,+ SETTING_ROUTE_WORKSPACE_GENERAL,SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,SQL_EDITOR_DATABASE_MODULE,SQL_EDITOR_HOME_MODULE,SQL_EDITOR_PROJECT_MODULE,+ WORKSPACE_ROUTE_AUDIT_LOG,+ WORKSPACE_ROUTE_CUSTOM_APPROVAL,+ WORKSPACE_ROUTE_DATA_CLASSIFICATION,+ WORKSPACE_ROUTE_GLOBAL_MASKING,+ WORKSPACE_ROUTE_GROUPS,+ WORKSPACE_ROUTE_IDENTITY_PROVIDERS,+ WORKSPACE_ROUTE_IM,WORKSPACE_ROUTE_LANDING,+ WORKSPACE_ROUTE_MCP,+ WORKSPACE_ROUTE_MEMBERS,WORKSPACE_ROUTE_MY_ISSUES,+ WORKSPACE_ROUTE_RISK_ASSESSMENT,+ WORKSPACE_ROUTE_ROLES,+ WORKSPACE_ROUTE_SEMANTIC_TYPES,+ WORKSPACE_ROUTE_SERVICE_ACCOUNTS,+ WORKSPACE_ROUTE_SQL_REVIEW,+ WORKSPACE_ROUTE_USER_PROFILE,+ WORKSPACE_ROUTE_USERS,+ WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,};export type ReactRoute = {diff --git a/frontend/src/react/shell-bridge.ts b/frontend/src/react/shell-bridge.tsnew file mode 100644index 0000000000..e339006c67--- /dev/null+++ b/frontend/src/react/shell-bridge.ts@@ -0,0 +1,34 @@+import type { NotificationCreate } from "@/types/notification";++export const ReactShellBridgeEvent = {+ localeChange: "bb.react-locale-change",+ notification: "bb.react-notification",+ quickstartReset: "bb.react-quickstart-reset",+} as const;++export type ReactShellBridgeEventName =+ (typeof ReactShellBridgeEvent)[keyof typeof ReactShellBridgeEvent];++export type ReactQuickstartResetDetail = {+ keys: string[];+};++export function emitReactLocaleChange(lang: string) {+ window.dispatchEvent(+ new CustomEvent(ReactShellBridgeEvent.localeChange, { detail: lang })+ );+}++export function emitReactNotification(notification: NotificationCreate) {+ window.dispatchEvent(+ new CustomEvent(ReactShellBridgeEvent.notification, {+ detail: notification,+ })+ );+}++export function emitReactQuickstartReset(detail: ReactQuickstartResetDetail) {+ window.dispatchEvent(+ new CustomEvent(ReactShellBridgeEvent.quickstartReset, { detail })+ );+}diff --git a/frontend/src/react/stores/app/index.test.ts b/frontend/src/react/stores/app/index.test.tsindex 9bace8890e..294d0937eb 100644--- a/frontend/src/react/stores/app/index.test.ts+++ b/frontend/src/react/stores/app/index.test.ts@@ -1,5 +1,6 @@import { create as createProto } from "@bufbuild/protobuf";import { beforeEach, describe, expect, test, vi } from "vitest";+import { ReactShellBridgeEvent } from "@/react/shell-bridge";import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";import { State } from "@/types/proto-es/v1/common_pb";import {@@ -235,10 +236,22 @@ describe("useAppStore", () => {);});+ test("uses pipeline app feature defaults before profile overrides", () => {+ const store = createAppStore();++ expect(+ store.getState().appFeatures["bb.feature.database-change-mode"]+ ).toBe(DatabaseChangeMode.PIPELINE);+ expect(store.getState().appFeatures["bb.feature.hide-quick-start"]).toBe(+ false+ );+ expect(store.getState().appFeatures["bb.feature.hide-trial"]).toBe(false);+ });+test("dispatches notification events for the Vue shell bridge", () => {const store = createAppStore();const listener = vi.fn();- window.addEventListener("bb.react-notification", listener);+ window.addEventListener(ReactShellBridgeEvent.notification, listener);store.getState().notify({module: "bytebase",@@ -248,14 +261,14 @@ describe("useAppStore", () => {expect(store.getState().notifications).toHaveLength(1);expect(listener).toHaveBeenCalledTimes(1);- window.removeEventListener("bb.react-notification", listener);+ window.removeEventListener(ReactShellBridgeEvent.notification, listener);});test("keeps user-scoped preferences in localStorage", () => {const store = createAppStore();const listener = vi.fn();store.setState({ currentUser: user });- window.addEventListener("bb.react-quickstart-reset", listener);+ window.addEventListener(ReactShellBridgeEvent.quickstartReset, listener);store.getState().setRecentProject(projectA.name);store.getState().setRecentProject(projectB.name);@@ -283,6 +296,6 @@ describe("useAppStore", () => {}),}));- window.removeEventListener("bb.react-quickstart-reset", listener);+ window.removeEventListener(ReactShellBridgeEvent.quickstartReset, listener);});});diff --git a/frontend/src/react/stores/app/notification.ts b/frontend/src/react/stores/app/notification.tsindex 96e35bea15..049fae2bd1 100644--- a/frontend/src/react/stores/app/notification.ts+++ b/frontend/src/react/stores/app/notification.ts@@ -1,3 +1,4 @@+import { emitReactNotification } from "@/react/shell-bridge";import type { AppSliceCreator, NotificationSlice } from "./types";export const createNotificationSlice: AppSliceCreator<NotificationSlice> = (@@ -9,8 +10,6 @@ export const createNotificationSlice: AppSliceCreator<NotificationSlice> = (set((state) => ({notifications: [...state.notifications, notification],}));- window.dispatchEvent(- new CustomEvent("bb.react-notification", { detail: notification })- );+ emitReactNotification(notification);},});diff --git a/frontend/src/react/stores/app/preferences.ts b/frontend/src/react/stores/app/preferences.tsindex 2b75627e76..791b7d8e97 100644--- a/frontend/src/react/stores/app/preferences.ts+++ b/frontend/src/react/stores/app/preferences.ts@@ -1,3 +1,4 @@+import { emitReactQuickstartReset } from "@/react/shell-bridge";import {storageKeyIntroState,storageKeyRecentProjects,@@ -64,10 +65,6 @@ export const createPreferencesSlice: AppSliceCreator<PreferencesSlice> = (...Object.fromEntries(QUICKSTART_RESET_KEYS.map((key) => [key, false])),};writeJson(key, next);- window.dispatchEvent(- new CustomEvent("bb.react-quickstart-reset", {- detail: { keys: QUICKSTART_RESET_KEYS },- })- );+ emitReactQuickstartReset({ keys: QUICKSTART_RESET_KEYS });},});diff --git a/frontend/src/router/dashboard/instance.ts b/frontend/src/router/dashboard/instance.tsindex ca3f97d29f..363b0da54e 100644--- a/frontend/src/router/dashboard/instance.ts+++ b/frontend/src/router/dashboard/instance.ts@@ -1,12 +1,64 @@import type { RouteLocationNormalized, RouteRecordRaw } from "vue-router";+import DummyRootView from "@/DummyRootView";import InstanceLayout from "@/layouts/InstanceLayout.vue";import { t } from "@/plugins/i18n";+import {+ databaseNamePrefix,+ instanceNamePrefix,+ pushNotification,+ useDatabaseV1Store,+} from "@/store";+import { isValidProjectName } from "@/types";+import { extractProjectResourceName } from "@/utils/v1";+import { PROJECT_V1_ROUTE_DATABASE_DETAIL } from "./projectV1";import { INSTANCE_ROUTE_DASHBOARD } from "./workspaceRoutes";export const INSTANCE_ROUTE_CREATE = `${INSTANCE_ROUTE_DASHBOARD}.create`;export const INSTANCE_ROUTE_DETAIL = `${INSTANCE_ROUTE_DASHBOARD}.detail`;export const INSTANCE_ROUTE_DATABASE_DETAIL = `${INSTANCE_ROUTE_DASHBOARD}.database.detail`;+const redirectToProjectDatabaseDetail = async (+ route: RouteLocationNormalized+) => {+ const instanceId = route.params.instanceId as string;+ const databaseName = route.params.databaseName as string;+ try {+ const database = await useDatabaseV1Store().getOrFetchDatabaseByName(+ `${instanceNamePrefix}${instanceId}/${databaseNamePrefix}${databaseName}`+ );+ if (database && isValidProjectName(database.project)) {+ return {+ name: PROJECT_V1_ROUTE_DATABASE_DETAIL,+ params: {+ projectId: extractProjectResourceName(database.project),+ instanceId,+ databaseName,+ },+ };+ }+ pushNotification({+ module: "bytebase",+ style: "WARN",+ title: "Database not found",+ description: `Database: ${databaseName}`,+ });+ } catch (error) {+ console.error("Failed to fetch database:", error);+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: "Error",+ description: `Failed to load database: ${databaseName}`,+ });+ }+ return {+ name: INSTANCE_ROUTE_DETAIL,+ params: {+ instanceId,+ },+ };+};+const instanceRoutes: RouteRecordRaw[] = [{path: "instances/new",@@ -53,8 +105,8 @@ const instanceRoutes: RouteRecordRaw[] = [meta: {requiredPermissionList: () => ["bb.projects.get", "bb.databases.get"],},- component: () => import("@/components/InstanceDatabaseRedirect.vue"),- props: true,+ component: DummyRootView,+ beforeEnter: redirectToProjectDatabaseDetail,},],},diff --git a/frontend/src/router/dashboard/workspaceSetting.ts b/frontend/src/router/dashboard/workspaceSetting.tsindex 86431251bc..ae355edbd5 100644--- a/frontend/src/router/dashboard/workspaceSetting.ts+++ b/frontend/src/router/dashboard/workspaceSetting.ts@@ -56,7 +56,8 @@ const workspaceSettingRoutes: RouteRecordRaw[] = [title: () => t("settings.sidebar.subscription"),requiredPermissionList: () => ["bb.settings.get"],},- component: () => import("@/react/SubscriptionPageMount.vue"),+ component: () => import("@/react/ReactPageMount.vue"),+ props: () => ({ page: "SubscriptionPage" }),},],},diff --git a/frontend/src/shell-bridge.test.ts b/frontend/src/shell-bridge.test.tsnew file mode 100644index 0000000000..eeb9ccc30f--- /dev/null+++ b/frontend/src/shell-bridge.test.ts@@ -0,0 +1,227 @@+import { mount } from "@vue/test-utils";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { nextTick } from "vue";+import {+ emitReactLocaleChange,+ emitReactNotification,+ emitReactQuickstartReset,+} from "@/react/shell-bridge";++const mocks = vi.hoisted(() => ({+ locale: { value: "en-US" },+ route: {+ meta: {+ title: () => "Workspace",+ },+ query: {},+ },+ previousRoute: {+ query: {},+ },+ replace: vi.fn(),+ setDocumentTitle: vi.fn(),+ overrideAppProfile: vi.fn(),+ pushNotification: vi.fn(),+ tryPopNotification: vi.fn(),+ notificationCreate: vi.fn(),+ introState: {} as Record<string, boolean>,+ saveIntroStateByKey: vi.fn(+ async ({ key, newState }: { key: string; newState: boolean }) => {+ mocks.introState[key] = newState;+ return newState;+ }+ ),+}));++vi.mock("naive-ui", async () => {+ const { defineComponent, h } = await import("vue");+ const passthrough = (name: string) =>+ defineComponent({+ name,+ setup(_, { slots }) {+ return () => h("div", slots.default?.());+ },+ });+ return {+ NConfigProvider: passthrough("NConfigProvider"),+ NDialogProvider: passthrough("NDialogProvider"),+ NNotificationProvider: passthrough("NNotificationProvider"),+ useNotification: () => ({+ create: mocks.notificationCreate,+ }),+ };+});++vi.mock("../naive-ui.config", () => ({+ dateLang: {},+ generalLang: {},+ themeOverrides: {},+}));++vi.mock("@/components/misc/Watermark.vue", async () => {+ const { defineComponent, h } = await import("vue");+ return {+ default: defineComponent({+ name: "MockWatermark",+ setup() {+ return () => h("div");+ },+ }),+ };+});++vi.mock("./AuthContext.vue", async () => {+ const { defineComponent, h } = await import("vue");+ return {+ default: defineComponent({+ name: "MockAuthContext",+ setup(_, { slots }) {+ return () => h("div", slots.default?.());+ },+ }),+ };+});++vi.mock("./components/misc/OverlayStackManager.vue", async () => {+ const { defineComponent, h } = await import("vue");+ return {+ default: defineComponent({+ name: "MockOverlayStackManager",+ setup(_, { slots }) {+ return () => h("div", slots.default?.());+ },+ }),+ };+});++vi.mock("./customAppProfile", () => ({+ overrideAppProfile: mocks.overrideAppProfile,+}));++vi.mock("./plugins/i18n", () => ({+ locale: mocks.locale,+ t: (key: string) => key,+}));++vi.mock("./store", () => ({+ useNotificationStore: () => ({+ pushNotification: mocks.pushNotification,+ tryPopNotification: mocks.tryPopNotification,+ }),+ useUIStateStore: () => ({+ introState: mocks.introState,+ saveIntroStateByKey: mocks.saveIntroStateByKey,+ }),+}));++vi.mock("./utils", () => ({+ isDev: () => false,+ setDocumentTitle: mocks.setDocumentTitle,+}));++vi.mock("vue-router", async () => {+ const actual =+ await vi.importActual<typeof import("vue-router")>("vue-router");+ const { reactive } = await import("vue");+ const route = reactive(mocks.route);+ return {+ ...actual,+ useRoute: () => route,+ useRouter: () => ({+ replace: mocks.replace,+ }),+ };+});++import App from "./App.vue";+import NotificationContext from "./NotificationContext.vue";++beforeEach(() => {+ vi.clearAllMocks();+ mocks.locale.value = "en-US";+ mocks.route.meta.title = () => "Workspace";+ mocks.route.query = {};+ mocks.previousRoute.query = {};+ mocks.introState = {};+});++afterEach(() => {+ document.body.innerHTML = "";+});++describe("React shell bridge", () => {+ test("updates Vue locale and document title from locale events", async () => {+ const wrapper = mount(App, {+ attachTo: document.body,+ global: {+ stubs: {+ RouterView: { template: "<div />" },+ },+ },+ });+ await nextTick();++ emitReactLocaleChange("ja-JP");++ expect(mocks.locale.value).toBe("ja-JP");+ expect(mocks.setDocumentTitle).toHaveBeenCalledWith("Workspace");++ wrapper.unmount();+ });++ test("updates quickstart intro state from reset events", async () => {+ const wrapper = mount(App, {+ attachTo: document.body,+ global: {+ stubs: {+ RouterView: { template: "<div />" },+ },+ },+ });+ await nextTick();++ emitReactQuickstartReset({ keys: ["hidden", "data.query"] });+ await nextTick();++ expect(mocks.introState).toMatchObject({+ hidden: false,+ "data.query": false,+ });+ expect(mocks.saveIntroStateByKey).toHaveBeenCalledTimes(2);++ wrapper.unmount();+ });++ test("shows bytebase notifications and ignores other modules", async () => {+ const wrapper = mount(NotificationContext, {+ attachTo: document.body,+ slots: {+ default: "<div />",+ },+ });+ await nextTick();++ emitReactNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: "Saved",+ });++ expect(mocks.notificationCreate).toHaveBeenCalledWith(+ expect.objectContaining({+ type: "success",+ })+ );++ mocks.notificationCreate.mockClear();+ emitReactNotification({+ module: "other",+ style: "SUCCESS",+ title: "Ignored",+ });++ expect(mocks.notificationCreate).not.toHaveBeenCalled();++ wrapper.unmount();+ });+});diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.tsindex 41614068ba..3f1eb05a57 100644--- a/frontend/vitest.config.ts+++ b/frontend/vitest.config.ts@@ -10,6 +10,7 @@ export default mergeConfig(environment: "jsdom",exclude: [...configDefaults.exclude, "e2e/*", "tests/e2e/**"],root: fileURLToPath(new URL("./", import.meta.url)),+ setupFiles: ["./vitest.setup.ts"],},}));diff --git a/frontend/vitest.setup.ts b/frontend/vitest.setup.tsnew file mode 100644index 0000000000..f4f37f543c--- /dev/null+++ b/frontend/vitest.setup.ts@@ -0,0 +1,19 @@+import { vi } from "vitest";++vi.mock("pouchdb", () => {+ class MockPouchDB {+ static plugin = vi.fn();++ get = vi.fn(async () => undefined);+ put = vi.fn(async () => undefined);+ remove = vi.fn(async () => undefined);+ }++ return {+ default: MockPouchDB,+ };+});++vi.mock("pouchdb-find", () => ({+ default: {},+}));