Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(react): plan & issue detail bugfixes (#20201)
boojack73cb14cb61b8
diff --git a/docs/plans/2026-05-06-react-plan-issue-detail-bugfixes.md b/docs/plans/2026-05-06-react-plan-issue-detail-bugfixes.mdnew file mode 100644index 0000000000..91ea4baccbBinary files /dev/null and b/docs/plans/2026-05-06-react-plan-issue-detail-bugfixes.md differdiff --git a/frontend/src/react/components/PermissionGuard.test.tsx b/frontend/src/react/components/PermissionGuard.test.tsxnew file mode 100644index 0000000000..62cbfb1c40--- /dev/null+++ b/frontend/src/react/components/PermissionGuard.test.tsx@@ -0,0 +1,128 @@+import type { ReactNode } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import type { Permission } from "@/types";+import type { Project } from "@/types/proto-es/v1/project_service_pb";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ workspacePermissions: new Set<Permission>(),+ projectPermissions: new Set<Permission>(),+ loadWorkspacePermissionState: vi.fn(async () => {}),+ loadProjectIamPolicy: vi.fn(async (_project: string) => undefined),+}));++vi.mock("monaco-editor", () => ({}));++vi.mock(+ "@codingame/monaco-vscode-editor-api/vscode/src/vs/editor/standalone/browser/standalone-tokens.css",+ () => ({})+);++vi.mock("@/react/stores/app", () => ({+ useAppStore: (+ selector: (state: {+ currentUser: { name: string };+ roles: unknown[];+ workspacePolicy: undefined;+ projectPoliciesByName: Record<string, unknown>;+ hasWorkspacePermission: (permission: Permission) => boolean;+ hasProjectPermission: (+ _project: Project,+ permission: Permission+ ) => boolean;+ loadWorkspacePermissionState: () => Promise<void>;+ loadProjectIamPolicy: (project: string) => Promise<undefined>;+ }) => unknown+ ) =>+ selector({+ currentUser: { name: "users/[email protected]" },+ roles: [],+ workspacePolicy: undefined,+ projectPoliciesByName: {},+ hasWorkspacePermission: (permission) =>+ mocks.workspacePermissions.has(permission),+ hasProjectPermission: (_project, permission) =>+ mocks.workspacePermissions.has(permission) ||+ mocks.projectPermissions.has(permission),+ loadWorkspacePermissionState: mocks.loadWorkspacePermissionState,+ loadProjectIamPolicy: mocks.loadProjectIamPolicy,+ }),+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("@/react/components/ui/tooltip", () => ({+ Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,+ BlockTooltip: ({ children }: { children: ReactNode }) => <>{children}</>,+}));++import { PermissionGuard } from "./PermissionGuard";++let container: HTMLDivElement;+let root: ReturnType<typeof createRoot>;++beforeEach(() => {+ mocks.workspacePermissions = new Set();+ mocks.projectPermissions = new Set();+ mocks.loadWorkspacePermissionState.mockReset();+ mocks.loadWorkspacePermissionState.mockResolvedValue(undefined);+ mocks.loadProjectIamPolicy.mockReset();+ mocks.loadProjectIamPolicy.mockResolvedValue(undefined);+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => {+ root.unmount();+ });+ document.body.removeChild(container);+});++describe("PermissionGuard", () => {+ test("loads workspace permission state before enabling children", async () => {+ mocks.workspacePermissions.add("bb.instances.create");++ await act(async () => {+ root.render(+ <PermissionGuard permissions={["bb.instances.create"]}>+ {({ disabled }) => <button disabled={disabled}>create</button>}+ </PermissionGuard>+ );+ });+ await act(async () => {+ await Promise.resolve();+ });++ expect(mocks.loadWorkspacePermissionState).toHaveBeenCalledTimes(1);+ expect(container.querySelector("button")?.disabled).toBe(false);+ });++ test("loads project IAM policy for project permission checks", async () => {+ const project = { name: "projects/demo" } as Project;+ mocks.projectPermissions.add("bb.sql.select");++ await act(async () => {+ root.render(+ <PermissionGuard permissions={["bb.sql.select"]} project={project}>+ {({ disabled }) => <button disabled={disabled}>connect</button>}+ </PermissionGuard>+ );+ });+ await act(async () => {+ await Promise.resolve();+ });++ expect(mocks.loadWorkspacePermissionState).toHaveBeenCalledTimes(1);+ expect(mocks.loadProjectIamPolicy).toHaveBeenCalledWith(project.name);+ expect(container.querySelector("button")?.disabled).toBe(false);+ });+});diff --git a/frontend/src/react/components/PermissionGuard.tsx b/frontend/src/react/components/PermissionGuard.tsxindex e1f52cff6a..7856f748c4 100644--- a/frontend/src/react/components/PermissionGuard.tsx+++ b/frontend/src/react/components/PermissionGuard.tsx@@ -1,8 +1,11 @@import type { ReactNode } from "react";import { useTranslation } from "react-i18next";+import {+ useComponentPermissionState,+ usePermissionDataReady,+} from "@/react/components/ComponentPermissionGuard";import type { Permission } from "@/types";import type { Project } from "@/types/proto-es/v1/project_service_pb";-import { hasProjectPermissionV2, hasWorkspacePermissionV2 } from "@/utils";import { BlockTooltip, Tooltip } from "./ui/tooltip";/**@@ -14,9 +17,12 @@ export function usePermissionCheck(project?: Project): [boolean, string | undefined] {const { t } = useTranslation();- const missed = project- ? permissions.filter((p) => !hasProjectPermissionV2(project, p))- : permissions.filter((p) => !hasWorkspacePermissionV2(p));+ const ready = usePermissionDataReady(project);+ const { missedPermissions } = useComponentPermissionState({+ permissions,+ project,+ });+ const missed = ready ? missedPermissions : permissions;if (missed.length === 0) return [true, undefined];return [false,@@ -73,26 +79,30 @@ export function PermissionGuard({display = "inline",}: PermissionGuardProps) {const { t } = useTranslation();- const missed = project- ? permissions.filter((p) => !hasProjectPermissionV2(project, p))- : permissions.filter((p) => !hasWorkspacePermissionV2(p));+ const ready = usePermissionDataReady(project);+ const { missedPermissions } = useComponentPermissionState({+ permissions,+ project,+ });+ const missed = ready ? missedPermissions : permissions;const disabled = missed.length > 0;- const tooltip = disabled ? (- <div className="flex flex-col gap-1">- {project- ? t("common.missing-required-permission-for-resource", {- resource: project.name,- })- : t("common.missing-required-permission", { permissions: "" })}- <ul className="list-disc pl-4">- {missed.map((p) => (- <li key={p}>{p}</li>- ))}- </ul>- </div>- ) : undefined;+ const tooltip =+ ready && disabled ? (+ <div className="flex flex-col gap-1">+ {project+ ? t("common.missing-required-permission-for-resource", {+ resource: project.name,+ })+ : t("common.missing-required-permission", { permissions: "" })}+ <ul className="list-disc pl-4">+ {missed.map((p) => (+ <li key={p}>{p}</li>+ ))}+ </ul>+ </div>+ ) : undefined;const content =typeof children === "function" ? children({ disabled }) : children;diff --git a/frontend/src/react/components/monaco/MonacoEditor.tsx b/frontend/src/react/components/monaco/MonacoEditor.tsxindex 54cd549d68..163965345d 100644--- a/frontend/src/react/components/monaco/MonacoEditor.tsx+++ b/frontend/src/react/components/monaco/MonacoEditor.tsx@@ -58,6 +58,19 @@ import {trySetContentWithUndo,} from "./utils";+const supportedLanguages = new Set<Language>([+ "sql",+ "javascript",+ "redis",+ "json",+]);++const normalizeContent = (value: unknown): string =>+ typeof value === "string" ? value : "";++const normalizeLanguage = (value: unknown): Language =>+ supportedLanguages.has(value as Language) ? (value as Language) : "sql";+export interface MonacoEditorProps {advices?: AdviceOption[];autoCompleteContext?: AutoCompleteContext;@@ -120,12 +133,14 @@ export function MonacoEditor({formatContentOptions,}: MonacoEditorProps) {const { t } = useTranslation();+ const safeContent = normalizeContent(content);+ const safeLanguage = normalizeLanguage(language);const containerRef = useRef<HTMLDivElement>(null);const editorRef = useRef<IStandaloneCodeEditor | null>(null);const modelRef = useRef<ITextModel | null>(null);const activeDecorationRef = useRef<{ clear(): void } | null>(null);- const contentRef = useRef(content);- const languageRef = useRef(language);+ const contentRef = useRef(safeContent);+ const languageRef = useRef(safeLanguage);const readOnlyRef = useRef(readOnly);const optionsRef = useRef(options);const onChangeRef = useRef(onChange);@@ -144,10 +159,11 @@ export function MonacoEditor({typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"? crypto.randomUUID(): Math.random().toString(36).slice(2);- return `${id}.${extensionNameOfLanguage(language)}`;- }, [filename, language]);+ return `${id}.${extensionNameOfLanguage(safeLanguage)}`;+ }, [filename, safeLanguage]);const [contentHeight, setContentHeight] = useState(min);const [ready, setReady] = useState(false);+ const [initFailed, setInitFailed] = useState(false);useEffect(() => {configureMonacoMessages({@@ -157,8 +173,8 @@ export function MonacoEditor({});}, [t]);- contentRef.current = content;- languageRef.current = language;+ contentRef.current = safeContent;+ languageRef.current = safeLanguage;readOnlyRef.current = readOnly;optionsRef.current = options;onChangeRef.current = onChange;@@ -239,121 +255,129 @@ export function MonacoEditor({const host = document.createElement("div");host.className = "h-full w-full";containerRef.current?.replaceChildren(host);+ setInitFailed(false);(async () => {- if (!containerRef.current || editorRef.current) return;+ try {+ if (!containerRef.current || editorRef.current) return;- if (shouldEnableLSP) {- void initializeLSPClient().catch(() => undefined);- }+ if (shouldEnableLSP) {+ void initializeLSPClient().catch(() => undefined);+ }- const editor = await createMonacoEditor({- container: host,- options: {- ...optionsRef.current,- language: languageRef.current,- value: contentRef.current,- readOnly: readOnlyRef.current,- domReadOnly: readOnlyRef.current,- },- });+ const editor = await createMonacoEditor({+ container: host,+ options: {+ ...optionsRef.current,+ model: null,+ readOnly: readOnlyRef.current,+ domReadOnly: readOnlyRef.current,+ },+ });- if (disposed) {- editor.dispose();- return;- }+ if (disposed) {+ editor.dispose();+ return;+ }- editorRef.current = editor;- const monaco = await loadMonacoEditor();- // Re-apply the editor's intended theme after construction.- // Monaco's theme is global — when a previous editor was- // constructed with a different theme (e.g. CompactSQLEditor's- // `vs-dark` for admin mode), that theme persists across editor- // disposal. If the new editor's requested theme isn't- // registered (the custom `bb` theme is silently swallowed by- // the vscode-api theme service override in some runtime modes- // — see `initializeTheme` in core.ts), `setTheme` becomes a- // no-op and the dark theme stays stuck.- // `getResolvedTheme` returns the requested theme if it's known- // to be registered, otherwise falls back to the always-available- // built-in `vs`.- monaco.editor.setTheme(getResolvedTheme(optionsRef.current?.theme));- const model = await getOrCreateTextModel(- generatedFilename,- contentRef.current,- languageRef.current- );- if (disposed) {- editor.dispose();- return;- }- modelRef.current = model;- editor.setModel(model);- restoreViewState(editor, model);- await setMonacoModelLanguage(model, languageRef.current);-- contentSizeSubscription = editor.onDidContentSizeChange((event) => {- if (!event.contentHeightChanged) return;- setContentHeight(event.contentHeight);- });-- contentSubscription = editor.onDidChangeModelContent(() => {- if (isApplyingExternalChangeRef.current) {+ editorRef.current = editor;+ const monaco = await loadMonacoEditor();+ // Re-apply the editor's intended theme after construction.+ // Monaco's theme is global — when a previous editor was+ // constructed with a different theme (e.g. CompactSQLEditor's+ // `vs-dark` for admin mode), that theme persists across editor+ // disposal. If the new editor's requested theme isn't+ // registered (the custom `bb` theme is silently swallowed by+ // the vscode-api theme service override in some runtime modes+ // — see `initializeTheme` in core.ts), `setTheme` becomes a+ // no-op and the dark theme stays stuck.+ // `getResolvedTheme` returns the requested theme if it's known+ // to be registered, otherwise falls back to the always-available+ // built-in `vs`.+ monaco.editor.setTheme(getResolvedTheme(optionsRef.current?.theme));+ const model = await getOrCreateTextModel(+ generatedFilename,+ contentRef.current,+ languageRef.current+ );+ if (disposed) {+ editor.dispose();return;}- onChangeRef.current?.(editor.getValue());- emitSelectionSideEffects();- });+ modelRef.current = model;+ editor.setModel(model);+ restoreViewState(editor, model);+ await setMonacoModelLanguage(model, languageRef.current);++ contentSizeSubscription = editor.onDidContentSizeChange((event) => {+ if (!event.contentHeightChanged) return;+ setContentHeight(event.contentHeight);+ });- selectionSubscription = editor.onDidChangeCursorSelection(() => {- emitSelectionSideEffects();- });- modelSubscription = editor.onDidChangeModel(() => {- modelRef.current = editor.getModel();- emitSelectionSideEffects();- });- cursorSubscription = editor.onDidChangeCursorPosition(() => {- emitSelectionSideEffects();- });+ contentSubscription = editor.onDidChangeModelContent(() => {+ if (isApplyingExternalChangeRef.current) {+ return;+ }+ onChangeRef.current?.(editor.getValue());+ emitSelectionSideEffects();+ });- if (editor.getValue() !== contentRef.current) {- isApplyingExternalChangeRef.current = true;- editor.setValue(contentRef.current);- isApplyingExternalChangeRef.current = false;- }+ selectionSubscription = editor.onDidChangeCursorSelection(() => {+ emitSelectionSideEffects();+ });+ modelSubscription = editor.onDidChangeModel(() => {+ modelRef.current = editor.getModel();+ emitSelectionSideEffects();+ });+ cursorSubscription = editor.onDidChangeCursorPosition(() => {+ emitSelectionSideEffects();+ });- setContentHeight(editor.getContentHeight());- setReady(true);- onReadyRef.current?.(monaco, editor);- emitSelectionSideEffects();-- if (!readOnlyRef.current) {- formatAction = attachFormatAction(- monaco,- editor,- () => dialect,- () => formatContentOptions ?? { disabled: false },- t("sql-editor.format-sql")- );- suggestStyle = ensureSuggestOverrideStyle();- }+ if (editor.getValue() !== contentRef.current) {+ isApplyingExternalChangeRef.current = true;+ editor.setValue(contentRef.current);+ isApplyingExternalChangeRef.current = false;+ }- if (shouldEnableLSP) {- const wsPromise =- getConnectionWebSocket() ??- initializeLSPClient().then(() => getConnectionWebSocket());- wsPromise?.then((ws) => {- if (!ws || disposed) return;- messageHandler = (message: MessageEvent) => {- processStatementRangeMessage(message, activeRangeByUriRef);- emitSelectionSideEffects();- };- ws.addEventListener("message", messageHandler);- });- }+ setContentHeight(editor.getContentHeight());+ setReady(true);+ onReadyRef.current?.(monaco, editor);+ emitSelectionSideEffects();- if (autoFocus) {- editor.focus();+ if (!readOnlyRef.current) {+ formatAction = attachFormatAction(+ monaco,+ editor,+ () => dialect,+ () => formatContentOptions ?? { disabled: false },+ t("sql-editor.format-sql")+ );+ suggestStyle = ensureSuggestOverrideStyle();+ }++ if (shouldEnableLSP) {+ const wsPromise =+ getConnectionWebSocket() ??+ initializeLSPClient().then(() => getConnectionWebSocket());+ wsPromise?.then((ws) => {+ if (!ws || disposed) return;+ messageHandler = (message: MessageEvent) => {+ processStatementRangeMessage(message, activeRangeByUriRef);+ emitSelectionSideEffects();+ };+ ws.addEventListener("message", messageHandler);+ });+ }++ if (autoFocus) {+ editor.focus();+ }+ } catch (error) {+ if (disposed) {+ return;+ }+ console.error("Failed to initialize Monaco editor:", error);+ setInitFailed(true);}})();@@ -421,14 +445,14 @@ export function MonacoEditor({isApplyingExternalChangeRef.current = false;}setContentHeight(editor.getContentHeight());- }, [content]);+ }, [safeContent]);useEffect(() => {const model = modelRef.current ?? editorRef.current?.getModel();if (!model) return;void setMonacoModelLanguage(model, languageRef.current);- }, [generatedFilename, language]);+ }, [generatedFilename, safeLanguage]);useEffect(() => {const editor = editorRef.current;@@ -533,8 +557,28 @@ export function MonacoEditor({const height = clampMeasuredHeight(contentHeight);+ if (initFailed) {+ return (+ <div className={cn("relative", autoHeight ? "" : "h-full", className)}>+ <pre+ className={cn(+ "m-0 w-full overflow-auto whitespace-pre-wrap break-words font-mono text-sm",+ autoHeight ? "" : "h-full"+ )}+ style={autoHeight ? { height } : undefined}+ >+ {safeContent}+ </pre>+ </div>+ );+ }+return (- <div className={cn("relative", autoHeight ? "" : "h-full", className)}>+ <div+ data-testid="monaco-editor"+ data-ready={ready ? "true" : "false"}+ className={cn("relative", autoHeight ? "" : "h-full", className)}+ ><divref={containerRef}className={cn(diff --git a/frontend/src/react/components/revision/RevisionDetailPanel.tsx b/frontend/src/react/components/revision/RevisionDetailPanel.tsxindex 7df39f5bb6..b106db1a5c 100644--- a/frontend/src/react/components/revision/RevisionDetailPanel.tsx+++ b/frontend/src/react/components/revision/RevisionDetailPanel.tsx@@ -214,10 +214,12 @@ export function RevisionDetailPanel({) : null}<CopyButton content={statement} /></p>- <ReadonlyMonaco- content={statement}- className="relative h-auto max-h-[600px] min-h-[120px]"- />+ <div className="overflow-hidden rounded-sm border border-control-border bg-white">+ <ReadonlyMonaco+ content={statement}+ className="relative h-auto max-h-[600px] min-h-[120px]"+ />+ </div></div></div></main>diff --git a/frontend/src/react/pages/project/DatabaseChangelogDetailPage.tsx b/frontend/src/react/pages/project/DatabaseChangelogDetailPage.tsxindex 14e70033fc..dd01249493 100644--- a/frontend/src/react/pages/project/DatabaseChangelogDetailPage.tsx+++ b/frontend/src/react/pages/project/DatabaseChangelogDetailPage.tsx@@ -485,16 +485,20 @@ export function DatabaseChangelogDetailPage({</div>{showDiff ? (- <ReadonlyDiffMonaco- original={previousChangelog?.schema ?? ""}- modified={resolvedChangelog.schema}- className="relative h-auto max-h-[600px] min-h-[120px]"- />+ <div className="overflow-hidden rounded-sm border border-control-border bg-white">+ <ReadonlyDiffMonaco+ original={previousChangelog?.schema ?? ""}+ modified={resolvedChangelog.schema}+ className="relative h-auto max-h-[600px] min-h-[120px]"+ />+ </div>) : resolvedChangelog.schema ? (- <ReadonlyMonaco- content={resolvedChangelog.schema}- className="relative h-auto max-h-[600px] min-h-[120px]"- />+ <div className="overflow-hidden rounded-sm border border-control-border bg-white">+ <ReadonlyMonaco+ content={resolvedChangelog.schema}+ className="relative h-auto max-h-[600px] min-h-[120px]"+ />+ </div>) : (<div className="text-sm text-control-light">{t("changelog.current-schema-empty")}diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailChecks.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailChecks.tsxindex 51a6d9a244..ecc7a0591c 100644--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailChecks.tsx+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailChecks.tsx@@ -88,12 +88,13 @@ export function IssueDetailChecks() {}, [currentUser.email, page.plan, project]);const refreshChecks = useCallback(async () => {- if (!page.plan) {+ const planName = page.plan?.name;+ if (!planName) {return [];}const nextPlan = await planServiceClientConnect.getPlan(create(GetPlanRequestSchema, {- name: page.plan.name,+ name: planName,}));@@ -101,7 +102,7 @@ export function IssueDetailChecks() {try {const response = await planServiceClientConnect.getPlanCheckRun(create(GetPlanCheckRunRequestSchema, {- name: `${page.plan.name}/planCheckRun`,+ name: `${planName}/planCheckRun`,}));nextPlanCheckRuns = [response];@@ -114,7 +115,7 @@ export function IssueDetailChecks() {planCheckRuns: nextPlanCheckRuns,});return nextPlanCheckRuns;- }, [page.plan]);+ }, [page.plan?.name, page.patchState]);const runChecks = useCallback(async () => {if (!page.plan?.name) {diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailLabels.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailLabels.tsxindex a38447e1d3..89efe55fac 100644--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailLabels.tsx+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailLabels.tsx@@ -18,6 +18,7 @@ import { PROJECT_V1_ROUTE_SETTINGS } from "@/router/dashboard/projectV1";import { pushNotification, useProjectV1Store } from "@/store";import { getProjectName, projectNamePrefix } from "@/store/modules/v1/common";import {+ IssueSchema,IssueStatus,UpdateIssueRequestSchema,} from "@/types/proto-es/v1/issue_service_pb";@@ -77,11 +78,12 @@ export function IssueDetailLabels() {}try {setIsUpdating(true);+ const issuePatch = create(IssueSchema, {+ ...page.issue,+ labels,+ });const request = create(UpdateIssueRequestSchema, {- issue: {- ...page.issue,- labels,- },+ issue: issuePatch,updateMask: { paths: ["labels"] },});const response = await issueServiceClientConnect.updateIssue(request);diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailStatementSection.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailStatementSection.tsxindex 99ba3b321f..da9d6019b2 100644--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailStatementSection.tsx+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailStatementSection.tsx@@ -50,6 +50,7 @@ import { useIssueDetailContext } from "../context/IssueDetailContext";import {createEmptyLocalSheet,getLocalSheetByName,+ removeLocalSheet,} from "../utils/localSheet";const MAX_DISPLAYED_RELEASE_FILES = 4;@@ -340,6 +341,7 @@ export function IssueDetailStatementSection({setIsSaving(true);const sheet = createEmptyLocalSheet();setSheetStatement(sheet, draftStatement);+ const previousSheetName = sheetName;const createdSheet = await sheetStore.createSheet(project.name, sheet);const nextPlan = patchPlanStatement(page.plan, spec, createdSheet.name);if (!nextPlan) {@@ -355,6 +357,12 @@ export function IssueDetailStatementSection({page.patchState({plan: response,});+ // Drop the orphaned local sheet only after the spec is committed —+ // an updatePlan failure would otherwise leave the spec referencing+ // a now-empty local entry, losing the user's typed content.+ if (extractSheetUID(previousSheetName).startsWith("-")) {+ removeLocalSheet(previousSheetName);+ }setStatement(draftStatement);setIsEditing(false);pushNotification({@@ -455,7 +463,7 @@ export function IssueDetailStatementSection({{t("common.loading")}</div>) : statement || isEditing ? (- <div className="relative">+ <div className="relative overflow-hidden rounded-sm border border-control-border">{isEditing ? (<MonacoEditorautoCompleteContext={autoCompleteContext}diff --git a/frontend/src/react/pages/project/issue-detail/utils/actionRegistry.ts b/frontend/src/react/pages/project/issue-detail/utils/actionRegistry.tsindex 19faf7e999..abb186f434 100644--- a/frontend/src/react/pages/project/issue-detail/utils/actionRegistry.ts+++ b/frontend/src/react/pages/project/issue-detail/utils/actionRegistry.ts@@ -433,7 +433,9 @@ export const createIssueDetailActions = (t: TFunction): ActionDefinition[] => {if (ctx.isExportPlan) {return t("common.only-creator-allowed-export");}- return t("common.missing-required-permission");+ return t("common.missing-required-permission", {+ permissions: "bb.taskRuns.create",+ });}return undefined;},diff --git a/frontend/src/react/pages/project/issue-detail/utils/localSheet.ts b/frontend/src/react/pages/project/issue-detail/utils/localSheet.tsindex 1fe49c620a..74ddd251eb 100644--- a/frontend/src/react/pages/project/issue-detail/utils/localSheet.ts+++ b/frontend/src/react/pages/project/issue-detail/utils/localSheet.ts@@ -1,12 +1,19 @@import { create } from "@bufbuild/protobuf";-import { reactive } from "vue";import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";import { SheetSchema } from "@/types/proto-es/v1/sheet_service_pb";-const localSheetsByName = reactive(new Map<string, Sheet>());+const state = {+ uid: -101,+};++const localSheetsByName = new Map<string, Sheet>();export const createEmptyLocalSheet = () => {- return reactive(create(SheetSchema, {}));+ return create(SheetSchema, {});+};++export const getNextLocalSheetUID = () => {+ return String(state.uid--);};export const getLocalSheetByName = (name: string): Sheet => {@@ -14,10 +21,14 @@ export const getLocalSheetByName = (name: string): Sheet => {if (existing) {return existing;}- const sheet = reactive({+ const sheet = create(SheetSchema, {...createEmptyLocalSheet(),name,});localSheetsByName.set(name, sheet);return sheet;};++export const removeLocalSheet = (name: string): void => {+ localSheetsByName.delete(name);+};diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsxindex 028969f663..d5415f2276 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsx@@ -14,6 +14,7 @@ import { FeatureBadge } from "@/react/components/FeatureBadge";import { getAvatarColor, getInitials } from "@/react/components/UserAvatar";import { Button } from "@/react/components/ui/button";import { Tooltip } from "@/react/components/ui/tooltip";+import { useVueState } from "@/react/hooks/useVueState";import { cn } from "@/react/lib/utils";import { router } from "@/router";import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";@@ -32,7 +33,7 @@ import {useIssueCommentStore,} from "@/store/modules/v1/issueComment";import { RiskLevel, State } from "@/types/proto-es/v1/common_pb";-import type { Issue } from "@/types/proto-es/v1/issue_service_pb";+import type { Issue, IssueComment } from "@/types/proto-es/v1/issue_service_pb";import {Issue_ApprovalStatus,Issue_Approver_Status,@@ -57,6 +58,11 @@ import { usePlanDetailContext } from "../context/PlanDetailContext";type ApprovalStepStatus = "approved" | "rejected" | "current" | "pending";+// Stable empty array for the comments selector — useVueState's getter must+// return a cached reference when we want React to skip re-renders, otherwise+// useSyncExternalStore will treat every render as a snapshot change.+const EMPTY_COMMENTS: IssueComment[] = [];+export function PlanDetailSidebarApprovalFlow() {return <PlanDetailApprovalFlowContent mode="sidebar" />;}@@ -108,15 +114,15 @@ function PlanDetailApprovalFlowContent({.catch(() => undefined);}, [issue?.name, issueCommentStore, mode]);- if (!issue) {- return null;- }-- const approvalSteps = issue.approvalTemplate?.flow?.roles ?? [];- const statusTag = getStatusTag(issue, approvalSteps.length, t);- const comments = issueCommentStore.getIssueComments(issue.name);+ const comments = useVueState(() => {+ if (!issue) return EMPTY_COMMENTS;+ const list = issueCommentStore.getIssueComments(issue.name);+ // The store returns a fresh `[]` on cache miss; normalise to a stable+ // reference so useSyncExternalStore can short-circuit re-renders.+ return list.length > 0 ? list : EMPTY_COMMENTS;+ });const lastRejection = useMemo(() => {- if (issue.approvalStatus !== Issue_ApprovalStatus.REJECTED) {+ if (!issue || issue.approvalStatus !== Issue_ApprovalStatus.REJECTED) {return undefined;}for (let i = comments.length - 1; i >= 0; i--) {@@ -129,7 +135,14 @@ function PlanDetailApprovalFlowContent({}}return undefined;- }, [comments, issue.approvalStatus]);+ }, [comments, issue]);++ if (!issue) {+ return null;+ }++ const approvalSteps = issue.approvalTemplate?.flow?.roles ?? [];+ const statusTag = getStatusTag(issue, approvalSteps.length, t);const issueUID = extractIssueUID(issue.name);const riskLevelText =issue.riskLevel === RiskLevel.LOW@@ -658,7 +671,10 @@ function useApprovalStep(issue: Issue, step: string, stepIndex: number) {const [reRequesting, setReRequesting] = useState(false);const projectName = `${projectNamePrefix}${page.projectId}`;const currentUserEmail = currentUser?.email ?? "";- const project = projectStore.getProjectByName(projectName);+ const project = useVueState(() => projectStore.getProjectByName(projectName));+ const projectIamPolicy = useVueState(() =>+ projectIamPolicyStore.getProjectIamPolicy(projectName)+ );const stepApprover = issue.approvers[stepIndex];const status = useMemo<ApprovalStepStatus>(() => {@@ -698,9 +714,9 @@ function useApprovalStep(issue: Issue, step: string, stepIndex: number) {}, [currentUserEmail, issue.creator, stepApprover?.status]);const groupNamesKey = useMemo(() => {- const policy = projectIamPolicyStore.getProjectIamPolicy(projectName);+ if (!projectIamPolicy) return "";const names: string[] = [];- for (const binding of policy.bindings) {+ for (const binding of projectIamPolicy.bindings) {if (binding.role !== step || isBindingPolicyExpired(binding)) continue;for (const member of binding.members) {if (member.startsWith(groupBindingPrefix)) {@@ -709,7 +725,7 @@ function useApprovalStep(issue: Issue, step: string, stepIndex: number) {}}return [...new Set(names)].sort().join("\u0000");- }, [projectIamPolicyStore, projectName, step]);+ }, [projectIamPolicy, step]);const groupNames = useMemo(() => (groupNamesKey ? groupNamesKey.split("\u0000") : []),[groupNamesKey]@@ -720,8 +736,8 @@ function useApprovalStep(issue: Issue, step: string, stepIndex: number) {}, [groupNames, groupStore]);const candidateEmailsKey = useMemo(() => {- const policy = projectIamPolicyStore.getProjectIamPolicy(projectName);- const memberMap = memberMapToRolesInProjectIAM(policy, step);+ if (!projectIamPolicy) return "";+ const memberMap = memberMapToRolesInProjectIAM(projectIamPolicy, step);const candidates: string[] = [];for (const fullname of memberMap.keys()) {if (fullname.startsWith(userNamePrefix)) {@@ -729,7 +745,7 @@ function useApprovalStep(issue: Issue, step: string, stepIndex: number) {}}return [...new Set(candidates)].sort().join("\u0000");- }, [projectIamPolicyStore, projectName, step]);+ }, [projectIamPolicy, step]);const candidateEmails = useMemo(() => (candidateEmailsKey ? candidateEmailsKey.split("\u0000") : []),[candidateEmailsKey]diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsxindex 7aba9cb1fa..21edf9f381 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx@@ -107,7 +107,11 @@ import {updateRoleSetter,updateTransactionMode,} from "../utils/directiveUtils";-import { getLocalSheetByName, getNextLocalSheetUID } from "../utils/localSheet";+import {+ getLocalSheetByName,+ getNextLocalSheetUID,+ removeLocalSheet,+} from "../utils/localSheet";import {allowGhostForDatabase,getPlanOptionVisibility,@@ -164,7 +168,9 @@ export function PlanDetailChangesBranch({const { patchState } = page;const currentUser = useCurrentUserV1().value;const projectStore = useProjectV1Store();- const project = projectStore.getProjectByName(`projects/${page.projectId}`);+ const project = useVueState(() =>+ projectStore.getProjectByName(`projects/${page.projectId}`)+ );const sheetStore = useSheetV1Store();const [showAddSpecSheet, setShowAddSpecSheet] = useState(false);const [showTargetSelectorSheet, setShowTargetSelectorSheet] = useState(false);@@ -239,6 +245,7 @@ export function PlanDetailChangesBranch({project.name,localSheet);+ removeLocalSheet(localSheet.name);if (spec.config.case === "changeDatabaseConfig") {spec.config.value.sheet = createdSheet.name;}@@ -476,7 +483,9 @@ function OptionsSection({ selectedSpec }: { selectedSpec: Plan_Spec }) {const { patchState, refreshState } = page;const currentUser = useCurrentUserV1().value;const projectStore = useProjectV1Store();- const project = projectStore.getProjectByName(`projects/${page.projectId}`);+ const project = useVueState(() =>+ projectStore.getProjectByName(`projects/${page.projectId}`)+ );const databaseStore = useDatabaseV1Store();const dbGroupStore = useDBGroupStore();const sheetStore = useSheetV1Store();diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChecks.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChecks.tsxindex 260c13b18a..359a671c8b 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChecks.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChecks.tsx@@ -23,15 +23,21 @@ import {SheetTitle,} from "@/react/components/ui/sheet";import { Tooltip } from "@/react/components/ui/tooltip";+import { useVueState } from "@/react/hooks/useVueState";import { cn } from "@/react/lib/utils";import {projectNamePrefix,pushNotification,useCurrentUserV1,+ useDBGroupStore,useProjectV1Store,} from "@/store";import { extractUserEmail } from "@/store/modules/v1/common";-import { getDateForPbTimestampProtoEs } from "@/types";+import {+ getDateForPbTimestampProtoEs,+ 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 {GetPlanCheckRunRequestSchema,@@ -46,6 +52,7 @@ import { hasProjectPermissionV2 } from "@/utils";import { extractDatabaseResourceName } from "@/utils/v1/database";import { usePlanDetailContext } from "../context/PlanDetailContext";import {+ expandSpecTargets,getFilteredResultGroups,getPlanCheckSummary,type PlanCheckSummary,@@ -63,16 +70,61 @@ export function PlanDetailChecks({const page = usePlanDetailContext();const { patchState } = page;const projectStore = useProjectV1Store();+ const dbGroupStore = useDBGroupStore();const currentUser = useCurrentUserV1().value;const [isRunningChecks, setIsRunningChecks] = useState(false);const [selectedResultStatus, setSelectedResultStatus] = useState<Advice_Level | undefined>();const projectName = `${projectNamePrefix}${page.projectId}`;- const project = projectStore.getProjectByName(projectName);+ const project = useVueState(() => projectStore.getProjectByName(projectName));++ // Plan check results are keyed by per-database resource names even for+ // db-group specs (the scheduler expands targets at runtime). Pre-fetch any+ // db-group target this spec references so we can resolve it to the matched+ // databases when filtering check results below.+ const dbGroupTargets = useMemo(() => {+ if (selectedSpec.config.case === "changeDatabaseConfig") {+ return (selectedSpec.config.value.targets ?? []).filter(+ isValidDatabaseGroupName+ );+ }+ if (selectedSpec.config.case === "exportDataConfig") {+ return (selectedSpec.config.value.targets ?? []).filter(+ isValidDatabaseGroupName+ );+ }+ return [];+ }, [selectedSpec]);+ useEffect(() => {+ for (const target of dbGroupTargets) {+ void dbGroupStore+ .getOrFetchDBGroupByName(target, { view: DatabaseGroupView.FULL })+ .catch(() => undefined);+ }+ }, [dbGroupStore, dbGroupTargets]);+ // Stable join-key so useVueState can detect changes via Object.is+ // — returning a fresh array each call would trigger an update loop.+ const expandedTargetsKey = useVueState(() => {+ const targets = expandSpecTargets(selectedSpec, (name) => {+ if (!isValidDatabaseGroupName(name)) return undefined;+ const group = dbGroupStore.getDBGroupByName(name, DatabaseGroupView.FULL);+ return group.matchedDatabases.map((db) => db.name);+ });+ return targets.join("\u0000");+ });+ const expandedTargets = useMemo(+ () => (expandedTargetsKey ? expandedTargetsKey.split("\u0000") : []),+ [expandedTargetsKey]+ );const filteredPlanCheckRuns = useMemo(- () => planCheckRunListForSpec(page.planCheckRuns, selectedSpec),- [page.planCheckRuns, selectedSpec]+ () =>+ planCheckRunListForSpec(+ page.planCheckRuns,+ selectedSpec,+ expandedTargets+ ),+ [page.planCheckRuns, selectedSpec, expandedTargets]);const summary = useMemo(() => getPlanCheckSummary(filteredPlanCheckRuns),diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsxindex 31feb11ca7..883c37e7cf 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx@@ -49,7 +49,7 @@ import {hasChecksWarning,shouldStayOnPlanDetailPage,} from "../utils/header";-import { getLocalSheetByName } from "../utils/localSheet";+import { getLocalSheetByName, removeLocalSheet } from "../utils/localSheet";export function PlanDetailHeader() {const { t } = useTranslation();@@ -279,6 +279,7 @@ export function PlanDetailHeader() {if (uid.startsWith("-")) {const local = getLocalSheetByName(config.sheet);const createdSheet = await sheetStore.createSheet(project.name, local);+ removeLocalSheet(config.sheet);config.sheet = createdSheet.name;}}diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailRollbackSheet.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailRollbackSheet.tsxindex a343c0074c..6b3ee0782d 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailRollbackSheet.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailRollbackSheet.tsx@@ -21,6 +21,7 @@ import {SheetHeader,SheetTitle,} from "@/react/components/ui/sheet";+import { useVueState } from "@/react/hooks/useVueState";import { router } from "@/router";import { PROJECT_V1_ROUTE_PLAN_DETAIL } from "@/router/dashboard/projectV1";import { pushNotification, useProjectV1Store, useSheetV1Store } from "@/store";@@ -66,7 +67,9 @@ export function PlanDetailRollbackSheet({const normalizedProjectName = projectName.startsWith("projects/")? projectName: `projects/${projectName}`;- const project = projectStore.getProjectByName(normalizedProjectName);+ const project = useVueState(() =>+ projectStore.getProjectByName(normalizedProjectName)+ );const [loading, setLoading] = useState(false);const [selectedTaskRunNames, setSelectedTaskRunNames] = useState<string[]>([]@@ -234,7 +237,7 @@ export function PlanDetailRollbackSheet({</div>) : preview.statement ? (<ReadonlyMonaco- className="relative h-auto max-h-[320px] min-h-[120px]"+ className="relative h-auto max-h-[320px] min-h-[120px] overflow-hidden rounded-md border border-control-border"content={preview.statement}language="sql"/>diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsxindex 1c6f7b4f69..e8e3b905fb 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx@@ -47,6 +47,7 @@ import { usePlanDetailContext } from "../context/PlanDetailContext";import {createEmptyLocalSheet,getLocalSheetByName,+ removeLocalSheet,} from "../utils/localSheet";import { getSQLAdviceMarkers } from "../utils/sqlAdvice";import { SchemaEditorSheet } from "./SchemaEditorSheet";@@ -319,6 +320,7 @@ export function PlanDetailStatementSection({setIsSaving(true);const sheet = createEmptyLocalSheet();setSheetStatement(sheet, draftStatement);+ const previousSheetName = sheetName;const createdSheet = await sheetStore.createSheet(project.name, sheet);const nextPlan = patchPlanStatement(createdSheet.name);if (!nextPlan) return;@@ -328,6 +330,16 @@ export function PlanDetailStatementSection({});const response = await planServiceClientConnect.updatePlan(request);page.patchState({ plan: response });+ // Drop the orphaned local sheet only after the spec is committed+ // to the new server sheet — otherwise an updatePlan failure would+ // leave the spec pointing at a now-empty local entry, losing the+ // user's typed content on the next read.+ if (+ previousSheetName &&+ extractSheetUID(previousSheetName).startsWith("-")+ ) {+ removeLocalSheet(previousSheetName);+ }setStatement(draftStatement);setIsEditing(false);pushNotification({diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskItem.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskItem.tsxindex 59cc99b8fc..077764f976 100644--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskItem.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskItem.tsx@@ -300,7 +300,7 @@ export function DeployTaskItem({<><ReadonlyMonacoclassName={cn(- "relative max-h-64 min-h-[120px] overflow-hidden text-sm",+ "relative max-h-64 min-h-[120px] overflow-hidden rounded border text-sm",isTruncated && "rounded-b-none")}content={statement}diff --git a/frontend/src/react/pages/project/plan-detail/utils/localSheet.ts b/frontend/src/react/pages/project/plan-detail/utils/localSheet.tsindex 09e9aab6bd..74ddd251eb 100644--- a/frontend/src/react/pages/project/plan-detail/utils/localSheet.ts+++ b/frontend/src/react/pages/project/plan-detail/utils/localSheet.ts@@ -28,3 +28,7 @@ export const getLocalSheetByName = (name: string): Sheet => {localSheetsByName.set(name, sheet);return sheet;};++export const removeLocalSheet = (name: string): void => {+ localSheetsByName.delete(name);+};diff --git a/frontend/src/react/pages/project/plan-detail/utils/planCheck.ts b/frontend/src/react/pages/project/plan-detail/utils/planCheck.tsindex 1153f11852..3a4170d752 100644--- a/frontend/src/react/pages/project/plan-detail/utils/planCheck.ts+++ b/frontend/src/react/pages/project/plan-detail/utils/planCheck.ts@@ -65,11 +65,19 @@ const targetsForSpec = (spec: Plan_Spec): string[] => {return [];};+// The plan-check scheduler expands a db-group spec into per-database targets+// before running checks (see backend/runner/plancheck/derive.go), so result.target+// is always a database resource name. The spec, however, still stores the+// db-group name. The caller is responsible for resolving any db-group target to+// its matched database names before calling this function; otherwise checks for+// db-group specs would silently render empty.export const planCheckRunListForSpec = (planCheckRuns: PlanCheckRun[],- spec: Plan_Spec+ spec: Plan_Spec,+ expandedTargets?: string[]): PlanCheckRun[] => {- const targetSet = new Set(targetsForSpec(spec));+ const targets = expandedTargets ?? targetsForSpec(spec);+ const targetSet = new Set(targets);if (targetSet.size === 0) {return [];}@@ -91,6 +99,17 @@ export const planCheckRunListForSpec = (});};+export const expandSpecTargets = (+ spec: Plan_Spec,+ resolveDatabaseGroup: (name: string) => string[] | undefined+): string[] => {+ const raw = targetsForSpec(spec);+ return raw.flatMap((target) => {+ const databases = resolveDatabaseGroup(target);+ return databases ?? [target];+ });+};+export const getFilteredResultGroups = ({includeRunFailure = false,planCheckRuns,