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(frontend): stop rollout stage/spec switch flicker (BYT-9762, BYT-9763) (#20652)
boojack49a2432951aa
diff --git a/frontend/src/react/hooks/useSheetStatement.test.tsx b/frontend/src/react/hooks/useSheetStatement.test.tsxnew file mode 100644index 0000000000..86c6ec977f--- /dev/null+++ b/frontend/src/react/hooks/useSheetStatement.test.tsx@@ -0,0 +1,111 @@+import { render, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, test, vi } from "vitest";+import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";+import {+ type SheetStatementSnapshot,+ seedSheetStatement,+ useSheetStatement,+} from "./useSheetStatement";++const getSheetByName = vi.fn();+const getOrFetchSheetByName = vi.fn();++vi.mock("@/react/stores/app", () => ({+ useAppStore: {+ getState: () => ({ getSheetByName, getOrFetchSheetByName }),+ },+}));+vi.mock("@/utils/sheet", () => ({+ getStatementSize: (statement: string) => statement.length,+}));+vi.mock("@/utils/v1/sheet", () => ({+ getSheetStatement: (sheet: { statement: string }) => sheet.statement,+ extractSheetUID: (name: string) => name.split("/").pop() ?? "",+}));++const sheet = (statement: string, contentSize = statement.length): Sheet =>+ ({ statement, contentSize }) as unknown as Sheet;++const renderSnapshots = (props: Parameters<typeof useSheetStatement>[0]) => {+ const snapshots: SheetStatementSnapshot[] = [];+ const Probe = () => {+ snapshots.push(useSheetStatement(props));+ return null;+ };+ const result = render(<Probe />);+ return { snapshots, rerender: () => result.rerender(<Probe />) };+};++describe("useSheetStatement", () => {+ beforeEach(() => {+ getSheetByName.mockReset();+ getOrFetchSheetByName.mockReset();+ });++ test("paints a cached remote statement on the first render", () => {+ getSheetByName.mockReturnValue(sheet("select 1;"));+ const { snapshots } = renderSnapshots({+ enabled: true,+ sheetName: "projects/p/sheets/1",+ });+ expect(snapshots[0]).toEqual({+ statement: "select 1;",+ isLoading: false,+ isTruncated: false,+ });+ expect(getOrFetchSheetByName).not.toHaveBeenCalled();+ });++ test("shows loading (not empty) on the first render when a fetch is needed", async () => {+ getSheetByName.mockReturnValue(undefined);+ getOrFetchSheetByName.mockResolvedValue(sheet("select 2;"));+ const { snapshots } = renderSnapshots({+ enabled: true,+ sheetName: "projects/p/sheets/2",+ });+ expect(snapshots[0]).toEqual({+ statement: "",+ isLoading: true,+ isTruncated: false,+ });+ await waitFor(() => {+ expect(snapshots.at(-1)?.statement).toBe("select 2;");+ expect(snapshots.at(-1)?.isLoading).toBe(false);+ });+ });++ test("reads a draft (local) sheet synchronously without fetching", () => {+ const getLocalSheet = vi.fn().mockReturnValue(sheet("select 3;"));+ const { snapshots } = renderSnapshots({+ enabled: true,+ sheetName: "projects/p/sheets/-1",+ getLocalSheet,+ });+ expect(snapshots[0].statement).toBe("select 3;");+ expect(snapshots[0].isLoading).toBe(false);+ expect(getLocalSheet).toHaveBeenCalledWith("projects/p/sheets/-1");+ expect(getOrFetchSheetByName).not.toHaveBeenCalled();+ });++ test("seedSheetStatement marks oversized previews as truncated", () => {+ getSheetByName.mockReturnValue(sheet("select 1;", 9999));+ expect(seedSheetStatement("projects/p/sheets/1")).toEqual({+ statement: "select 1;",+ isLoading: false,+ isTruncated: true,+ });+ });++ test("is empty and not loading when disabled", () => {+ const { snapshots } = renderSnapshots({+ enabled: false,+ sheetName: "projects/p/sheets/1",+ });+ expect(snapshots[0]).toEqual({+ statement: "",+ isLoading: false,+ isTruncated: false,+ });+ expect(getSheetByName).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/react/hooks/useSheetStatement.ts b/frontend/src/react/hooks/useSheetStatement.tsnew file mode 100644index 0000000000..56bb7a0c76--- /dev/null+++ b/frontend/src/react/hooks/useSheetStatement.ts@@ -0,0 +1,131 @@+import { useEffect, useState } from "react";+import { useAppStore } from "@/react/stores/app";+import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";+import { getStatementSize } from "@/utils/sheet";+import { extractSheetUID, getSheetStatement } from "@/utils/v1/sheet";++export type SheetStatementSnapshot = {+ statement: string;+ /** A fetch is in flight; render a loading state rather than an empty one. */+ isLoading: boolean;+ /** The cached statement is a preview of a larger sheet (size < contentSize). */+ isTruncated: boolean;+};++const EMPTY_SNAPSHOT: SheetStatementSnapshot = {+ statement: "",+ isLoading: false,+ isTruncated: false,+};++const snapshotOfSheet = (sheet: Sheet): SheetStatementSnapshot => {+ const statement = getSheetStatement(sheet);+ return {+ statement,+ isLoading: false,+ isTruncated: getStatementSize(statement) < sheet.contentSize,+ };+};++/**+ * Resolve a sheet's statement synchronously from what is already in memory, so+ * the first paint never shows an empty "No data" placeholder before the loader+ * has started. Local (draft) sheets are always in memory; a remote sheet is+ * used when cached, otherwise we report `isLoading` because a fetch will run.+ *+ * `getLocalSheet` is injected so this stays decoupled from any single page's+ * local-sheet store; callers that never use draft sheets (e.g. rollout tasks)+ * can omit it.+ */+export const seedSheetStatement = (+ sheetName: string,+ getLocalSheet?: (name: string) => Sheet | undefined+): SheetStatementSnapshot => {+ if (!sheetName) {+ return EMPTY_SNAPSHOT;+ }+ if (extractSheetUID(sheetName).startsWith("-")) {+ const localSheet = getLocalSheet?.(sheetName);+ return localSheet ? snapshotOfSheet(localSheet) : EMPTY_SNAPSHOT;+ }+ const cached = useAppStore.getState().getSheetByName(sheetName);+ return cached+ ? snapshotOfSheet(cached)+ : { statement: "", isLoading: true, isTruncated: false };+};++/**+ * Load a sheet's statement without the first-paint "No data" flash. State is+ * seeded synchronously from cache (see {@link seedSheetStatement}) and re-seeded+ * during render whenever the sheet changes — so switching specs/stages paints+ * the cached statement (or a loading state) immediately instead of flashing the+ * previous sheet's content or an empty placeholder, then a remote fetch fills in+ * any sheet that wasn't cached.+ *+ * The render-time re-seed keeps it correct under both call-site idioms: a+ * consumer may remount it per entity (`key={id}`) or reuse a single instance as+ * the `sheetName` prop changes. Owner components that keep their own mutable+ * statement reuse {@link seedSheetStatement} directly instead.+ */+export const useSheetStatement = ({+ enabled,+ sheetName,+ getLocalSheet,+}: {+ enabled: boolean;+ sheetName: string;+ getLocalSheet?: (name: string) => Sheet | undefined;+}): SheetStatementSnapshot => {+ const [snapshot, setSnapshot] = useState<SheetStatementSnapshot>(() =>+ enabled ? seedSheetStatement(sheetName, getLocalSheet) : EMPTY_SNAPSHOT+ );++ const seedKey = enabled ? sheetName : "";+ const [trackedSeedKey, setTrackedSeedKey] = useState(seedKey);+ if (seedKey !== trackedSeedKey) {+ setTrackedSeedKey(seedKey);+ setSnapshot(+ enabled ? seedSheetStatement(sheetName, getLocalSheet) : EMPTY_SNAPSHOT+ );+ }++ useEffect(() => {+ if (!enabled || !sheetName) {+ return;+ }+ // Local and already-cached sheets were seeded synchronously above.+ if (extractSheetUID(sheetName).startsWith("-")) {+ return;+ }+ if (useAppStore.getState().getSheetByName(sheetName)) {+ return;+ }++ let canceled = false;+ const load = async () => {+ try {+ const sheet = await useAppStore+ .getState()+ .getOrFetchSheetByName(sheetName);+ if (canceled || !sheet) {+ return;+ }+ setSnapshot(snapshotOfSheet(sheet));+ } finally {+ if (!canceled) {+ setSnapshot((prev) =>+ prev.isLoading ? { ...prev, isLoading: false } : prev+ );+ }+ }+ };+ void load();+ return () => {+ canceled = true;+ };+ // getLocalSheet is intentionally excluded: only the synchronous seed reads+ // it, and the effect handles remote sheets exclusively.+ }, [enabled, sheetName]);++ return snapshot;+};diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsxindex 97c600ddf1..90e3920a0c 100644--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx@@ -22,6 +22,7 @@ import {} from "@/react/components/ui/sheet";import { Switch } from "@/react/components/ui/switch";import { Tooltip } from "@/react/components/ui/tooltip";+import { useSheetStatement } from "@/react/hooks/useSheetStatement";import { cn } from "@/react/lib/utils";import { router } from "@/react/router";import {@@ -49,11 +50,9 @@ import {getDefaultTransactionMode,getInstanceResource,} from "@/utils";-import { getStatementSize } from "@/utils/sheet";import { extractDatabaseGroupName } from "@/utils/v1/databaseGroup";import { instanceV1SupportsTransactionMode } from "@/utils/v1/instance";import { sheetNameOfSpec } from "@/utils/v1/issue/plan";-import { extractSheetUID, getSheetStatement } from "@/utils/v1/sheet";import { useIssueDetailContext } from "../context/IssueDetailContext";import { useIssueDetailSpecValidation } from "../hooks/useIssueDetailSpecValidation";import {@@ -152,9 +151,13 @@ export function IssueDetailDatabaseChangeView({<div className="rounded-b-lg border-x border-b border-control-border bg-white px-3 py-2">{selectedSpec && (<div className="flex flex-col gap-2">- <IssueDetailDatabaseChangeTargets selectedSpec={selectedSpec} />+ <IssueDetailDatabaseChangeTargets+ key={selectedSpec.id}+ selectedSpec={selectedSpec}+ /><div className="flex flex-col"><IssueDetailStatementSection+ key={selectedSpec.id}forceReadonlyspec={selectedSpec}/>@@ -175,8 +178,16 @@ function IssueDetailDatabaseChangeOptions({}) {const { t } = useTranslation();const databasesByName = useAppStore((s) => s.databasesByName);- const [sheetStatement, setSheetStatement] = useState("");- const [isSheetOversize, setIsSheetOversize] = useState(false);+ const sheetName = useMemo(+ () => sheetNameOfSpec(selectedSpec),+ [selectedSpec]+ );+ const { statement: sheetStatement, isTruncated: isSheetOversize } =+ useSheetStatement({+ enabled: true,+ sheetName,+ getLocalSheet: getLocalSheetByName,+ });const [instanceRoles, setInstanceRoles] = useState<string[]>([]);const targets = useMemo(() => {@@ -306,35 +317,6 @@ function IssueDetailDatabaseChangeOptions({] satisfies Array<{ label: string; value: IsolationLevel }>;}, [t]);- useEffect(() => {- let canceled = false;- const sheetName = sheetNameOfSpec(selectedSpec);- if (!sheetName) {- setSheetStatement("");- setIsSheetOversize(false);- return;- }-- const loadSheet = async () => {- const uid = extractSheetUID(sheetName);- const sheet = uid.startsWith("-")- ? getLocalSheetByName(sheetName)- : await useAppStore.getState().getOrFetchSheetByName(sheetName);- if (!sheet || canceled) {- return;- }- const statement = getSheetStatement(sheet);- setSheetStatement(statement);- setIsSheetOversize(getStatementSize(statement) < sheet.contentSize);- };-- void loadSheet();-- return () => {- canceled = true;- };- }, [selectedSpec]);-useEffect(() => {let canceled = false;if (!showInstanceRole || !instanceName) {@@ -509,17 +491,21 @@ function IssueDetailDatabaseChangeTargets({}) {const { t } = useTranslation();const databasesByName = useAppStore((s) => s.databasesByName);- const [showAllTargetsDialog, setShowAllTargetsDialog] = useState(false);- const [searchText, setSearchText] = useState("");- const [isLoadingTargets, setIsLoadingTargets] = useState(false);- const [isLoadingAllTargets, setIsLoadingAllTargets] = useState(false);-const targets = useMemo(() => {if (selectedSpec.config?.case === "changeDatabaseConfig") {return selectedSpec.config.value.targets ?? [];}return [];}, [selectedSpec]);+ const [showAllTargetsDialog, setShowAllTargetsDialog] = useState(false);+ const [searchText, setSearchText] = useState("");+ // Start loading when there are targets to resolve, so the first paint shows+ // the spinner instead of blank (unknownDatabase) chips.+ const [isLoadingTargets, setIsLoadingTargets] = useState(+ () => targets.length > 0+ );+ const [isLoadingAllTargets, setIsLoadingAllTargets] = useState(false);+const visibleTargets = useMemo(() => {return targets.slice(0, Math.min(DEFAULT_VISIBLE_TARGETS, targets.length));}, [targets]);diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailStatementSection.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailStatementSection.tsxindex 79dea3db10..b16fb54d74 100644--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailStatementSection.tsx+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailStatementSection.tsx@@ -9,6 +9,7 @@ import { Alert } from "@/react/components/ui/alert";import { Button } from "@/react/components/ui/button";import { useCurrentUser, useReleaseByName } from "@/react/hooks/useAppState";import { useProjectByName } from "@/react/hooks/useProjectByName";+import { seedSheetStatement } from "@/react/hooks/useSheetStatement";import { cn } from "@/react/lib/utils";import { useAppStore } from "@/react/stores/app";import { projectNamePrefix, pushNotification } from "@/store";@@ -68,12 +69,20 @@ export function IssueDetailStatementSection({const release = useReleaseByName(isValidReleaseName(releaseName) ? releaseName : undefined);- const [isLoading, setIsLoading] = useState(false);- const [isSheetOversize, setIsSheetOversize] = useState(false);+ const [isLoading, setIsLoading] = useState(() =>+ isValidReleaseName(releaseName)+ ? false+ : seedSheetStatement(sheetName, getLocalSheetByName).isLoading+ );+ const [isSheetOversize, setIsSheetOversize] = useState(+ () => seedSheetStatement(sheetName, getLocalSheetByName).isTruncated+ );const [isDownloading, setIsDownloading] = useState(false);const [isEditing, setIsEditing] = useState(false);const [isSaving, setIsSaving] = useState(false);- const [statement, setStatement] = useState("");+ const [statement, setStatement] = useState(+ () => seedSheetStatement(sheetName, getLocalSheetByName).statement+ );const [draftStatement, setDraftStatement] = useState("");const inputRef = useRef<HTMLInputElement>(null);@@ -155,12 +164,21 @@ export function IssueDetailStatementSection({return;}+ // Resolve already-in-memory sheets synchronously (no loading/"No data"+ // flash on the first paint); only an uncached remote sheet needs a fetch.+ const seed = seedSheetStatement(sheetName, getLocalSheetByName);+ if (!seed.isLoading) {+ setStatement(seed.statement);+ setIsSheetOversize(seed.isTruncated);+ setIsLoading(false);+ return;+ }+try {setIsLoading(true);- const uid = extractSheetUID(sheetName);- const sheet = uid.startsWith("-")- ? getLocalSheetByName(sheetName)- : await useAppStore.getState().getOrFetchSheetByName(sheetName);+ const sheet = await useAppStore+ .getState()+ .getOrFetchSheetByName(sheetName);if (!sheet || canceled) {return;}diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsxindex f5e1a0f6c6..df33d4f83a 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx@@ -62,6 +62,7 @@ import { Tooltip } from "@/react/components/ui/tooltip";import { useCurrentUser } from "@/react/hooks/useAppState";import { useProjectByName } from "@/react/hooks/useProjectByName";import { useSessionPageSize } from "@/react/hooks/useSessionPageSize";+import { seedSheetStatement } from "@/react/hooks/useSheetStatement";import { cn } from "@/react/lib/utils";import { router } from "@/react/router";import {@@ -102,7 +103,6 @@ import { getStatementSize } from "@/utils/sheet";import { extractDatabaseGroupName } from "@/utils/v1/databaseGroup";import { sheetNameOfSpec } from "@/utils/v1/issue/plan";import {- extractSheetUID,getSheetStatement,setSheetStatement as setLocalSheetStatement,} from "@/utils/v1/sheet";@@ -614,11 +614,13 @@ export function PlanDetailChangesBranch({<div className="flex flex-1 flex-col overflow-y-auto px-4 py-4"><div className="flex flex-col gap-y-4"><TargetsSection+ key={selectedSpec.id}allowEdit={canModifySpecs}onEdit={() => setShowTargetSelectorSheet(true)}selectedSpec={selectedSpec}/><PlanDetailStatementSection+ key={selectedSpec.id}planCheckRuns={page.isCreating? draftCheckRuns@@ -639,6 +641,7 @@ export function PlanDetailChangesBranch({)}{!specHasRelease && (<OptionsSection+ key={selectedSpec.id}onStatementPersisted={() =>handleStatementPersisted(selectedSpec.id)}@@ -716,8 +719,16 @@ function OptionsSection({void projectsByName;const project = useProjectByName(`projects/${page.projectId}`);const databasesByName = useAppStore((s) => s.databasesByName);- const [sheetStatement, setSheetStatementValue] = useState("");- const [isSheetOversize, setIsSheetOversize] = useState(false);+ const sheetName = useMemo(+ () => sheetNameOfSpec(selectedSpec),+ [selectedSpec]+ );+ const [sheetStatement, setSheetStatementValue] = useState(+ () => seedSheetStatement(sheetName, getLocalSheetByName).statement+ );+ const [isSheetOversize, setIsSheetOversize] = useState(+ () => seedSheetStatement(sheetName, getLocalSheetByName).isTruncated+ );const [instanceRoles, setInstanceRoles] = useState<string[]>([]);const targets = useMemo(() => {@@ -823,18 +834,25 @@ function OptionsSection({}, [targets]);useEffect(() => {- let canceled = false;- const sheetName = sheetNameOfSpec(selectedSpec);if (!sheetName) {setSheetStatementValue("");setIsSheetOversize(false);return;}+ // Resolve in-memory sheets synchronously so switching specs shows the new+ // statement's options immediately instead of the previous spec's; only an+ // uncached remote sheet needs a fetch.+ const seed = seedSheetStatement(sheetName, getLocalSheetByName);+ if (!seed.isLoading) {+ setSheetStatementValue(seed.statement);+ setIsSheetOversize(seed.isTruncated);+ return;+ }+ let canceled = false;const load = async () => {- const uid = extractSheetUID(sheetName);- const sheet = uid.startsWith("-")- ? getLocalSheetByName(sheetName)- : await useAppStore.getState().getOrFetchSheetByName(sheetName);+ const sheet = await useAppStore+ .getState()+ .getOrFetchSheetByName(sheetName);if (!sheet || canceled) return;const statement = getSheetStatement(sheet);setSheetStatementValue(statement);@@ -844,7 +862,7 @@ function OptionsSection({return () => {canceled = true;};- }, [selectedSpec]);+ }, [sheetName]);useEffect(() => {let canceled = false;@@ -1206,17 +1224,20 @@ function TargetsSection({}) {const { t } = useTranslation();const databasesByName = useAppStore((s) => s.databasesByName);- const [showAllTargetsDialog, setShowAllTargetsDialog] = useState(false);- const [searchText, setSearchText] = useState("");- const [isLoadingTargets, setIsLoadingTargets] = useState(false);- const [isLoadingAllTargets, setIsLoadingAllTargets] = useState(false);-const targets = useMemo(() => {if (selectedSpec.config?.case === "changeDatabaseConfig") {return selectedSpec.config.value.targets ?? [];}return [];}, [selectedSpec]);+ const [showAllTargetsDialog, setShowAllTargetsDialog] = useState(false);+ const [searchText, setSearchText] = useState("");+ // Start loading when there are targets to resolve, so the first paint shows+ // the spinner instead of blank (unknownDatabase) chips.+ const [isLoadingTargets, setIsLoadingTargets] = useState(+ () => targets.length > 0+ );+ const [isLoadingAllTargets, setIsLoadingAllTargets] = useState(false);const visibleTargets = useMemo(() => targets.slice(0, Math.min(DEFAULT_VISIBLE_TARGETS, targets.length)),[targets]diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsxindex abbe2c8672..0602d2a9a3 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx@@ -11,6 +11,7 @@ import { MonacoEditor, ReadonlyMonaco } from "@/react/components/monaco";import { ReleaseInfoCard } from "@/react/components/release/ReleaseInfoCard";import { Alert } from "@/react/components/ui/alert";import { Button } from "@/react/components/ui/button";+import { seedSheetStatement } from "@/react/hooks/useSheetStatement";import { cn } from "@/react/lib/utils";import { useAppStore } from "@/react/stores/app";import { pushNotification } from "@/store";@@ -74,12 +75,20 @@ export function PlanDetailStatementSection({: "";const sheetName = useMemo(() => sheetNameOfSpec(spec), [spec]);const [release, setRelease] = useState<Release>();- const [isLoading, setIsLoading] = useState(false);- const [isSheetOversize, setIsSheetOversize] = useState(false);+ const [isLoading, setIsLoading] = useState(() =>+ isValidReleaseName(releaseName)+ ? false+ : seedSheetStatement(sheetName, getLocalSheetByName).isLoading+ );+ const [isSheetOversize, setIsSheetOversize] = useState(+ () => seedSheetStatement(sheetName, getLocalSheetByName).isTruncated+ );const [isDownloading, setIsDownloading] = useState(false);const [isEditing, setIsEditing] = useState(page.isCreating);const [isSaving, setIsSaving] = useState(false);- const [statement, setStatement] = useState("");+ const [statement, setStatement] = useState(+ () => seedSheetStatement(sheetName, getLocalSheetByName).statement+ );const [draftStatement, setDraftStatement] = useState("");const [isSchemaEditorOpen, setIsSchemaEditorOpen] = useState(false);const inputRef = useRef<HTMLInputElement>(null);@@ -195,12 +204,22 @@ export function PlanDetailStatementSection({return;}+ // Resolve already-in-memory sheets synchronously (no loading/"No data"+ // flash on the first paint); only an uncached remote sheet needs a fetch.+ const seed = seedSheetStatement(sheetName, getLocalSheetByName);+ if (!seed.isLoading) {+ setStatement(seed.statement);+ setDraftStatement(seed.statement);+ setIsSheetOversize(seed.isTruncated);+ setIsLoading(false);+ return;+ }+try {setIsLoading(true);- const uid = extractSheetUID(sheetName);- const sheet = uid.startsWith("-")- ? getLocalSheetByName(sheetName)- : await useAppStore.getState().getOrFetchSheetByName(sheetName);+ const sheet = await useAppStore+ .getState()+ .getOrFetchSheetByName(sheetName);if (!sheet || canceled) return;const nextStatement = getSheetStatement(sheet);setStatement(nextStatement);diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.test.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.test.tsxnew file mode 100644index 0000000000..4bed04aafa--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.test.tsx@@ -0,0 +1,130 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, test, vi } from "vitest";+import {+ type Stage,+ type Task,+ Task_Status,+} from "@/types/proto-es/v1/rollout_service_pb";+import type { PlanDetailPageState } from "../../shell/hooks/types";+import { PlanDetailProvider } from "../../shell/PlanDetailContext";+import { DeployStageContentView } from "./DeployStageContentView";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++// Stub the task list so the test can read exactly which tasks survive the+// stage's filter, without pulling in DeployTaskItem (Monaco, task actions…).+vi.mock("./DeployTaskList", () => ({+ DeployTaskList: ({ stage }: { stage: Stage }) => (+ <div>+ {stage.tasks.map((task) => (+ <span data-testid="visible-task" key={task.name}>+ {task.name}+ </span>+ ))}+ </div>+ ),+}));++// Stub the filter UI down to a single control that selects the RUNNING filter.+vi.mock("./DeployTaskFilter", () => ({+ DeployTaskFilter: ({+ onChange,+ }: {+ onChange: (statuses: Task_Status[]) => void;+ }) => (+ <button+ data-testid="select-running"+ onClick={() => onChange([Task_Status.RUNNING])}+ type="button"+ >+ running-filter+ </button>+ ),+}));++vi.mock("./DeployStageRollbackSection", () => ({+ DeployStageRollbackSection: () => null,+}));+vi.mock("../PlanDetailTaskRolloutActionPanel", () => ({+ PlanDetailTaskRolloutActionPanel: () => null,+}));+vi.mock("../../../issue-detail/utils/rollout", () => ({+ canRolloutTasks: () => false,+ preloadRolloutPermissionContext: () => Promise.resolve(),+ RUNNABLE_TASK_STATUSES: [],+}));+vi.mock("@/connect", () => ({ rolloutServiceClientConnect: {} }));+vi.mock("@/store", () => ({ pushNotification: () => undefined }));++const makeStage = (+ name: string,+ tasks: Array<{ name: string; status: Task_Status }>+): Stage =>+ ({+ name,+ environment: `environments/${name.split("/").pop()}`,+ tasks: tasks as unknown as Task[],+ }) as unknown as Stage;++const page = {+ currentUser: {},+ project: { name: "projects/p1" },+ issue: undefined,+ plan: { name: "projects/p1/plans/1" },+ refreshState: () => Promise.resolve(),+} as unknown as PlanDetailPageState;++const renderStage = (stage: Stage) => (+ <PlanDetailProvider value={page}>+ <DeployStageContentView stage={stage} />+ </PlanDetailProvider>+);++const visibleTaskNames = () =>+ screen.queryAllByTestId("visible-task").map((node) => node.textContent);++describe("DeployStageContentView filter scoping", () => {+ test("does not carry the task filter across stages (BYT-9762)", () => {+ const testStage = makeStage("projects/p1/rollouts/r1/stages/test", [+ {+ name: "projects/p1/rollouts/r1/stages/test/tasks/t1",+ status: Task_Status.RUNNING,+ },+ {+ name: "projects/p1/rollouts/r1/stages/test/tasks/t2",+ status: Task_Status.DONE,+ },+ ]);+ const prodStage = makeStage("projects/p1/rollouts/r1/stages/prod", [+ {+ name: "projects/p1/rollouts/r1/stages/prod/tasks/p1",+ status: Task_Status.NOT_STARTED,+ },+ {+ name: "projects/p1/rollouts/r1/stages/prod/tasks/p2",+ status: Task_Status.PENDING,+ },+ ]);++ const { rerender } = render(renderStage(testStage));++ // Both Test tasks visible before filtering.+ expect(visibleTaskNames()).toHaveLength(2);++ // Filter the Test stage down to RUNNING tasks.+ fireEvent.click(screen.getByTestId("select-running"));+ expect(visibleTaskNames()).toEqual([+ "projects/p1/rollouts/r1/stages/test/tasks/t1",+ ]);++ // Switch to the Prod stage (same instance, no `key`). Prod has no RUNNING+ // task, so a leaked filter would hide everything; the filter must reset.+ rerender(renderStage(prodStage));+ expect(visibleTaskNames()).toEqual([+ "projects/p1/rollouts/r1/stages/prod/tasks/p1",+ "projects/p1/rollouts/r1/stages/prod/tasks/p2",+ ]);+ });+});diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.tsxindex 4b189d3ae3..ef09fc1c48 100644--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.tsx@@ -33,6 +33,16 @@ export function DeployStageContentView({const currentUser = page.currentUser;const project = page.project;const [filterStatuses, setFilterStatuses] = useState<Task_Status[]>([]);+ // Scope the task filter to the stage: when switching to a different stage,+ // drop the previous stage's filter so it can't silently hide the new stage's+ // tasks (BYT-9762). Resetting during render — rather than in a post-paint+ // effect — keeps the new stage's first paint correct instead of briefly+ // showing the wrong filtered set.+ const [filteredStageName, setFilteredStageName] = useState(stage.name);+ if (stage.name !== filteredStageName) {+ setFilteredStageName(stage.name);+ setFilterStatuses([]);+ }const [rolloutPermissionReady, setRolloutPermissionReady] = useState(false);const [runStageOpen, setRunStageOpen] = useState(false);const stageTaskKey = stage.tasks.map((task) => task.name).join("|");diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.test.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.test.tsxnew file mode 100644index 0000000000..336bebbf6b--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.test.tsx@@ -0,0 +1,78 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, test, vi } from "vitest";+import {+ type Stage,+ type Task,+ Task_Status,+} from "@/types/proto-es/v1/rollout_service_pb";+import type { PlanDetailPageState } from "../../shell/hooks/types";+import { PlanDetailProvider } from "../../shell/PlanDetailContext";+import { DeployTaskList } from "./DeployTaskList";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("./DeployTaskItem", () => ({+ DeployTaskItem: ({+ task,+ isExpanded,+ }: {+ task: Task;+ isExpanded: boolean;+ }) => (+ <div data-expanded={isExpanded ? "true" : "false"} data-testid="task">+ {task.name}+ </div>+ ),+}));++vi.mock("./DeployTaskToolbar", () => ({ DeployTaskToolbar: () => null }));++const page = {+ refreshState: () => Promise.resolve(),+} as unknown as PlanDetailPageState;++const makeStage = (name: string, taskNames: string[]): Stage =>+ ({+ name,+ environment: "environments/test",+ tasks: taskNames.map((taskName) => ({+ name: taskName,+ status: Task_Status.NOT_STARTED,+ })) as unknown as Task[],+ }) as unknown as Stage;++const expandedOf = (taskName: string) =>+ screen.getByText(taskName).getAttribute("data-expanded");++const renderList = (stage: Stage) => (+ <PlanDetailProvider value={page}>+ <DeployTaskList readonly stage={stage} />+ </PlanDetailProvider>+);++describe("DeployTaskList stage switching (BYT-9763)", () => {+ test("auto-expands the new stage's first task on switch, without a stale frame", () => {+ const stageA = makeStage("rollouts/r/stages/a", [+ "rollouts/r/stages/a/tasks/a1",+ "rollouts/r/stages/a/tasks/a2",+ ]);+ const stageB = makeStage("rollouts/r/stages/b", [+ "rollouts/r/stages/b/tasks/b1",+ "rollouts/r/stages/b/tasks/b2",+ ]);++ const { rerender } = render(renderList(stageA));+ expect(expandedOf("rollouts/r/stages/a/tasks/a1")).toBe("true");+ expect(expandedOf("rollouts/r/stages/a/tasks/a2")).toBe("false");++ // Switch stage on the same instance. The first task of the new stage must+ // be expanded immediately — derived during render — instead of relying on+ // a post-paint effect that briefly leaves the list collapsed.+ rerender(renderList(stageB));+ expect(screen.queryByText("rollouts/r/stages/a/tasks/a1")).toBeNull();+ expect(expandedOf("rollouts/r/stages/b/tasks/b1")).toBe("true");+ expect(expandedOf("rollouts/r/stages/b/tasks/b2")).toBe("false");+ });+});diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.tsxindex 71c06684d2..b0b259988a 100644--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.tsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useState } from "react";+import { useMemo, useState } from "react";import { useTranslation } from "react-i18next";import { Button } from "@/react/components/ui/button";import type { Stage, Task } from "@/types/proto-es/v1/rollout_service_pb";@@ -22,46 +22,44 @@ export function DeployTaskList({const page = usePlanDetailContext();const [displayedTaskCount, setDisplayedTaskCount] =useState(DEFAULT_PAGE_SIZE);- const [expandedTaskNames, setExpandedTaskNames] = useState<Set<string>>(- new Set()+ const filteredTasks = stage.tasks;+ const [expandedTaskNames, setExpandedTaskNames] = useState<Set<string>>(() =>+ filteredTasks.length > 0 ? new Set([filteredTasks[0].name]) : new Set());const [selectedTaskNames, setSelectedTaskNames] = useState<Set<string>>(new Set());- const filteredTasks = stage.tasks;- const visibleTasks = filteredTasks.slice(0, displayedTaskCount);- const hasMoreTasks = filteredTasks.length > displayedTaskCount;- const remainingTasksCount = filteredTasks.length - displayedTaskCount;- const selectedTasks = useMemo(- () => filteredTasks.filter((task) => selectedTaskNames.has(task.name)),- [filteredTasks, selectedTaskNames]- );const taskNamesKey = filteredTasks.map((task) => task.name).join(",");- useEffect(() => {+ // When the visible task set changes — most importantly when switching to a+ // different stage — re-derive the per-stage list state (pagination, the+ // auto-expanded first task, and the still-valid selection) during render+ // rather than in a post-paint effect. Doing it here means the new stage's+ // first paint already shows the first task expanded, instead of painting a+ // collapsed list and expanding it a frame later, which read as a flash+ // (BYT-9763).+ const [trackedTaskNamesKey, setTrackedTaskNamesKey] = useState(taskNamesKey);+ if (taskNamesKey !== trackedTaskNamesKey) {+ setTrackedTaskNamesKey(taskNamesKey);setDisplayedTaskCount(DEFAULT_PAGE_SIZE);- }, [taskNamesKey]);-- useEffect(() => {- setExpandedTaskNames(() => {- if (filteredTasks.length === 0) {- return new Set();- }- return new Set([filteredTasks[0].name]);- });- }, [taskNamesKey]);-- useEffect(() => {+ setExpandedTaskNames(+ filteredTasks.length > 0 ? new Set([filteredTasks[0].name]) : new Set()+ );setSelectedTaskNames((prev) => {const remaining = [...prev].filter((taskName) =>filteredTasks.some((task) => task.name === taskName));- if (remaining.length === prev.size) {- return prev;- }- return new Set(remaining);+ return remaining.length === prev.size ? prev : new Set(remaining);});- }, [taskNamesKey]);+ }++ const visibleTasks = filteredTasks.slice(0, displayedTaskCount);+ const hasMoreTasks = filteredTasks.length > displayedTaskCount;+ const remainingTasksCount = filteredTasks.length - displayedTaskCount;+ const selectedTasks = useMemo(+ () => filteredTasks.filter((task) => selectedTaskNames.has(task.name)),+ [filteredTasks, selectedTaskNames]+ );const toggleExpand = (task: Task) => {setExpandedTaskNames((prev) => {diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/useDeployTaskStatement.test.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/useDeployTaskStatement.test.tsxnew file mode 100644index 0000000000..087f95d1df--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/useDeployTaskStatement.test.tsx@@ -0,0 +1,75 @@+import { render, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, test, vi } from "vitest";+import type { Task } from "@/types/proto-es/v1/rollout_service_pb";+import { useDeployTaskStatement } from "./useDeployTaskStatement";++const getSheetByName = vi.fn();+const getOrFetchSheetByName = vi.fn();++vi.mock("@/react/stores/app", () => ({+ useAppStore: {+ getState: () => ({ getSheetByName, getOrFetchSheetByName }),+ },+}));+vi.mock("@/utils/sheet", () => ({+ getStatementSize: (statement: string) => statement.length,+}));+vi.mock("@/utils/v1/issue/rollout", () => ({+ sheetNameOfTaskV1: () => "projects/p1/sheets/1",+}));+vi.mock("@/utils/v1/sheet", () => ({+ getSheetStatement: (sheet: { statement: string }) => sheet.statement,+ extractSheetUID: (name: string) => name.split("/").pop() ?? "",+}));++const task = { name: "tasks/t1" } as unknown as Task;++type HookResult = ReturnType<typeof useDeployTaskStatement>;++const renderHookRecording = () => {+ const renders: HookResult[] = [];+ const Probe = () => {+ renders.push(useDeployTaskStatement({ enabled: true, task }));+ return null;+ };+ render(<Probe />);+ return renders;+};++describe("useDeployTaskStatement initial render (BYT-9763)", () => {+ beforeEach(() => {+ getSheetByName.mockReset();+ getOrFetchSheetByName.mockReset();+ });++ test("renders a cached statement on the first paint — no 'No data' flash", () => {+ getSheetByName.mockReturnValue({ statement: "select 1;", contentSize: 9 });++ const renders = renderHookRecording();++ // The very first render must already carry the statement, so the expanded+ // task never paints the empty "No data" branch.+ expect(renders[0].statement).toBe("select 1;");+ expect(renders[0].isLoading).toBe(false);+ });++ test("reports loading (not empty) on the first paint when the sheet must be fetched", async () => {+ getSheetByName.mockReturnValue(undefined);+ getOrFetchSheetByName.mockResolvedValue({+ statement: "select 2;",+ contentSize: 9,+ });++ const renders = renderHookRecording();++ // First paint: a fetch is pending, so show loading rather than "No data".+ expect(renders[0].isLoading).toBe(true);+ expect(renders[0].statement).toBe("");++ // After the fetch resolves the statement appears.+ await waitFor(() => {+ expect(renders.at(-1)?.statement).toBe("select 2;");+ expect(renders.at(-1)?.isLoading).toBe(false);+ });+ });+});diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/useDeployTaskStatement.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/useDeployTaskStatement.tsxindex f2702f9cb9..41e8fb4694 100644--- a/frontend/src/react/pages/project/plan-detail/components/deploy/useDeployTaskStatement.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/useDeployTaskStatement.tsx@@ -1,10 +1,12 @@-import { useEffect, useMemo, useState } from "react";-import { useAppStore } from "@/react/stores/app";+import { useMemo } from "react";+import { useSheetStatement } from "@/react/hooks/useSheetStatement";import type { Task } from "@/types/proto-es/v1/rollout_service_pb";-import { getStatementSize } from "@/utils/sheet";import { sheetNameOfTaskV1 } from "@/utils/v1/issue/rollout";-import { getSheetStatement } from "@/utils/v1/sheet";+// Rollout tasks always reference committed (remote) sheets, so this is just the+// shared sheet-statement loader keyed on the task's sheet — seeded from cache to+// avoid the first-paint "No data" flash when expanding a task or switching+// stages (BYT-9763).export const useDeployTaskStatement = ({enabled,task,@@ -13,44 +15,5 @@ export const useDeployTaskStatement = ({task: Task;}) => {const sheetName = useMemo(() => sheetNameOfTaskV1(task), [task]);- const [statement, setStatement] = useState("");- const [isLoading, setIsLoading] = useState(false);- const [isTruncated, setIsTruncated] = useState(false);-- useEffect(() => {- if (!enabled || !sheetName) {- setStatement("");- setIsTruncated(false);- setIsLoading(false);- return;- }-- let canceled = false;- const load = async () => {- setIsLoading(true);- try {- let sheet = useAppStore.getState().getSheetByName(sheetName);- if (!sheet) {- sheet = await useAppStore.getState().getOrFetchSheetByName(sheetName);- }- if (!sheet) {- return;- }- if (canceled) return;- const nextStatement = getSheetStatement(sheet);- setStatement(nextStatement);- setIsTruncated(getStatementSize(nextStatement) < sheet.contentSize);- } finally {- if (!canceled) {- setIsLoading(false);- }- }- };- void load();- return () => {- canceled = true;- };- }, [enabled, sheetName]);-- return { isLoading, isTruncated, statement };+ return useSheetStatement({ enabled, sheetName });};