Skip to content

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

feat(frontend): split Plans and Releases lists by change source (#21637)

boojack36190dc6167b
diff --git a/frontend/src/app/router/releaseDetailRedirect.test.ts b/frontend/src/app/router/releaseDetailRedirect.test.ts
new file mode 100644
index 0000000000..47373d8fc8
--- /dev/null
+++ b/frontend/src/app/router/releaseDetailRedirect.test.ts
@@ -0,0 +1,88 @@
+// @vitest-environment node
+import type { LoaderFunctionArgs } from "react-router";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ listPlans: vi.fn(),
+}));
+
+vi.mock("@/api", () => ({
+ planServiceClientConnect: { listPlans: mocks.listPlans },
+}));
+
+import { setAppRouter } from "./navigation";
+import { releaseDetailRedirectLoader } from "./releaseDetailRedirect";
+
+const RELEASES_URL =
+ "/projects/p1/releases?q=release%3Aprojects%252Fp1%252Freleases%252Fr1";
+
+const run = (): Promise<Response | null> =>
+ releaseDetailRedirectLoader({
+ params: { projectId: "p1", releaseId: "r1" },
+ request: new Request("http://localhost/projects/p1/releases/r1"),
+ } as unknown as LoaderFunctionArgs);
+
+beforeEach(() => {
+ mocks.listPlans.mockReset();
+ setAppRouter({
+ navigate: vi.fn(),
+ state: {
+ initialized: false,
+ location: { pathname: "/projects/p1/releases/r1", search: "", hash: "" },
+ matches: [],
+ },
+ });
+});
+
+describe("releaseDetailRedirectLoader", () => {
+ test("opens the rollout of the one active Plan that used the release", async () => {
+ mocks.listPlans.mockResolvedValue({
+ plans: [{ name: "projects/p1/plans/7", hasRollout: true }],
+ });
+
+ const response = await run();
+
+ expect(response?.headers.get("Location")).toBe(
+ "/projects/p1/plans/7/rollout"
+ );
+ expect(mocks.listPlans).toHaveBeenCalledWith(
+ expect.objectContaining({
+ parent: "projects/p1",
+ filter: 'release == "projects/p1/releases/r1" && state == "ACTIVE"',
+ pageSize: 2,
+ })
+ );
+ });
+
+ test("opens Plan Detail when that Plan has no rollout yet", async () => {
+ mocks.listPlans.mockResolvedValue({
+ plans: [{ name: "projects/p1/plans/7", hasRollout: false }],
+ });
+
+ const response = await run();
+
+ expect(response?.headers.get("Location")).toBe("/projects/p1/plans/7");
+ });
+
+ test.each([
+ { name: "no Plan", plans: [] },
+ {
+ name: "several Plans",
+ plans: [{ name: "projects/p1/plans/7" }, { name: "projects/p1/plans/8" }],
+ },
+ ])("lists the release's Plans when it has $name", async ({ plans }) => {
+ mocks.listPlans.mockResolvedValue({ plans });
+
+ const response = await run();
+
+ expect(response?.headers.get("Location")).toBe(RELEASES_URL);
+ });
+
+ test("lists the release's Plans when the lookup fails", async () => {
+ mocks.listPlans.mockRejectedValue(new Error("unavailable"));
+
+ const response = await run();
+
+ expect(response?.headers.get("Location")).toBe(RELEASES_URL);
+ });
+});
diff --git a/frontend/src/app/router/releaseDetailRedirect.ts b/frontend/src/app/router/releaseDetailRedirect.ts
new file mode 100644
index 0000000000..665d8eea3c
--- /dev/null
+++ b/frontend/src/app/router/releaseDetailRedirect.ts
@@ -0,0 +1,49 @@
+import { create } from "@bufbuild/protobuf";
+import type { LoaderFunctionArgs } from "react-router";
+import { planServiceClientConnect } from "@/api";
+import { canonicalRedirect } from "@/app/router/canonicalRedirect";
+import { projectNamePrefix } from "@/stores/modules/v1/common";
+import { ListPlansRequestSchema } from "@/types/proto-es/v1/plan_service_pb";
+import { buildSearchTextBySearchParams } from "@/utils/v1/advanced-search/common";
+import { celString } from "@/utils/v1/celLiteral";
+import { extractPlanUID } from "@/utils/v1/issue/plan";
+
+// The release detail page is retired: a Release is tracked through the Plan
+// that deployed it. Old links, including the CI summary bytebase-action
+// writes, open that Plan, or the Releases list filtered to the release when
+// zero or several active Plans reference it.
+export async function releaseDetailRedirectLoader({
+ params,
+}: LoaderFunctionArgs): Promise<Response | null> {
+ const { projectId, releaseId } = params;
+ if (!projectId || !releaseId) {
+ return null;
+ }
+ const projectName = `${projectNamePrefix}${projectId}`;
+ const releaseName = `${projectName}/releases/${releaseId}`;
+ try {
+ const { plans } = await planServiceClientConnect.listPlans(
+ create(ListPlansRequestSchema, {
+ parent: projectName,
+ filter: `release == ${celString(releaseName)} && state == "ACTIVE"`,
+ pageSize: 2,
+ })
+ );
+ if (plans.length === 1) {
+ const plan = plans[0];
+ const planPath = `/projects/${projectId}/plans/${extractPlanUID(plan.name)}`;
+ return canonicalRedirect(
+ plan.hasRollout ? `${planPath}/rollout` : planPath
+ );
+ }
+ } catch {
+ // Fall through to the filtered list, which reports its own errors.
+ }
+ const search = buildSearchTextBySearchParams({
+ query: "",
+ scopes: [{ id: "release", value: releaseName }],
+ });
+ return canonicalRedirect(
+ `/projects/${projectId}/releases?q=${encodeURIComponent(search)}`
+ );
+}
diff --git a/frontend/src/app/router/routes/dashboard.tsx b/frontend/src/app/router/routes/dashboard.tsx
index 6c35a6ddc5..e6f5a80b32 100644
--- a/frontend/src/app/router/routes/dashboard.tsx
+++ b/frontend/src/app/router/routes/dashboard.tsx
@@ -81,6 +81,7 @@ import { issueDetailRedirectLoader } from "@/app/router/issueDetailRedirect";
import { lazyPage } from "@/app/router/lazyPage";
import { ProjectRouteGate } from "@/app/router/ProjectRouteGate";
import { RouteGroupOutlet } from "@/app/router/RouteGroupOutlet";
+import { releaseDetailRedirectLoader } from "@/app/router/releaseDetailRedirect";
import type { Permission } from "@/types";
import { sqlReviewV2Enabled } from "@/utils/featureGates";
@@ -906,7 +907,7 @@ const projectV1Routes: RouteObject[] = [
index: true,
handle: {
name: PROJECT_V1_ROUTE_RELEASES,
- requiredPermissionList: (): Permission[] => ["bb.releases.list"],
+ requiredPermissionList: (): Permission[] => ["bb.plans.list"],
},
lazy: lazyPage(
() => import("@/routes/project/ProjectReleaseDashboardPage"),
@@ -917,12 +918,9 @@ const projectV1Routes: RouteObject[] = [
path: ":releaseId",
handle: {
name: PROJECT_V1_ROUTE_RELEASE_DETAIL,
- requiredPermissionList: (): Permission[] => ["bb.releases.get"],
+ requiredPermissionList: (): Permission[] => ["bb.plans.list"],
},
- lazy: lazyPage(
- () => import("@/routes/project/ProjectReleaseDetailPage"),
- (m) => m.ProjectReleaseDetailPage
- ),
+ loader: releaseDetailRedirectLoader,
},
],
},
diff --git a/frontend/src/components/ProjectSidebar.test.tsx b/frontend/src/components/ProjectSidebar.test.tsx
index 4e0b7f1939..ee6c5a498f 100644
--- a/frontend/src/components/ProjectSidebar.test.tsx
+++ b/frontend/src/components/ProjectSidebar.test.tsx
@@ -13,9 +13,12 @@ const mocks = vi.hoisted(() => ({
fullPath: "/projects/sample/masking-exemption",
params: {
projectId: "sample",
- },
+ } as Record<string, string>,
query: {},
},
+ viewedPlan: undefined as
+ | { name: string; isReleaseBacked: boolean }
+ | undefined,
defaultProject: "",
dev: true,
getOrFetchProjectByName: vi.fn(),
@@ -88,6 +91,7 @@ vi.mock("@/stores/app", () => {
selector: (state: {
getOrFetchProjectByName: typeof mocks.getOrFetchProjectByName;
serverInfo: { defaultProject: string };
+ viewedPlan: typeof mocks.viewedPlan;
}) => unknown
) =>
selector({
@@ -95,6 +99,7 @@ vi.mock("@/stores/app", () => {
serverInfo: {
defaultProject: mocks.defaultProject,
},
+ viewedPlan: mocks.viewedPlan,
});
useAppStore.getState = () => ({
getOrFetchProjectByName: mocks.getOrFetchProjectByName,
@@ -136,6 +141,7 @@ beforeEach(async () => {
};
mocks.defaultProject = "";
mocks.dev = true;
+ mocks.viewedPlan = undefined;
({ ProjectSidebar } = await import("./ProjectSidebar"));
});
@@ -241,4 +247,92 @@ describe("ProjectSidebar", () => {
unmount();
});
+
+ describe("CI/CD entries", () => {
+ const activeLabels = (container: HTMLElement) =>
+ Array.from(container.querySelectorAll("a"))
+ .filter((link) => link.className.includes("router-link-active"))
+ .map((link) => link.textContent?.trim());
+
+ const renderAt = (name: string, params: Record<string, string> = {}) => {
+ mocks.currentRoute.name = name;
+ mocks.currentRoute.params = { projectId: "sample", ...params };
+ const view = renderIntoContainer(<ProjectSidebar />);
+ view.render();
+ return view;
+ };
+
+ test("lists Plans and Releases without a GitOps entry", () => {
+ const { container, unmount } = renderAt("workspace.project.plan");
+
+ const labels = Array.from(container.querySelectorAll("a")).map((link) =>
+ link.textContent?.trim()
+ );
+ expect(labels).toEqual(expect.arrayContaining(["Plans", "Releases"]));
+ expect(labels).not.toContain("GitOps");
+
+ unmount();
+ });
+
+ test("highlights Releases on the GitOps setup page", () => {
+ const { container, unmount } = renderAt("workspace.project.gitops");
+
+ expect(activeLabels(container)).toEqual(["Releases"]);
+
+ unmount();
+ });
+
+ test("highlights Releases on a GitOps Plan's detail page", () => {
+ mocks.viewedPlan = {
+ name: "projects/sample/plans/7",
+ isReleaseBacked: true,
+ };
+ const { container, unmount } = renderAt(
+ "workspace.project.plan.detail.rollout",
+ { planId: "7" }
+ );
+
+ expect(activeLabels(container)).toEqual(["Releases"]);
+
+ unmount();
+ });
+
+ test("highlights Plans on a ClickOps Plan's detail page", () => {
+ mocks.viewedPlan = {
+ name: "projects/sample/plans/7",
+ isReleaseBacked: false,
+ };
+ const { container, unmount } = renderAt("workspace.project.plan.detail", {
+ planId: "7",
+ });
+
+ expect(activeLabels(container)).toEqual(["Plans"]);
+
+ unmount();
+ });
+
+ test("ignores a GitOps Plan viewed before the current one", () => {
+ mocks.viewedPlan = {
+ name: "projects/sample/plans/6",
+ isReleaseBacked: true,
+ };
+ const { container, unmount } = renderAt("workspace.project.plan.detail", {
+ planId: "7",
+ });
+
+ expect(activeLabels(container)).toEqual(["Plans"]);
+
+ unmount();
+ });
+
+ test("hides CI/CD for the default project", () => {
+ mocks.defaultProject = "projects/sample";
+ const { container, unmount } = renderAt("workspace.project.detail");
+
+ expect(container.textContent).not.toContain("Plans");
+ expect(container.textContent).not.toContain("Releases");
+
+ unmount();
+ });
+ });
});
diff --git a/frontend/src/components/ProjectSidebar.tsx b/frontend/src/components/ProjectSidebar.tsx
index cab2842ffb..db56a3505a 100644
--- a/frontend/src/components/ProjectSidebar.tsx
+++ b/frontend/src/components/ProjectSidebar.tsx
@@ -24,6 +24,7 @@ import {
PROJECT_V1_ROUTE_ISSUES,
PROJECT_V1_ROUTE_MASKING_EXEMPTION,
PROJECT_V1_ROUTE_MEMBERS,
+ PROJECT_V1_ROUTE_PLAN_DETAIL,
PROJECT_V1_ROUTE_PLANS,
PROJECT_V1_ROUTE_RELEASES,
PROJECT_V1_ROUTE_SERVICE_ACCOUNTS,
@@ -51,16 +52,28 @@ interface SidebarItem {
type: "div";
expand?: boolean;
children?: SidebarItem[];
+ // Routes outside `path` that also highlight this item, and routes under
+ // `path` that do not.
+ activeRoutes?: string[];
+ inactiveRoutes?: string[];
}
// ---------------------------------------------------------------------------
// Active-route detection
// ---------------------------------------------------------------------------
+const matchesRoute = (route: string | undefined, currentRouteName: string) =>
+ !!route &&
+ (route === currentRouteName || currentRouteName.startsWith(`${route}.`));
+
function getItemClass(item: SidebarItem, currentRouteName: string): string[] {
const isActive =
- item.path === currentRouteName ||
- currentRouteName.startsWith(`${item.path}.`);
+ !item.inactiveRoutes?.some((route) =>
+ matchesRoute(route, currentRouteName)
+ ) &&
+ [item.path, ...(item.activeRoutes ?? [])].some((route) =>
+ matchesRoute(route, currentRouteName)
+ );
if (isActive) {
return ["router-link-active", "bg-link-hover"];
}
@@ -82,6 +95,14 @@ function useSidebarItems(): SidebarItem[] {
? `${projectNamePrefix}${sidebarProjectId}`
: "";
const isDefault = !!defaultProject && sidebarProjectName === defaultProject;
+ // Plan Detail serves both kinds of Plan; a GitOps Plan belongs to Releases.
+ const sidebarPlanId = sidebarRoute.params.planId as string | undefined;
+ const isGitOpsPlanDetail = useAppStore(
+ (s) =>
+ !!sidebarPlanId &&
+ s.viewedPlan?.name === `${sidebarProjectName}/plans/${sidebarPlanId}` &&
+ s.viewedPlan.isReleaseBacked
+ );
return useMemo(
(): SidebarItem[] => [
@@ -109,16 +130,17 @@ function useSidebarItems(): SidebarItem[] {
title: t("plan.plans"),
path: PROJECT_V1_ROUTE_PLANS,
type: "div",
+ inactiveRoutes: isGitOpsPlanDetail
+ ? [PROJECT_V1_ROUTE_PLAN_DETAIL]
+ : undefined,
},
{
title: t("release.releases"),
path: PROJECT_V1_ROUTE_RELEASES,
type: "div",
- },
- {
- title: t("gitops.self"),
- path: PROJECT_V1_ROUTE_GITOPS,
- type: "div",
+ activeRoutes: isGitOpsPlanDetail
+ ? [PROJECT_V1_ROUTE_GITOPS, PROJECT_V1_ROUTE_PLAN_DETAIL]
+ : [PROJECT_V1_ROUTE_GITOPS],
},
{
title: t("sql-review.title"),
@@ -218,7 +240,7 @@ function useSidebarItems(): SidebarItem[] {
hide: isDefault,
},
],
- [t, isDefault]
+ [t, isDefault, isGitOpsPlanDetail]
);
}
diff --git a/frontend/src/components/release/ReleaseFileDetailPanel.tsx b/frontend/src/components/release/ReleaseFileDetailPanel.tsx
deleted file mode 100644
index 3442433997..0000000000
--- a/frontend/src/components/release/ReleaseFileDetailPanel.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-import { Loader2 } from "lucide-react";
-import { useEffect, useState } from "react";
-import { useTranslation } from "react-i18next";
-import { sheetServiceClientConnect } from "@/api";
-import { ReadonlyMonaco } from "@/components/monaco/ReadonlyMonaco";
-import { CopyButton } from "@/components/ui/copy-button";
-import { Separator } from "@/components/ui/separator";
-import type { Release_File } from "@/types/proto-es/v1/release_service_pb";
-
-export interface ReleaseFileDetailPanelProps {
- releaseFile: Release_File;
-}
-
-export function ReleaseFileDetailPanel({
- releaseFile,
-}: ReleaseFileDetailPanelProps) {
- const { t } = useTranslation();
- const [statement, setStatement] = useState("");
- const [loading, setLoading] = useState(false);
-
- useEffect(() => {
- let cancelled = false;
- setLoading(true);
- setStatement("");
- sheetServiceClientConnect
- .getSheet({ name: releaseFile.sheet, raw: true })
- .then((sheet) => {
- if (!cancelled && sheet?.content) {
- setStatement(new TextDecoder().decode(sheet.content));
- }
- })
- .catch((error) => {
- console.error("Failed to fetch statement", error);
- })
- .finally(() => {
- if (!cancelled) setLoading(false);
- });
- return () => {
- cancelled = true;
- };
- }, [releaseFile]);
-
- return (
- <div className="flex flex-col gap-y-4">
- <div className="w-full">
- <div className="flex flex-row items-center gap-2">
- <p className="text-lg flex gap-x-1">
- <span className="text-control">{t("common.version")}:</span>
- <span className="font-bold text-main">{releaseFile.version}</span>
- </p>
- </div>
- <p className="mt-3 text-control text-sm flex gap-x-4">
- {releaseFile.path && (
- <span>
- {t("database.revision.filename")}: {releaseFile.path}
- </span>
- )}
- <span>Hash: {releaseFile.sheetSha256.slice(0, 8)}</span>
- </p>
- </div>
-
- <Separator />
-
- <div className="flex flex-col gap-y-2">
- <p className="w-auto flex items-center text-base text-main mb-2 gap-x-2">
- {t("common.statement")}
- <CopyButton content={statement} />
- </p>
- {loading ? (
- <div className="flex items-center justify-center py-8 text-control-light">
- <Loader2 className="size-5 animate-spin" />
- </div>
- ) : (
- <ReadonlyMonaco
- content={statement}
- max={480}
- className="border border-control-border rounded-xs text-sm overflow-clip relative"
- />
- )}
- </div>
- </div>
- );
-}
diff --git a/frontend/src/components/release/ReleaseInfoCard.test.tsx b/frontend/src/components/release/ReleaseInfoCard.test.tsx
index aa00a02be7..16d66cfc63 100644
--- a/frontend/src/components/release/ReleaseInfoCard.test.tsx
+++ b/frontend/src/components/release/ReleaseInfoCard.test.tsx
@@ -87,6 +87,26 @@ describe("ReleaseInfoCard", () => {
unmount();
});
+ test("expands to every file in place", async () => {
+ ({ ReleaseInfoCard } = await import("./ReleaseInfoCard"));
+ const { container, unmount } = renderIntoContainer(
+ createElement(ReleaseInfoCard, {
+ release: buildRelease(6),
+ releaseName: "projects/p/releases/r1",
+ })
+ );
+
+ const viewAll = Array.from(container.querySelectorAll("button")).find(
+ (button) => button.textContent === "release.view-all-files"
+ );
+ act(() => viewAll?.click());
+
+ expect(container.textContent).toContain("V0006.sql");
+ expect(container.textContent).not.toContain("release.and-n-more-files");
+ expect(container.querySelector("a")).toBeNull();
+ unmount();
+ });
+
test("renders the loading state when isLoading is true", async () => {
({ ReleaseInfoCard } = await import("./ReleaseInfoCard"));
const { container, unmount } = renderIntoContainer(
diff --git a/frontend/src/components/release/ReleaseInfoCard.tsx b/frontend/src/components/release/ReleaseInfoCard.tsx
index 276e4d6844..512744d3fb 100644
--- a/frontend/src/components/release/ReleaseInfoCard.tsx
+++ b/frontend/src/components/release/ReleaseInfoCard.tsx
@@ -1,10 +1,10 @@
import type { TFunction } from "i18next";
-import { ExternalLink, Loader2, Package } from "lucide-react";
+import { Loader2, Package } from "lucide-react";
import type { ReactNode } from "react";
-import { useMemo } from "react";
+import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { HumanizeTs } from "@/components/HumanizeTs";
-import { RouterLink } from "@/components/RouterLink";
+import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { getTimeForPbTimestampProtoEs } from "@/types";
import { State, VCSType } from "@/types/proto-es/v1/common_pb";
@@ -25,7 +25,6 @@ export function ReleaseInfoCard({
release?: Release;
releaseName: string;
}>) {
- const { t } = useTranslation();
// Treat the release as missing when it's absent or its name doesn't parse
// as a real release resource name.
const effectiveRelease =
@@ -55,17 +54,6 @@ export function ReleaseInfoCard({
{releaseTitle}
</span>
</div>
- {effectiveRelease && (
- <RouterLink
- to={`/${effectiveRelease.name}`}
- className="inline-flex items-center gap-x-1 text-sm text-accent hover:underline"
- rel="noreferrer"
- target="_blank"
- >
- <span>{t("common.view")}</span>
- <ExternalLink className="h-4 w-4" />
- </RouterLink>
- )}
</div>
{body}
</div>
@@ -95,7 +83,12 @@ function NotFoundBlock() {
function ReleaseBlock({ release }: Readonly<{ release: Release }>) {
const { t } = useTranslation();
- const displayedFiles = release.files.slice(0, MAX_DISPLAYED_RELEASE_FILES);
+ const [showAllFiles, setShowAllFiles] = useState(false);
+ const isTruncated =
+ !showAllFiles && release.files.length > MAX_DISPLAYED_RELEASE_FILES;
+ const displayedFiles = isTruncated
+ ? release.files.slice(0, MAX_DISPLAYED_RELEASE_FILES)
+ : release.files;
return (
<div className="rounded-sm border border-control-border bg-control-bg/50 px-4 py-3">
@@ -106,15 +99,16 @@ function ReleaseBlock({ release }: Readonly<{ release: Release }>) {
<div className="text-sm font-medium text-control">
{t("release.files")} ({release.files.length})
</div>
- {release.files.length > MAX_DISPLAYED_RELEASE_FILES && (
- <RouterLink
- to={`/${release.name}`}
- className="text-sm text-accent hover:underline"
- rel="noreferrer"
- target="_blank"
+ {isTruncated && (
+ <Button
+ type="button"
+ appearance="link"
+ size="sm"
+ className="h-auto p-0 text-accent"
+ onClick={() => setShowAllFiles(true)}
>
{t("release.view-all-files")}
- </RouterLink>
+ </Button>
)}
</div>
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2 md:grid-cols-3">
@@ -132,7 +126,7 @@ function ReleaseBlock({ release }: Readonly<{ release: Release }>) {
</div>
</div>
))}
- {release.files.length > MAX_DISPLAYED_RELEASE_FILES && (
+ {isTruncated && (
<div className="flex items-center justify-center rounded-sm border border-dashed border-control-border bg-background p-2 text-xs text-control-light">
{t("release.and-n-more-files", {
count: release.files.length - MAX_DISPLAYED_RELEASE_FILES,
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 4af1f9f788..fd583de59a 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1007,6 +1007,7 @@
"password-optional": "Encrypt with password (Optional)"
},
"gitops": {
+ "back-to-releases": "Back to Releases",
"checklist": {
"database-group-recommendation": "For databases sharing the same schema, a database group lets you migrate them together in one change. Define the group once and reuse it across migrations without picking individual databases every time.",
"external-url": "External URL",
@@ -1022,7 +1023,6 @@
"description-git": "Your database schema lives in Git alongside your application code. Pull requests trigger SQL review, and merging to the target branch automatically creates rollouts.",
"title": "What is GitOps"
},
- "self": "GitOps",
"test-setup": {
"description": "Verify the workflow is working end-to-end with a sample migration file.",
"naming-convention": "Migration files are applied in lexicographic order. Use a timestamp or sequence prefix, e.g. 20240101000000_create_table.sql. Append _ddl or _dml to indicate the change type.",
@@ -1927,6 +1927,7 @@
"review-waiting": "Waiting for {{role}}",
"run": "Run"
},
+ "list-description": "Change requests created in the UI and their deploy progress.",
"meta": {
"created-by": "Created by {{user}}"
},
@@ -2114,8 +2115,11 @@
"affected-rows_one": "~{{count}} row affected",
"affected-rows_other": "~{{count}} rows affected"
},
+ "status-scope": {
+ "description": "Filter by the current status of the plan's tasks",
+ "waiting": "Waiting"
+ },
"submit-review-anyway": "Submit anyway",
- "subtitle": "Draft database changes and run pre-checks before creating an issue for approval.",
"summary": {
"approved-by": "Approved by {{names}}",
"last-approved-by": "Last approved by {{name}}",
@@ -2465,17 +2469,24 @@
"release": {
"and-n-more-files": "and {{count}} more files",
"change-tip": "This change is linked to a release artifact.",
- "file": "Release File",
+ "empty": {
+ "description": "Changes your CI pipeline releases to Bytebase appear here with their deploy progress.",
+ "read-guide": "Read the GitOps guide",
+ "set-up": "Set up GitOps",
+ "title": "No GitOps changes yet"
+ },
"file-type": {
"declarative": "Declarative",
"unspecified": "Unspecified",
"versioned": "Versioned"
},
"files": "Files",
+ "gitops-setup": "GitOps setup",
+ "list-description": "Changes released through GitOps and their deploy progress.",
"not-found": "Release not found",
"releases": "Releases",
- "total-files": "Total {{}} files",
- "usage-description": "A release is a versioned application artifact whose deployment to an environment is triggered by a GitOps workflow.",
+ "self": "Release",
+ "source": "Source",
"vcs-source": "VCS Source",
"vcs-type": {
"unspecified": "Unknown VCS"
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index d6595793fe..14b58c40cf 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1007,6 +1007,7 @@
"password-optional": "Cifrar con contraseña (opcional)"
},
"gitops": {
+ "back-to-releases": "Volver a Lanzamientos",
"checklist": {
"database-group-recommendation": "Para bases de datos con el mismo esquema, un grupo de bases de datos permite migrarlas juntas en un solo cambio. Defina el grupo una vez y reutilícelo en las migraciones sin tener que seleccionar bases de datos individuales cada vez.",
"external-url": "URL externa",
@@ -1022,7 +1023,6 @@
"description-git": "El esquema de su base de datos se almacena en Git junto con el código de su aplicación. Las pull requests activan la revisión de SQL, y la fusión en la rama de destino crea automáticamente los despliegues.",
"title": "Qué es GitOps"
},
- "self": "GitOps",
"test-setup": {
"description": "Verifique que el flujo de trabajo funciona de extremo a extremo con un archivo de migración de ejemplo.",
"naming-convention": "Los archivos de migración se aplican en orden lexicográfico. Use un prefijo de marca de tiempo o secuencia, p. ej. 20240101000000_create_table.sql. Agregue _ddl o _dml para indicar el tipo de cambio.",
@@ -1927,6 +1927,7 @@
"review-waiting": "Esperando a {{role}}",
"run": "Ejecutar"
},
+ "list-description": "Solicitudes de cambio creadas en la interfaz y su progreso de despliegue.",
"meta": {
"created-by": "Creado por {{user}}"
},
@@ -2114,8 +2115,11 @@
"affected-rows_one": "~{{count}} fila afectada",
"affected-rows_other": "~{{count}} filas afectadas"
},
+ "status-scope": {
+ "description": "Filtrar por el estado actual de las tareas del plan",
+ "waiting": "En espera"
+ },
"submit-review-anyway": "Enviar de todos modos",
- "subtitle": "Redactar cambios en la base de datos y ejecutar comprobaciones previas antes de crear un problema para su aprobación.",
"summary": {
"approved-by": "Aprobado por {{names}}",
"last-approved-by": "Última aprobación por {{name}}",
@@ -2465,17 +2469,24 @@
"release": {
"and-n-more-files": "y {{count}} archivos más",
"change-tip": "Este cambio está vinculado a un artefacto de versión.",
- "file": "Archivo de lanzamiento",
+ "empty": {
+ "description": "Los cambios que tu pipeline de CI publica en Bytebase aparecen aquí con su progreso de despliegue.",
+ "read-guide": "Leer la guía de GitOps",
+ "set-up": "Configurar GitOps",
+ "title": "Aún no hay cambios de GitOps"
+ },
"file-type": {
"declarative": "Declarativo",
"unspecified": "Sin especificar",
"versioned": "Versionado"
},
"files": "Archivos",
+ "gitops-setup": "Configuración de GitOps",
+ "list-description": "Cambios publicados mediante GitOps y su progreso de despliegue.",
"not-found": "Versión no encontrada",
"releases": "Lanzamientos",
- "total-files": "Total de {{}} 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.",
+ "self": "Lanzamiento",
+ "source": "Origen",
"vcs-source": "Origen de VCS",
"vcs-type": {
"unspecified": "VCS desconocido"
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 55ba0f0af9..0ed229acd8 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -1007,6 +1007,7 @@
"password-optional": "パスワード暗号化の設定 (オプション)"
},
"gitops": {
+ "back-to-releases": "リリースに戻る",
"checklist": {
"database-group-recommendation": "同じスキーマを持つデータベースには、データベースグループを使用すると一度の変更でまとめてマイグレーションできます。グループを一度定義すれば、毎回個別にデータベースを選択することなく、マイグレーション全体で再利用できます。",
"external-url": "外部URL",
@@ -1022,7 +1023,6 @@
"description-git": "データベーススキーマはアプリケーションコードと一緒に Git で管理されます。プルリクエストで SQL レビューがトリガーされ、ターゲットブランチへのマージで自動的にロールアウトが作成されます。",
"title": "GitOps とは"
},
- "self": "GitOps",
"test-setup": {
"description": "サンプルマイグレーションファイルでワークフロー全体が正常に動作するか確認します。",
"naming-convention": "マイグレーションファイルは辞書順に適用されます。タイムスタンプまたはシーケンス番号のプレフィックスを使用してください(例: 20240101000000_create_table.sql)。変更タイプを示すために _ddl または _dml を末尾に追加してください。",
@@ -1927,6 +1927,7 @@
"review-waiting": "{{role}} の承認待ち",
"run": "実行"
},
+ "list-description": "UI で作成された変更リクエストとそのデプロイ進捗。",
"meta": {
"created-by": "{{user}} が作成"
},
@@ -2114,8 +2115,11 @@
"affected-rows_one": "約 {{count}} 行に影響",
"affected-rows_other": "約 {{count}} 行に影響"
},
+ "status-scope": {
+ "description": "プラン内のタスクの現在のステータスで絞り込みます",
+ "waiting": "待機中"
+ },
"submit-review-anyway": "それでも提出する",
- "subtitle": "承認のためにイシューを作成する前に、データベースの変更を下書きし、事前チェックを実行します。",
"summary": {
"approved-by": "{{names}} が承認",
"last-approved-by": "{{name}} が最後に承認",
@@ -2465,17 +2469,24 @@
"release": {
"and-n-more-files": "他 {{count}} 件のファイル",
"change-tip": "この変更はリリースアーティファクトにリンクされています。",
- "file": "リリースファイル",
+ "empty": {
+ "description": "CI パイプラインが Bytebase にリリースした変更が、デプロイ進捗とともにここに表示されます。",
+ "read-guide": "GitOps ガイドを読む",
+ "set-up": "GitOps を設定",
+ "title": "GitOps の変更はまだありません"
+ },
"file-type": {
"declarative": "宣言的",
"unspecified": "未指定",
"versioned": "バージョン管理"
},
"files": "ファイル",
+ "gitops-setup": "GitOps 設定",
+ "list-description": "GitOps でリリースされた変更とそのデプロイ進捗。",
"not-found": "リリースが見つかりません",
"releases": "リリース",
- "total-files": "合計 {{}} ファイル",
- "usage-description": "リリースは、GitOpsワークフローによって環境へのデプロイがトリガーされるバージョン管理されたアプリケーションアーティファクトです。",
+ "self": "リリース",
+ "source": "ソース",
"vcs-source": "VCS ソース",
"vcs-type": {
"unspecified": "不明な VCS"
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index e9e47659bd..84e9a272c6 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -1007,6 +1007,7 @@
"password-optional": "Mã hóa bằng mật khẩu (Tùy chọn)"
},
"gitops": {
+ "back-to-releases": "Quay lại Bản phát hành",
"checklist": {
"database-group-recommendation": "Đối với các cơ sở dữ liệu có cùng schema, nhóm cơ sở dữ liệu cho phép bạn migration tất cả cùng lúc trong một thay đổi. Chỉ cần định nghĩa nhóm một lần và tái sử dụng trong các lần migration mà không cần chọn từng cơ sở dữ liệu mỗi lần.",
"external-url": "URL bên ngoài",
@@ -1022,7 +1023,6 @@
"description-git": "Schema cơ sở dữ liệu của bạn được lưu trữ trong Git cùng với mã nguồn ứng dụng. Pull request sẽ kích hoạt SQL review, và việc merge vào nhánh đích sẽ tự động tạo rollout.",
"title": "GitOps là gì"
},
- "self": "GitOps",
"test-setup": {
"description": "Xác minh workflow hoạt động đầy đủ với một tệp migration mẫu.",
"naming-convention": "Các tệp migration được áp dụng theo thứ tự từ điển. Sử dụng tiền tố timestamp hoặc số thứ tự, ví dụ: 20240101000000_create_table.sql. Thêm _ddl hoặc _dml để chỉ loại thay đổi.",
@@ -1927,6 +1927,7 @@
"review-waiting": "Đang chờ {{role}}",
"run": "Chạy"
},
+ "list-description": "Các yêu cầu thay đổi được tạo trong giao diện và tiến độ triển khai của chúng.",
"meta": {
"created-by": "Tạo bởi {{user}}"
},
@@ -2114,8 +2115,11 @@
"affected-rows_one": "~{{count}} dòng bị ảnh hưởng",
"affected-rows_other": "~{{count}} dòng bị ảnh hưởng"
},
+ "status-scope": {
+ "description": "Lọc theo trạng thái hiện tại của các tác vụ trong kế hoạch",
+ "waiting": "Đang chờ"
+ },
"submit-review-anyway": "Vẫn gửi",
- "subtitle": "Soạn thảo các thay đổi cơ sở dữ liệu và chạy các bước kiểm tra sơ bộ trước khi tạo vấn đề để phê duyệt.",
"summary": {
"approved-by": "Được phê duyệt bởi {{names}}",
"last-approved-by": "Phê duyệt gần nhất bởi {{name}}",
@@ -2465,17 +2469,24 @@
"release": {
"and-n-more-files": "và {{count}} tệp khác",
"change-tip": "Thay đổi này được liên kết với một artifact phát hành.",
- "file": "Tệp phát hành",
+ "empty": {
+ "description": "Các thay đổi mà pipeline CI của bạn phát hành lên Bytebase sẽ hiển thị ở đây cùng tiến độ triển khai.",
+ "read-guide": "Đọc hướng dẫn GitOps",
+ "set-up": "Thiết lập GitOps",
+ "title": "Chưa có thay đổi GitOps nào"
+ },
"file-type": {
"declarative": "Khai báo",
"unspecified": "Không xác định",
"versioned": "Có phiên bản"
},
"files": "Tệp",
+ "gitops-setup": "Thiết lập GitOps",
+ "list-description": "Các thay đổi được phát hành qua GitOps và tiến độ triển khai của chúng.",
"not-found": "Không tìm thấy bản phát hành",
"releases": "Bản phát hành",
- "total-files": "Tổng số {{}} 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.",
+ "self": "Bản phát hành",
+ "source": "Nguồn",
"vcs-source": "Nguồn VCS",
"vcs-type": {
"unspecified": "VCS không xác định"
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 7d42c68419..52e59f6275 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1007,6 +1007,7 @@
"password-optional": "设置密码加密(可选)"
},
"gitops": {
+ "back-to-releases": "返回发布包",
"checklist": {
"database-group-recommendation": "对于具有相同 Schema 的数据库,数据库分组可以让您在一次变更中同时迁移它们。只需定义一次分组,即可在多次迁移中复用,无需每次都逐个选择数据库。",
"external-url": "外部访问地址",
@@ -1022,7 +1023,6 @@
"description-git": "数据库架构与应用代码一起存储在 Git 中。拉取请求会触发 SQL 审查,合并到目标分支后会自动创建变更发布。",
"title": "什么是 GitOps"
},
- "self": "GitOps",
"test-setup": {
"description": "使用示例迁移文件验证整个工作流是否正常运行。",
"naming-convention": "迁移文件按字典顺序执行。请使用时间戳或序号前缀,例如 20240101000000_create_table.sql。在文件名末尾添加 _ddl 或 _dml 来标识变更类型。",
@@ -1927,6 +1927,7 @@
"review-waiting": "等待 {{role}}",
"run": "执行"
},
+ "list-description": "在界面中创建的变更请求及其部署进度。",
"meta": {
"created-by": "由 {{user}} 创建"
},
@@ -2114,8 +2115,11 @@
"affected-rows_one": "约影响 {{count}} 行",
"affected-rows_other": "约影响 {{count}} 行"
},
+ "status-scope": {
+ "description": "按计划中任务的当前状态筛选",
+ "waiting": "等待中"
+ },
"submit-review-anyway": "仍然提交",
- "subtitle": "草拟数据库变更并运行预检查,然后创建工单以请求审批。",
"summary": {
"approved-by": "已由 {{names}} 批准",
"last-approved-by": "最后由 {{name}} 审批",
@@ -2465,17 +2469,24 @@
"release": {
"and-n-more-files": "以及另外 {{count}} 个文件",
"change-tip": "该变更关联到了一个发布包。",
- "file": "发布包文件",
+ "empty": {
+ "description": "CI 流水线发布到 Bytebase 的变更会连同部署进度显示在这里。",
+ "read-guide": "阅读 GitOps 指南",
+ "set-up": "设置 GitOps",
+ "title": "暂无 GitOps 变更"
+ },
"file-type": {
"declarative": "声明式",
"unspecified": "未指定",
"versioned": "版本化"
},
"files": "文件",
+ "gitops-setup": "GitOps 设置",
+ "list-description": "通过 GitOps 发布的变更及其部署进度。",
"not-found": "未找到发布包",
"releases": "发布包",
- "total-files": "共 {{}} 个文件",
- "usage-description": "发布包是版本化的应用制品。GitOps 工作流将发布包部署到环境。",
+ "self": "发布包",
+ "source": "来源",
"vcs-source": "VCS 来源",
"vcs-type": {
"unspecified": "未知 VCS"
diff --git a/frontend/src/routes/project/PlanTable.test.tsx b/frontend/src/routes/project/PlanTable.test.tsx
new file mode 100644
index 0000000000..ab9ef2703b
--- /dev/null
+++ b/frontend/src/routes/project/PlanTable.test.tsx
@@ -0,0 +1,238 @@
+import type { TFunction } from "i18next";
+import { act, createElement, type ReactNode } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { ApprovalStatus, State } from "@/types/proto-es/v1/common_pb";
+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
+import {
+ createPlanStagesColumn,
+ type PlanColumn,
+ PlanLifecycleBadges,
+ PlanTable,
+} from "./PlanTable";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ routerPush: vi.fn(),
+ getEnvironmentByName: vi.fn(),
+}));
+
+vi.mock("react-i18next", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("react-i18next")>()),
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/app/router", () => ({
+ router: {
+ push: mocks.routerPush,
+ resolve: ({ params }: { params: Record<string, string> }) => ({
+ fullPath: `/projects/${params.projectId}/plans/${params.planId}`,
+ }),
+ },
+}));
+
+vi.mock("@/components/TaskStatusIcon", () => ({
+ TaskStatusIcon: () => null,
+}));
+
+vi.mock("@/components/ui/table", () => ({
+ Table: ({ children }: { children: ReactNode }) =>
+ createElement("table", {}, children),
+ TableBody: ({ children }: { children: ReactNode }) =>
+ createElement("tbody", {}, children),
+ TableCell: ({ children }: { children?: ReactNode }) =>
+ createElement("td", {}, children),
+ TableHead: ({ children }: { children?: ReactNode }) =>
+ createElement("th", {}, children),
+ TableHeader: ({ children }: { children: ReactNode }) =>
+ createElement("thead", {}, children),
+ TableRow: ({ children, ...props }: { children?: ReactNode }) =>
+ createElement("tr", props, children),
+}));
+
+vi.mock("@/hooks/useColumnWidths", () => ({
+ useColumnWidths: (columns: { defaultWidth: number }[]) => ({
+ widths: columns.map((column) => column.defaultWidth),
+ totalWidth: columns.reduce((sum, column) => sum + column.defaultWidth, 0),
+ onResizeStart: vi.fn(),
+ setWidths: vi.fn(),
+ }),
+}));
+
+vi.mock("@/stores/app", () => {
+ const state = {
+ environmentList: [],
+ getEnvironmentByName: mocks.getEnvironmentByName,
+ getUserByIdentifier: () => undefined,
+ };
+ return {
+ useAppStore: (selector: (s: typeof state) => unknown) => selector(state),
+ };
+});
+
+const basePlan = {
+ name: "projects/foo/plans/7",
+ title: "Plan 7",
+ state: State.ACTIVE,
+ creator: "users/[email protected]",
+ issue: "",
+ hasRollout: true,
+ approvalStatus: ApprovalStatus.APPROVAL_STATUS_UNSPECIFIED,
+ specs: [],
+ rolloutStageSummaries: [],
+} as unknown as Plan;
+
+const titleColumn: PlanColumn = {
+ key: "title",
+ title: "Title",
+ defaultWidth: 200,
+ render: (plan, ctx) => (
+ <span>
+ {plan.title}
+ <PlanLifecycleBadges ctx={ctx} />
+ </span>
+ ),
+};
+
+describe("PlanTable", () => {
+ let container: HTMLDivElement;
+ let root: Root;
+
+ const render = (plans: Plan[], props: Partial<Parameters<typeof PlanTable>[0]> = {}) => {
+ act(() => {
+ root.render(
+ <PlanTable
+ plans={plans}
+ projectId="foo"
+ columns={[titleColumn, createPlanStagesColumn(((key: string) => key) as unknown as TFunction)]}
+ isMobile={false}
+ onOpenPlan={vi.fn()}
+ {...props}
+ />
+ );
+ });
+ };
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ vi.clearAllMocks();
+ });
+
+ test("renders the given columns", () => {
+ render([basePlan]);
+
+ expect(
+ Array.from(container.querySelectorAll("th")).map((th) => th.textContent)
+ ).toEqual(["Title", "rollout.stage.self"]);
+ });
+
+ test("renders a stage chain with environment titles", () => {
+ mocks.getEnvironmentByName.mockImplementation((name: string) =>
+ name === "environments/prod" ? { title: "Production" } : undefined
+ );
+ render([
+ {
+ ...basePlan,
+ rolloutStageSummaries: [
+ { stage: "projects/foo/plans/7/rollout/stages/test", taskStatusCounts: [] },
+ { stage: "projects/foo/plans/7/rollout/stages/prod", taskStatusCounts: [] },
+ ],
+ } as unknown as Plan,
+ ]);
+
+ const stages = container.querySelectorAll("td")[1].textContent;
+ expect(stages).toContain("environments/test");
+ expect(stages).toContain("Production");
+ });
+
+ test("shows - for a Plan without rollout stages", () => {
+ render([basePlan]);
+
+ expect(container.querySelectorAll("td")[1].textContent).toBe("-");
+ });
+
+ test("opens the URL the caller resolves, in a new tab on ctrl-click", () => {
+ const open = vi.spyOn(window, "open").mockReturnValue(null);
+ const onOpenPlan = vi.fn();
+ render([basePlan], {
+ onOpenPlan,
+ resolvePlanUrl: (plan) => `/${plan.name}/rollout`,
+ });
+ const row = container.querySelector<HTMLElement>(
+ '[data-testid="plan-list-item"]'
+ );
+
+ act(() => row?.click());
+ expect(onOpenPlan).toHaveBeenCalledOnce();
+ expect(mocks.routerPush).toHaveBeenCalledWith("/projects/foo/plans/7/rollout");
+
+ act(() => {
+ row?.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, ctrlKey: true })
+ );
+ });
+ expect(open).toHaveBeenCalledWith("/projects/foo/plans/7/rollout", "_blank");
+ expect(mocks.routerPush).toHaveBeenCalledOnce();
+ open.mockRestore();
+ });
+
+ test("defaults to Plan Detail", () => {
+ render([basePlan]);
+
+ act(() =>
+ container
+ .querySelector<HTMLElement>('[data-testid="plan-list-item"]')
+ ?.click()
+ );
+
+ expect(mocks.routerPush).toHaveBeenCalledWith("/projects/foo/plans/7");
+ });
+
+ test.each([
+ {
+ name: "a closed Plan as Closed",
+ plan: { state: State.DELETED },
+ expected: "common.closed",
+ },
+ {
+ name: "a ClickOps Plan without an issue or rollout as Incomplete",
+ plan: { hasRollout: false },
+ expected: "plan.lifecycle.incomplete",
+ },
+ ])("badges $name", ({ plan, expected }) => {
+ render([{ ...basePlan, ...plan } as Plan]);
+
+ expect(container.querySelectorAll("td")[0].textContent).toBe(
+ `Plan 7${expected}`
+ );
+ });
+
+ test("never badges a GitOps Plan as Incomplete", () => {
+ render([
+ {
+ ...basePlan,
+ hasRollout: false,
+ specs: [
+ {
+ config: {
+ case: "changeDatabaseConfig",
+ value: { release: "projects/foo/releases/r1" },
+ },
+ },
+ ],
+ } as unknown as Plan,
+ ]);
+
+ expect(container.querySelectorAll("td")[0].textContent).toBe("Plan 7");
+ });
+});
diff --git a/frontend/src/routes/project/PlanTable.tsx b/frontend/src/routes/project/PlanTable.tsx
new file mode 100644
index 0000000000..ffa2766256
--- /dev/null
+++ b/frontend/src/routes/project/PlanTable.tsx
@@ -0,0 +1,273 @@
+import type { TFunction } from "i18next";
+import type { MouseEvent, ReactNode } from "react";
+import { useCallback, useEffect, useMemo, useRef } from "react";
+import { useTranslation } from "react-i18next";
+import { router } from "@/app/router";
+import { PROJECT_V1_ROUTE_PLAN_DETAIL } from "@/app/router/handles";
+import { TaskStatusIcon } from "@/components/TaskStatusIcon";
+import { Badge } from "@/components/ui/badge";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
+import { useColumnWidths } from "@/hooks/useColumnWidths";
+import { cn } from "@/lib/utils";
+import { useAppStore } from "@/stores/app";
+import {
+ formatEnvironmentName,
+ getTimeForPbTimestampProtoEs,
+ unknownUser,
+} from "@/types";
+import { State } from "@/types/proto-es/v1/common_pb";
+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
+import { extractPlanUID } from "@/utils";
+import {
+ extractStageUID,
+ getStageStatusFromCounts,
+} from "@/utils/v1/issue/rollout";
+import { isReleaseBackedPlan } from "./plan-detail/utils/spec";
+import {
+ getPlanDraftState,
+ getReviewBadge,
+ type PlanDraftState,
+ type ReviewBadge,
+} from "./utils/reviewBadge";
+
+export interface PlanColumn {
+ key: string;
+ title: ReactNode;
+ defaultWidth: number;
+ minWidth?: number;
+ resizable?: boolean;
+ render: (plan: Plan, ctx: PlanRowContext) => ReactNode;
+}
+
+export interface PlanRowContext {
+ creator: { title: string; name: string };
+ createTimeMs: number | undefined;
+ updateTimeMs: number | undefined;
+ approvalTag: { label: string; variant: ReviewBadge["variant"] } | undefined;
+ isDeleted: boolean;
+ draftState: PlanDraftState;
+}
+
+export function PlanLifecycleBadges({ ctx }: { ctx: PlanRowContext }) {
+ const { t } = useTranslation();
+ if (ctx.isDeleted) {
+ return (
+ <Badge variant="warning" className="shrink-0 font-normal">
+ {t("common.closed")}
+ </Badge>
+ );
+ }
+ if (ctx.draftState === "draft") {
+ return (
+ <Badge className="shrink-0 font-normal text-control-light">
+ {t("common.draft")}
+ </Badge>
+ );
+ }
+ if (ctx.draftState === "incomplete") {
+ return (
+ <Badge variant="destructive" className="shrink-0">
+ {t("plan.lifecycle.incomplete")}
+ </Badge>
+ );
+ }
+ return null;
+}
+
+// Both plan lists render stage progress through this column so they cannot drift.
+export function createPlanStagesColumn(t: TFunction): PlanColumn {
+ return {
+ key: "stages",
+ title: t("rollout.stage.self", { count: 2 }),
+ defaultWidth: 260,
+ minWidth: 140,
+ resizable: true,
+ render: (plan) => <PlanStages plan={plan} />,
+ };
+}
+
+function PlanStages({ plan }: { plan: Plan }) {
+ // Subscribe so stage names re-render when the environment cache loads.
+ const getEnvironmentByName = useAppStore((s) => s.getEnvironmentByName);
+ void useAppStore((s) => s.environmentList);
+
+ if (plan.rolloutStageSummaries.length === 0) {
+ return <span className="text-control-light">-</span>;
+ }
+ return (
+ <div className="flex items-center gap-1 flex-wrap">
+ {plan.rolloutStageSummaries.map((summary, index) => {
+ const envName = formatEnvironmentName(extractStageUID(summary.stage));
+ const environment = getEnvironmentByName(envName);
+ const stageStatus = getStageStatusFromCounts(summary.taskStatusCounts);
+ return (
+ <div key={summary.stage} className="flex items-center gap-1">
+ <div className="flex items-center gap-1">
+ <TaskStatusIcon size="tiny" status={stageStatus} />
+ <span className="text-sm">{environment?.title || envName}</span>
+ </div>
+ {index < plan.rolloutStageSummaries.length - 1 && (
+ <span className="mx-1 text-control-light">&rarr;</span>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+const resolvePlanDetailUrl = (plan: Plan, projectId: string): string =>
+ router.resolve({
+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,
+ params: { projectId, planId: extractPlanUID(plan.name) },
+ }).fullPath;
+
+export function PlanTable({
+ plans,
+ projectId,
+ columns,
+ isMobile,
+ resolvePlanUrl = resolvePlanDetailUrl,
+ onOpenPlan,
+}: {
+ plans: Plan[];
+ projectId: string;
+ columns: PlanColumn[];
+ isMobile: boolean;
+ resolvePlanUrl?: (plan: Plan, projectId: string) => string;
+ onOpenPlan: () => void;
+}) {
+ const { widths, totalWidth, onResizeStart, setWidths } =
+ useColumnWidths(columns);
+
+ // useColumnWidths seeds its state only on first render, so a viewport that
+ // crosses the `sm` breakpoint after mount (resize / rotate) would keep the
+ // stale name-column width. Re-seed from the rebuilt column defaults whenever
+ // the breakpoint flips.
+ const wasMobile = useRef(isMobile);
+ useEffect(() => {
+ if (wasMobile.current !== isMobile) {
+ wasMobile.current = isMobile;
+ setWidths(columns.map((c) => c.defaultWidth));
+ }
+ }, [isMobile, columns, setWidths]);
+
+ return (
+ <div className="overflow-x-auto rounded-sm border border-block-border">
+ <Table className="table-fixed" style={{ minWidth: `${totalWidth}px` }}>
+ <colgroup>
+ {widths.map((w, i) => (
+ <col key={columns[i].key} style={{ width: `${w}px` }} />
+ ))}
+ </colgroup>
+ <TableHeader>
+ <TableRow className="bg-control-bg">
+ {columns.map((col, colIdx) => (
+ <TableHead
+ key={col.key}
+ resizable={col.resizable}
+ onResizeStart={
+ col.resizable ? (e) => onResizeStart(colIdx, e) : undefined
+ }
+ >
+ {col.title}
+ </TableHead>
+ ))}
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {plans.map((plan) => (
+ <PlanRow
+ key={plan.name}
+ plan={plan}
+ columns={columns}
+ planUrl={resolvePlanUrl(plan, projectId)}
+ onOpenPlan={onOpenPlan}
+ />
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ );
+}
+
+function PlanRow({
+ plan,
+ columns,
+ planUrl,
+ onOpenPlan,
+}: Readonly<{
+ plan: Plan;
+ columns: PlanColumn[];
+ planUrl: string;
+ onOpenPlan: () => void;
+}>) {
+ const { t } = useTranslation();
+
+ const isDeleted = plan.state === State.DELETED;
+ const draftState = getPlanDraftState({
+ approvalStatus: plan.approvalStatus,
+ hasRollout: plan.hasRollout,
+ isGitOpsPlan: isReleaseBackedPlan(plan.specs),
+ issueName: plan.issue,
+ });
+
+ const creatorUser = useAppStore((state) =>
+ state.getUserByIdentifier(plan.creator)
+ );
+ const creator = creatorUser || unknownUser(plan.creator);
+
+ const onRowClick = useCallback(
+ (e: MouseEvent) => {
+ if (e.ctrlKey || e.metaKey) {
+ window.open(planUrl, "_blank");
+ } else {
+ onOpenPlan();
+ router.push(planUrl);
+ }
+ },
+ [onOpenPlan, planUrl]
+ );
+
+ const approvalTag = useMemo(() => {
+ const badge = getReviewBadge({
+ hasIssue: plan.issue !== "",
+ issueStatus: plan.issueStatus,
+ hasRollout: plan.hasRollout,
+ approvalStatus: plan.approvalStatus,
+ });
+ if (!badge) return undefined;
+ return { label: t(badge.labelKey), variant: badge.variant };
+ }, [plan.approvalStatus, plan.hasRollout, plan.issue, plan.issueStatus, t]);
+
+ const ctx: PlanRowContext = {
+ creator,
+ createTimeMs: getTimeForPbTimestampProtoEs(plan.createTime),
+ updateTimeMs: getTimeForPbTimestampProtoEs(plan.updateTime),
+ approvalTag,
+ isDeleted,
+ draftState,
+ };
+
+ return (
+ <TableRow
+ data-testid="plan-list-item"
+ data-scroll-restoration-anchor={plan.name}
+ className={cn("cursor-pointer", isDeleted && "opacity-60")}
+ onClick={onRowClick}
+ >
+ {columns.map((col) => (
+ <TableCell key={col.key} className="overflow-hidden">
+ {col.render(plan, ctx)}
+ </TableCell>
+ ))}
+ </TableRow>
+ );
+}
diff --git a/frontend/src/routes/project/ProjectGitOpsPage.tsx b/frontend/src/routes/project/ProjectGitOpsPage.tsx
index d329f05a85..054bf9d7bc 100644
--- a/frontend/src/routes/project/ProjectGitOpsPage.tsx
+++ b/frontend/src/routes/project/ProjectGitOpsPage.tsx
@@ -1,12 +1,20 @@
-import { Check, ChevronDown, ChevronRight, XCircle } from "lucide-react";
+import {
+ ArrowLeft,
+ Check,
+ ChevronDown,
+ ChevronRight,
+ XCircle,
+} from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
+import { PROJECT_V1_ROUTE_RELEASES } from "@/app/router/handles";
import gitopsWorkflowImage from "@/assets/gitops-workflow.svg";
import { CreateWorkloadIdentitySheet } from "@/components/CreateWorkloadIdentitySheet";
import { DatabaseSelect } from "@/components/DatabaseSelect";
import { ExternalUrlAlert } from "@/components/ExternalUrlAlert";
import { PermissionGuard } from "@/components/PermissionGuard";
import { ProjectPageLayout } from "@/components/ProjectPageLayout";
+import { RouterLink } from "@/components/RouterLink";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Combobox, type ComboboxOption } from "@/components/ui/combobox";
@@ -232,6 +240,13 @@ export function ProjectGitOpsPage({ projectId }: { projectId: string }) {
return (
<ProjectPageLayout className="gap-y-1">
+ <RouterLink
+ to={{ name: PROJECT_V1_ROUTE_RELEASES, params: { projectId } }}
+ className="mb-2 inline-flex items-center gap-x-1 self-start text-sm text-accent hover:underline"
+ >
+ <ArrowLeft className="size-4" />
+ {t("gitops.back-to-releases")}
+ </RouterLink>
{/* Section 1: What is GitOps */}
<div className="flex flex-col gap-y-3 rounded-sm border border-block-border p-6">
<div className="flex flex-col gap-y-1">
diff --git a/frontend/src/routes/project/ProjectPlanDashboardPage.test.tsx b/frontend/src/routes/project/ProjectPlanDashboardPage.test.tsx
index 1b6e426ae8..4f8edb9a32 100644
--- a/frontend/src/routes/project/ProjectPlanDashboardPage.test.tsx
+++ b/frontend/src/routes/project/ProjectPlanDashboardPage.test.tsx
@@ -28,6 +28,7 @@ const plan = {
const mocks = vi.hoisted(() => ({
batchGetOrFetchUsers: vi.fn(async () => []),
listUsers: vi.fn(async () => ({ users: [] })),
+ listPlans: vi.fn(async () => ({ plans: [], nextPageToken: "" })),
listScrollRestorationKey: undefined as string | undefined,
markListScrollRestorationEntry: vi.fn(),
routerPush: vi.fn(),
@@ -88,6 +89,10 @@ vi.mock("@/components/TaskStatusIcon", () => ({
TaskStatusIcon: () => null,
}));
+vi.mock("@/components/TimeRangePicker", () => ({
+ TimeRangePicker: () => null,
+}));
+
vi.mock("@/components/ui/badge", () => ({
Badge: ({
children,
@@ -193,7 +198,7 @@ vi.mock("@/stores/app", () => {
useAppStore: Object.assign(useAppStore, {
getState: () => ({
batchGetOrFetchDatabases: vi.fn(async () => []),
- listPlans: vi.fn(async () => ({ plans: [], nextPageToken: "" })),
+ listPlans: mocks.listPlans,
}),
}),
};
@@ -375,4 +380,37 @@ describe("ProjectPlanDashboardPage scroll restoration", () => {
);
expect(closedBadges).toHaveLength(2);
});
+
+ test("lists only ClickOps Plans and passes the status and created scopes", async () => {
+ act(() => {
+ root.render(
+ <MemoryRouter
+ initialEntries={[
+ "/projects/foo/plans?q=state%3AACTIVE%20status%3AFAILED%20created%3A1000%2C2000",
+ ]}
+ >
+ <ProjectPlanDashboardPage projectId="foo" />
+ </MemoryRouter>
+ );
+ });
+
+ const options = mocks.usePagedData.mock.lastCall?.[0] as {
+ fetchList: (params: { pageSize: number; pageToken: string }) => unknown;
+ };
+ await options.fetchList({ pageSize: 50, pageToken: "" });
+
+ expect(mocks.listPlans).toHaveBeenCalledWith(
+ expect.objectContaining({
+ find: expect.objectContaining({
+ project: "projects/foo",
+ hasRelease: false,
+ specType: "change_database_config",
+ state: "ACTIVE",
+ taskStatuses: ["FAILED"],
+ createdTsAfter: 1000,
+ createdTsBefore: 2000,
+ }),
+ })
+ );
+ });
});
diff --git a/frontend/src/routes/project/ProjectPlanDashboardPage.tsx b/frontend/src/routes/project/ProjectPlanDashboardPage.tsx
index da88b859b6..133f8abf82 100644
--- a/frontend/src/routes/project/ProjectPlanDashboardPage.tsx
+++ b/frontend/src/routes/project/ProjectPlanDashboardPage.tsx
@@ -5,11 +5,10 @@ import {
Loader2,
Plus,
} from "lucide-react";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { v4 as uuidv4 } from "uuid";
import { router } from "@/app/router";
-import { PROJECT_V1_ROUTE_PLAN_DETAIL } from "@/app/router/handles";
import {
markListScrollRestorationEntry,
useListScrollRestorationKey,
@@ -35,7 +34,7 @@ import {
ProjectPageInfo,
ProjectPageLayout,
} from "@/components/ProjectPageLayout";
-import { TaskStatusIcon } from "@/components/TaskStatusIcon";
+import { TimeRangePicker } from "@/components/TimeRangePicker";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { SearchInput } from "@/components/ui/search-input";
@@ -47,16 +46,7 @@ import {
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@/components/ui/table";
import { useCurrentUser } from "@/hooks/useAppState";
-import { useColumnWidths } from "@/hooks/useColumnWidths";
import { useEscapeKey } from "@/hooks/useEscapeKey";
import { useMediaQuery } from "@/hooks/useMediaQuery";
import { PagedTableFooter, usePagedData } from "@/hooks/usePagedData";
@@ -73,13 +63,7 @@ import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
import { buildPlanFindBySearchParams } from "@/stores/app/plan";
import { projectNamePrefix } from "@/stores/modules/v1/common";
-import {
- formatEnvironmentName,
- getTimeForPbTimestampProtoEs,
- isValidDatabaseGroupName,
- unknownUser,
-} from "@/types";
-import { State } from "@/types/proto-es/v1/common_pb";
+import { isValidDatabaseGroupName } from "@/types";
import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";
import type { Plan, Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
import {
@@ -94,21 +78,22 @@ import {
getDefaultPagination,
} from "@/utils";
import {
- extractStageUID,
- getStageStatusFromCounts,
-} from "@/utils/v1/issue/rollout";
-import { isReleaseBackedPlan } from "./plan-detail/utils/spec";
-import {
- getPlanDraftState,
- getReviewBadge,
- type PlanDraftState,
- type ReviewBadge,
-} from "./utils/reviewBadge";
+ createPlanStagesColumn,
+ type PlanColumn,
+ PlanLifecycleBadges,
+ PlanTable,
+} from "./PlanTable";
+import { planStateScopeOption, planStatusScopeOption } from "./planListSearch";
// Below Tailwind's `sm` breakpoint (640px) we switch the plan list and the
// database picker to their compact mobile layouts.
const MOBILE_MEDIA_QUERY = "(max-width: 639px)";
-const parsePlanSearchParams = createAdvancedSearchParser(["state", "creator"]);
+const parsePlanSearchParams = createAdvancedSearchParser([
+ "state",
+ "creator",
+ "status",
+ "created",
+]);
export function ProjectPlanDashboardPage({ projectId }: { projectId: string }) {
const { t } = useTranslation();
@@ -153,23 +138,8 @@ export function ProjectPlanDashboardPage({ projectId }: { projectId: string }) {
// Scope options
const scopeOptions: ScopeOption[] = useMemo(
() => [
- {
- id: "state",
- title: t("common.state"),
- description: t("issue.advanced-search.scope.state.description"),
- options: [
- {
- value: "ACTIVE",
- keywords: ["active", "ACTIVE"],
- render: () => <span>{t("common.active")}</span>,
- },
- {
- value: "DELETED",
- keywords: ["deleted", "DELETED", "closed", "CLOSED"],
- render: () => <span>{t("common.closed")}</span>,
- },
- ],
- },
+ planStateScopeOption(t),
+ planStatusScopeOption(t),
{
id: "creator",
title: t("issue.advanced-search.scope.creator.title"),
@@ -199,6 +169,9 @@ export function ProjectPlanDashboardPage({ projectId }: { projectId: string }) {
[t, listUsers, me]
);
+ const isMobile = useMediaQuery(MOBILE_MEDIA_QUERY);
+ const columns = usePlanColumns(isMobile);
+
const [canCreate] = usePermissionCheck(
["bb.plans.create", "bb.issues.create"],
project
@@ -215,6 +188,7 @@ export function ProjectPlanDashboardPage({ projectId }: { projectId: string }) {
};
return buildPlanFindBySearchParams(merged, {
specType: "change_database_config",
+ hasRelease: false,
});
}, [searchParams, projectId]);
@@ -296,13 +270,19 @@ export function ProjectPlanDashboardPage({ projectId }: { projectId: string }) {
return (
<ProjectPageLayout>
<div className="flex flex-col gap-y-2">
- <ProjectPageInfo description={t("plan.subtitle")} />
+ <ProjectPageInfo description={t("plan.list-description")} />
<div className="w-full flex flex-col lg:flex-row items-start lg:items-center justify-between gap-2">
- <div className="w-full flex flex-1 items-center justify-between gap-x-2">
- <AdvancedSearch
+ <div className="w-full flex flex-1 flex-wrap items-center justify-between gap-2">
+ <div className="min-w-0 basis-80 grow">
+ <AdvancedSearch
+ params={searchParams}
+ onParamsChange={setSearchParams}
+ scopeOptions={scopeOptions}
+ />
+ </div>
+ <TimeRangePicker
params={searchParams}
onParamsChange={setSearchParams}
- scopeOptions={scopeOptions}
/>
<PermissionGuard
permissions={["bb.plans.create", "bb.issues.create"]}
@@ -334,6 +314,8 @@ export function ProjectPlanDashboardPage({ projectId }: { projectId: string }) {
<PlanTable
plans={paged.dataList}
projectId={projectId}
+ columns={columns}
+ isMobile={isMobile}
onOpenPlan={markListScrollRestorationEntry}
/>
)}
@@ -364,41 +346,12 @@ export function ProjectPlanDashboardPage({ projectId }: { projectId: string }) {
}
// ---------------------------------------------------------------------------
-// PlanTable
+// Columns
// ---------------------------------------------------------------------------
-interface PlanColumn {
- key: string;
- title: React.ReactNode;
- defaultWidth: number;
- minWidth?: number;
- resizable?: boolean;
- render: (plan: Plan, ctx: PlanRowContext) => React.ReactNode;
-}
-
-interface PlanRowContext {
- creator: { title: string; name: string };
- updateTimeMs: number | undefined;
- approvalTag: { label: string; variant: ReviewBadge["variant"] } | undefined;
- isDeleted: boolean;
- draftState: PlanDraftState;
-}
-
-function PlanTable({
- plans,
- projectId,
- onOpenPlan,
-}: {
- plans: Plan[];
- projectId: string;
- onOpenPlan: () => void;
-}) {
+function usePlanColumns(isMobile: boolean): PlanColumn[] {
const { t } = useTranslation();
- const isMobile = useMediaQuery(MOBILE_MEDIA_QUERY);
- // Subscribe so stage cells re-render when the environment cache loads.
- void useAppStore((s) => s.environmentList);
-
- const columns = useMemo<PlanColumn[]>(
+ return useMemo<PlanColumn[]>(
() => [
{
key: "name",
@@ -419,21 +372,7 @@ function PlanTable({
) : (
<span className="opacity-60 italic">{t("common.untitled")}</span>
)}
- {ctx.isDeleted && (
- <span className="inline-flex items-center rounded-xs border border-transparent bg-warning/10 px-1.5 py-0.5 text-xs text-warning shrink-0">
- {t("common.closed")}
- </span>
- )}
- {ctx.draftState === "draft" && !ctx.isDeleted && (
- <span className="inline-flex items-center rounded-xs border border-transparent bg-control-bg px-1.5 py-0.5 text-xs text-control-light shrink-0">
- {t("common.draft")}
- </span>
- )}
- {ctx.draftState === "incomplete" && !ctx.isDeleted && (
- <Badge variant="destructive" className="shrink-0 px-2 text-xs">
- {t("plan.lifecycle.incomplete")}
- </Badge>
- )}
+ <PlanLifecycleBadges ctx={ctx} />
</div>
),
},
@@ -465,44 +404,7 @@ function PlanTable({
<span className="text-control-light">-</span>
),
},
- {
- key: "stages",
- title: t("rollout.stage.self", { count: 2 }),
- defaultWidth: 260,
- minWidth: 140,
- resizable: true,
- render: (plan, _ctx) =>
- plan.rolloutStageSummaries.length === 0 ? (
- <span className="text-control-light">-</span>
- ) : (
- <div className="flex items-center gap-1 flex-wrap">
- {plan.rolloutStageSummaries.map((summary, index) => {
- const envName = formatEnvironmentName(
- extractStageUID(summary.stage)
- );
- const environment = useAppStore
- .getState()
- .getEnvironmentByName(envName);
- const stageStatus = getStageStatusFromCounts(
- summary.taskStatusCounts
- );
- return (
- <div key={summary.stage} className="flex items-center gap-1">
- <div className="flex items-center gap-1">
- <TaskStatusIcon size="tiny" status={stageStatus} />
- <span className="text-sm">
- {environment?.title || envName}
- </span>
- </div>
- {index < plan.rolloutStageSummaries.length - 1 && (
- <span className="mx-1 text-control-light">&rarr;</span>
- )}
- </div>
- );
- })}
- </div>
- ),
- },
+ createPlanStagesColumn(t),
{
key: "updated",
title: t("issue.table.updated"),
@@ -522,148 +424,6 @@ function PlanTable({
],
[t, isMobile]
);
-
- const { widths, totalWidth, onResizeStart, setWidths } =
- useColumnWidths(columns);
-
- // useColumnWidths seeds its state only on first render, so a viewport that
- // crosses the `sm` breakpoint after mount (resize / rotate) would keep the
- // stale name-column width. Re-seed from the rebuilt column defaults whenever
- // the breakpoint flips.
- const wasMobile = useRef(isMobile);
- useEffect(() => {
- if (wasMobile.current !== isMobile) {
- wasMobile.current = isMobile;
- setWidths(columns.map((c) => c.defaultWidth));
- }
- }, [isMobile, columns, setWidths]);
-
- return (
- <div className="overflow-x-auto rounded-sm border border-block-border">
- <Table className="table-fixed" style={{ minWidth: `${totalWidth}px` }}>
- <colgroup>
- {widths.map((w, i) => (
- <col key={columns[i].key} style={{ width: `${w}px` }} />
- ))}
- </colgroup>
- <TableHeader>
- <TableRow className="bg-control-bg">
- {columns.map((col, colIdx) => (
- <TableHead
- key={col.key}
- resizable={col.resizable}
- onResizeStart={
- col.resizable ? (e) => onResizeStart(colIdx, e) : undefined
- }
- >
- {col.title}
- </TableHead>
- ))}
- </TableRow>
- </TableHeader>
- <TableBody>
- {plans.map((plan) => (
- <PlanRow
- key={plan.name}
- plan={plan}
- projectId={projectId}
- columns={columns}
- onOpenPlan={onOpenPlan}
- />
- ))}
- </TableBody>
- </Table>
- </div>
- );
-}
-
-// ---------------------------------------------------------------------------
-// PlanRow
-// ---------------------------------------------------------------------------
-
-function PlanRow({
- plan,
- projectId,
- columns,
- onOpenPlan,
-}: Readonly<{
- plan: Plan;
- projectId: string;
- columns: PlanColumn[];
- onOpenPlan: () => void;
-}>) {
- const { t } = useTranslation();
-
- const isDeleted = plan.state === State.DELETED;
- const draftState = getPlanDraftState({
- approvalStatus: plan.approvalStatus,
- hasRollout: plan.hasRollout,
- isGitOpsPlan: isReleaseBackedPlan(plan.specs),
- issueName: plan.issue,
- });
-
- const creatorUser = useAppStore((state) =>
- state.getUserByIdentifier(plan.creator)
- );
- const creator = creatorUser || unknownUser(plan.creator);
-
- const updateTimeMs = getTimeForPbTimestampProtoEs(plan.updateTime);
-
- const planUrl = useMemo(() => {
- return router.resolve({
- name: PROJECT_V1_ROUTE_PLAN_DETAIL,
- params: {
- projectId,
- planId: extractPlanUID(plan.name),
- },
- }).fullPath;
- }, [plan.name, projectId]);
-
- const onRowClick = useCallback(
- (e: React.MouseEvent) => {
- if (e.ctrlKey || e.metaKey) {
- window.open(planUrl, "_blank");
- } else {
- onOpenPlan();
- router.push(planUrl);
- }
- },
- [onOpenPlan, planUrl]
- );
-
- const approvalTag = useMemo(() => {
- const badge = getReviewBadge({
- hasIssue: plan.issue !== "",
- issueStatus: plan.issueStatus,
- hasRollout: plan.hasRollout,
- approvalStatus: plan.approvalStatus,
- });
- if (!badge) return undefined;
- return { label: t(badge.labelKey), variant: badge.variant };
- }, [plan.approvalStatus, plan.hasRollout, plan.issue, plan.issueStatus, t]);
-
- const ctx: PlanRowContext = {
- creator,
- updateTimeMs,
- approvalTag,
- isDeleted,
- draftState,
- };
-
- return (
- <TableRow
- data-testid="plan-list-item"
- data-scroll-restoration-anchor={plan.name}
- className={cn("cursor-pointer", isDeleted && "opacity-60")}
- onClick={onRowClick}
- >
- {columns.map((col) => (
- <TableCell key={col.key} className="overflow-hidden">
- {col.render(plan, ctx)}
- </TableCell>
- ))}
- </TableRow>
- );
}
// ---------------------------------------------------------------------------
diff --git a/frontend/src/routes/project/ProjectReleaseDashboardPage.test.tsx b/frontend/src/routes/project/ProjectReleaseDashboardPage.test.tsx
index 378f1158cd..206c81245e 100644
--- a/frontend/src/routes/project/ProjectReleaseDashboardPage.test.tsx
+++ b/frontend/src/routes/project/ProjectReleaseDashboardPage.test.tsx
@@ -1,41 +1,121 @@
import { act, createElement, type ReactNode } from "react";
import { createRoot, type Root } from "react-dom/client";
+import { MemoryRouter } from "react-router";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { State, VCSType } from "@/types/proto-es/v1/common_pb";
+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
+import type { Release } from "@/types/proto-es/v1/release_service_pb";
import { ProjectReleaseDashboardPage } from "./ProjectReleaseDashboardPage";
(
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
+const gitOpsPlan = {
+ name: "projects/foo/plans/7",
+ title: "Release r1 to all environments",
+ state: State.ACTIVE,
+ creator: "users/[email protected]",
+ issue: "",
+ hasRollout: true,
+ specs: [
+ {
+ config: {
+ case: "changeDatabaseConfig",
+ value: { release: "projects/foo/releases/release_20261022-RC01" },
+ },
+ },
+ ],
+ rolloutStageSummaries: [],
+} as unknown as Plan;
+
+const release = {
+ name: "projects/foo/releases/release_20261022-RC01",
+ state: State.ACTIVE,
+ vcsSource: {
+ vcsType: VCSType.GITHUB,
+ url: "https://github.com/acme/app/commit/0123456789abcdef",
+ },
+} as unknown as Release;
+
const mocks = vi.hoisted(() => ({
- listReleaseCategories: vi.fn(async () => ({ categories: [] })),
- listReleasesByProject: vi.fn(async () => ({
- nextPageToken: "",
- releases: [],
- })),
+ fetchRelease: vi.fn(),
+ listPlans: vi.fn(),
+ probeListPlans: vi.fn(),
+ canSetUpGitOps: true,
+ canGetReleases: true,
+ routerPush: vi.fn(),
usePagedData: vi.fn(),
}));
+const store = vi.hoisted(() => ({
+ current: undefined as
+ | import("zustand").UseBoundStore<
+ import("zustand").StoreApi<Record<string, unknown>>
+ >
+ | undefined,
+}));
+
+const pagedData = (dataList: Plan[]) => ({
+ dataList,
+ hasMore: false,
+ isFetchingMore: false,
+ isLoading: false,
+ loadMore: vi.fn(),
+ onPageSizeChange: vi.fn(),
+ pageSize: 50,
+ pageSizeOptions: [50, 100],
+ refresh: vi.fn(),
+ removeCache: vi.fn(),
+ updateCache: vi.fn(),
+});
+
vi.mock("react-i18next", async (importOriginal) => ({
...(await importOriginal<typeof import("react-i18next")>()),
useTranslation: () => ({ t: (key: string) => key }),
}));
vi.mock("@/api", () => ({
- releaseServiceClientConnect: {
- listReleaseCategories: mocks.listReleaseCategories,
- },
+ planServiceClientConnect: { listPlans: mocks.probeListPlans },
}));
vi.mock("@/app/router", () => ({
- router: { push: vi.fn() },
+ router: {
+ push: mocks.routerPush,
+ resolve: ({
+ name,
+ params,
+ }: {
+ name: string;
+ params: Record<string, string>;
+ }) => ({ fullPath: `/${name}/${params.planId ?? ""}` }),
+ },
}));
vi.mock("@/app/router/NavigationScrollRestoration", () => ({
markListScrollRestorationEntry: vi.fn(),
+ useListScrollRestorationKey: () => undefined,
useListScrollRestorationLoadMore: () => undefined,
}));
+vi.mock("@/components/AdvancedSearch", () => ({
+ AdvancedSearch: () => createElement("div"),
+}));
+
+vi.mock("@/components/HumanizeTs", async () => ({
+ ...(await import("@/test-utils/humanizeTs")).humanizeTsStub(),
+}));
+
+vi.mock("@/components/PermissionGuard", () => ({
+ PermissionGuard: ({ children }: { children: ReactNode }) => children,
+ usePermissionCheck: (permissions: string[]) => [
+ permissions.includes("bb.releases.get")
+ ? mocks.canGetReleases
+ : mocks.canSetUpGitOps,
+ undefined,
+ ],
+}));
+
vi.mock("@/components/ProjectPageLayout", () => ({
ProjectPageContent: ({ children }: { children: ReactNode }) =>
createElement("div", {}, children),
@@ -46,44 +126,91 @@ vi.mock("@/components/ProjectPageLayout", () => ({
createElement("div", {}, children),
}));
+vi.mock("@/components/TaskStatusIcon", () => ({
+ TaskStatusIcon: () => null,
+}));
+
+vi.mock("@/components/TimeRangePicker", () => ({
+ TimeRangePicker: () => null,
+}));
+
+vi.mock("@/hooks/useColumnWidths", () => ({
+ useColumnWidths: (columns: { defaultWidth: number }[]) => ({
+ widths: columns.map((column) => column.defaultWidth),
+ totalWidth: columns.reduce((sum, column) => sum + column.defaultWidth, 0),
+ onResizeStart: vi.fn(),
+ setWidths: vi.fn(),
+ }),
+}));
+
+vi.mock("@/hooks/useMediaQuery", () => ({
+ useMediaQuery: () => false,
+}));
+
vi.mock("@/hooks/usePagedData", () => ({
PagedTableFooter: () => null,
usePagedData: mocks.usePagedData,
}));
-vi.mock("@/hooks/useURLSearchParam", () => ({
- useURLSearchParam: () => ["", vi.fn()],
+vi.mock("@/hooks/useProjectByName", () => ({
+ useProjectByName: (name: string) => ({ name }),
}));
-vi.mock("@/stores/app", () => ({
- useAppStore: (
- selector: (state: { listReleasesByProject: typeof mocks.listReleasesByProject }) => unknown
- ) => selector({ listReleasesByProject: mocks.listReleasesByProject }),
-}));
+vi.mock("@/stores/app", async () => {
+ const { create: createStore } = await import("zustand");
+ store.current = createStore<Record<string, unknown>>(() => ({}));
+ return { useAppStore: store.current };
+});
-const pagedData = {
- dataList: [],
- hasMore: false,
- isFetchingMore: false,
- isLoading: false,
- loadMore: vi.fn(),
- onPageSizeChange: vi.fn(),
- pageSize: 50,
- pageSizeOptions: [50, 100],
- refresh: vi.fn(),
- removeCache: vi.fn(),
- updateCache: vi.fn(),
+const resetStore = () => {
+ store.current?.setState(
+ {
+ releasesByName: {},
+ environmentList: [],
+ fetchRelease: mocks.fetchRelease,
+ getEnvironmentByName: () => undefined,
+ getUserByIdentifier: () => undefined,
+ listPlans: mocks.listPlans,
+ },
+ true
+ );
};
describe("ProjectReleaseDashboardPage", () => {
let container: HTMLDivElement;
let root: Root;
+ const render = async () => {
+ await act(async () => {
+ root.render(
+ <MemoryRouter initialEntries={["/projects/foo/releases?category=hotfix"]}>
+ <ProjectReleaseDashboardPage projectId="foo" />
+ </MemoryRouter>
+ );
+ });
+ };
+
+ const text = () => container.textContent ?? "";
+
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
- mocks.usePagedData.mockReturnValue(pagedData);
+ resetStore();
+ mocks.fetchRelease.mockImplementation(async (name: string) => {
+ store.current?.setState((state) => ({
+ releasesByName: {
+ ...(state.releasesByName as Record<string, Release>),
+ [name]: release,
+ },
+ }));
+ return release;
+ });
+ mocks.listPlans.mockResolvedValue({ plans: [], nextPageToken: "" });
+ mocks.probeListPlans.mockResolvedValue({ plans: [] });
+ mocks.usePagedData.mockReturnValue(pagedData([gitOpsPlan]));
+ mocks.canSetUpGitOps = true;
+ mocks.canGetReleases = true;
});
afterEach(() => {
@@ -92,12 +219,141 @@ describe("ProjectReleaseDashboardPage", () => {
vi.clearAllMocks();
});
- test("hides the category filter when the project has no release categories", async () => {
- await act(async () => {
- root.render(<ProjectReleaseDashboardPage projectId="foo" />);
- await Promise.resolve();
- });
+ test("lists GitOps Plans, ignoring the old category parameter", async () => {
+ await render();
+
+ const options = mocks.usePagedData.mock.lastCall?.[0] as {
+ fetchList: (params: { pageSize: number; pageToken: string }) => unknown;
+ };
+ await options.fetchList({ pageSize: 50, pageToken: "" });
+
+ expect(mocks.listPlans).toHaveBeenCalledWith(
+ expect.objectContaining({
+ find: {
+ project: "projects/foo",
+ query: "",
+ hasRelease: true,
+ specType: "change_database_config",
+ state: "ACTIVE",
+ creator: "",
+ release: undefined,
+ createdTsAfter: undefined,
+ createdTsBefore: undefined,
+ taskStatuses: undefined,
+ },
+ })
+ );
+ });
+
+ test("renders the release ID, source commit, stages, and created columns", async () => {
+ await render();
+
+ const headers = Array.from(container.querySelectorAll("th")).map(
+ (th) => th.textContent
+ );
+ expect(headers).toEqual([
+ "release.self",
+ "release.source",
+ "rollout.stage.self",
+ "common.created-at",
+ ]);
+ expect(text()).toContain("release_20261022-RC01");
+ expect(text()).not.toContain(gitOpsPlan.title);
+ expect(mocks.fetchRelease).toHaveBeenCalledOnce();
+ const commit = container.querySelector<HTMLAnchorElement>(
+ 'a[href="https://github.com/acme/app/commit/0123456789abcdef"]'
+ );
+ expect(commit?.textContent).toBe("0123456");
+ });
+
+ test("shows - as the source when the release cannot be read", async () => {
+ mocks.fetchRelease.mockRejectedValue(new Error("not found"));
+
+ await render();
+
+ expect(container.querySelector("a")).toBeNull();
+ const sourceCell = container.querySelectorAll("td")[1];
+ expect(sourceCell.textContent).toBe("-");
+ });
+
+ test("skips release lookups without permission to read releases", async () => {
+ mocks.canGetReleases = false;
+
+ await render();
+
+ expect(mocks.fetchRelease).not.toHaveBeenCalled();
+ expect(text()).toContain("release_20261022-RC01");
+ expect(container.querySelectorAll("td")[1].textContent).toBe("-");
+ });
+
+ test("opens a Plan's rollout from its row", async () => {
+ await render();
+
+ act(() =>
+ container
+ .querySelector<HTMLElement>('[data-testid="plan-list-item"]')
+ ?.click()
+ );
+
+ expect(mocks.routerPush).toHaveBeenCalledWith(
+ "/workspace.project.plan.detail.rollout/7"
+ );
+ });
+
+ test("offers GitOps setup at the top right once the project has a GitOps Plan", async () => {
+ await render();
+
+ expect(
+ container.querySelector('[data-testid="release-gitops-setup"]')
+ ).not.toBeNull();
+ });
+
+ test("shows the setup empty state when the project has no GitOps Plan", async () => {
+ mocks.usePagedData.mockReturnValue(pagedData([]));
+
+ await render();
+
+ expect(
+ container.querySelector('[data-testid="release-setup-empty-state"]')
+ ).not.toBeNull();
+ expect(text()).toContain("release.empty.title");
+ expect(
+ container.querySelector('[data-testid="release-gitops-setup"]')
+ ).toBeNull();
+ expect(mocks.probeListPlans).toHaveBeenCalledWith(
+ expect.objectContaining({
+ parent: "projects/foo",
+ filter: 'has_release == true && spec_type == "change_database_config"',
+ pageSize: 1,
+ })
+ );
+ });
+
+ test("shows No data when filters hide the project's GitOps Plans", async () => {
+ mocks.usePagedData.mockReturnValue(pagedData([]));
+ mocks.probeListPlans.mockResolvedValue({ plans: [gitOpsPlan] });
+
+ await render();
+
+ expect(text()).toContain("common.no-data");
+ expect(text()).not.toContain("release.empty.title");
+ expect(
+ container.querySelector('[data-testid="release-gitops-setup"]')
+ ).not.toBeNull();
+ });
+
+ test.each([
+ { name: "the toolbar", plans: [gitOpsPlan], label: "release.gitops-setup" },
+ { name: "the empty state", plans: [], label: "release.empty.set-up" },
+ ])("disables GitOps setup in $name without setup permission", async ({ plans, label }) => {
+ mocks.canSetUpGitOps = false;
+ mocks.usePagedData.mockReturnValue(pagedData(plans));
+
+ await render();
- expect(container.querySelector('[role="combobox"]')).toBeNull();
+ const button = Array.from(container.querySelectorAll("button")).find(
+ (element) => element.textContent?.includes(label)
+ );
+ expect(button?.disabled).toBe(true);
});
});
diff --git a/frontend/src/routes/project/ProjectReleaseDashboardPage.tsx b/frontend/src/routes/project/ProjectReleaseDashboardPage.tsx
index 4c4c869e6d..f0c0a10e6b 100644
--- a/frontend/src/routes/project/ProjectReleaseDashboardPage.tsx
+++ b/frontend/src/routes/project/ProjectReleaseDashboardPage.tsx
@@ -1,49 +1,93 @@
import { create } from "@bufbuild/protobuf";
-import { Loader2 } from "lucide-react";
+import { GitCommitHorizontal, Loader2, Settings2 } from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
-import { releaseServiceClientConnect } from "@/api";
+import { planServiceClientConnect } from "@/api";
import { router } from "@/app/router";
+import {
+ PROJECT_V1_ROUTE_GITOPS,
+ PROJECT_V1_ROUTE_PLAN_DETAIL,
+ PROJECT_V1_ROUTE_PLAN_ROLLOUT,
+} from "@/app/router/handles";
import {
markListScrollRestorationEntry,
+ useListScrollRestorationKey,
useListScrollRestorationLoadMore,
} from "@/app/router/NavigationScrollRestoration";
+import azureDevOpsIcon from "@/assets/git/azure-devops.svg";
+import bitbucketIcon from "@/assets/git/bitbucket.svg";
+import githubIcon from "@/assets/git/github.svg";
+import gitlabIcon from "@/assets/git/gitlab.svg";
+import {
+ AdvancedSearch,
+ type ScopeOption,
+ type SearchParams,
+} from "@/components/AdvancedSearch";
import { HumanizeTs } from "@/components/HumanizeTs";
-import { LearnMoreLink } from "@/components/LearnMoreLink";
+import {
+ PermissionGuard,
+ usePermissionCheck,
+} from "@/components/PermissionGuard";
import {
ProjectPageContent,
ProjectPageFooter,
ProjectPageInfo,
ProjectPageLayout,
} from "@/components/ProjectPageLayout";
+import { TimeRangePicker } from "@/components/TimeRangePicker";
import { Button } from "@/components/ui/button";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@/components/ui/table";
+import { useMediaQuery } from "@/hooks/useMediaQuery";
import { PagedTableFooter, usePagedData } from "@/hooks/usePagedData";
-import { useURLSearchParam } from "@/hooks/useURLSearchParam";
-import { cn } from "@/lib/utils";
+import { useProjectByName } from "@/hooks/useProjectByName";
+import {
+ createAdvancedSearchParser,
+ serializeAdvancedSearch,
+ useURLSearchParam,
+} from "@/hooks/useURLSearchParam";
+import { projectPlansPagedDataCacheScope } from "@/lib/projectPagedDataCache";
import { useAppStore } from "@/stores/app";
+import {
+ buildPlanFilter,
+ buildPlanFindBySearchParams,
+} from "@/stores/app/plan";
import { projectNamePrefix } from "@/stores/modules/v1/common";
-import { getTimeForPbTimestampProtoEs } from "@/types";
-import { State } from "@/types/proto-es/v1/common_pb";
-import type { Release } from "@/types/proto-es/v1/release_service_pb";
-import { ListReleaseCategoriesRequestSchema } from "@/types/proto-es/v1/release_service_pb";
-import { buildCategoryFilter } from "@/utils/releaseFilter";
+import type { Permission } from "@/types";
+import { State, VCSType } from "@/types/proto-es/v1/common_pb";
+import {
+ ListPlansRequestSchema,
+ type Plan,
+} from "@/types/proto-es/v1/plan_service_pb";
+import { extractPlanUID } from "@/utils";
+import {
+ createPlanStagesColumn,
+ type PlanColumn,
+ PlanLifecycleBadges,
+ PlanTable,
+} from "./PlanTable";
+import { planStateScopeOption, planStatusScopeOption } from "./planListSearch";
-const MAX_SHOW_FILES_COUNT = 3;
+// Below Tailwind's `sm` breakpoint (640px) the table keeps a compact Release
+// column and scrolls sideways.
+const MOBILE_MEDIA_QUERY = "(max-width: 639px)";
+// `release` is not offered in the scope menu; the retired release detail URL
+// redirects here with it set.
+const parseReleaseSearchParams = createAdvancedSearchParser([
+ "state",
+ "status",
+ "created",
+ "release",
+]);
+const GITOPS_PLAN_FIND = {
+ specType: "change_database_config",
+ hasRelease: true,
+} as const;
+const GITOPS_SETUP_PERMISSIONS: Permission[] = [
+ "bb.workloadIdentities.list",
+ "bb.databases.list",
+];
+const GET_RELEASE_PERMISSIONS: Permission[] = ["bb.releases.get"];
+const GITOPS_GUIDE_URL =
+ "https://docs.bytebase.com/gitops/overview?source=console";
export function ProjectReleaseDashboardPage({
projectId,
@@ -51,101 +95,200 @@ export function ProjectReleaseDashboardPage({
projectId: string;
}) {
const { t } = useTranslation();
- const listReleasesByProject = useAppStore(
- (state) => state.listReleasesByProject
- );
+ const listScrollRestorationKey = useListScrollRestorationKey();
const projectName = `${projectNamePrefix}${projectId}`;
+ const project = useProjectByName(projectName);
+ const isMobile = useMediaQuery(MOBILE_MEDIA_QUERY);
+ const [canSetUpGitOps] = usePermissionCheck(
+ GITOPS_SETUP_PERMISSIONS,
+ project
+ );
- // Empty string means "All" — elided from the URL as the default.
- const [selectedCategory, setSelectedCategory] = useURLSearchParam({
- param: "category",
- defaultValue: "",
+ const defaultSearchParams = useMemo<SearchParams>(
+ () => ({
+ query: "",
+ scopes: [{ id: "state", value: "ACTIVE" }],
+ }),
+ []
+ );
+ const [searchParams, setSearchParams] = useURLSearchParam({
+ param: "q",
+ parse: parseReleaseSearchParams,
+ serialize: serializeAdvancedSearch,
+ defaultValue: defaultSearchParams,
});
+ const serializedSearch = serializeAdvancedSearch(searchParams);
+ const isDefaultSearch =
+ serializedSearch === serializeAdvancedSearch(defaultSearchParams);
- // Fetch categories
- const [categories, setCategories] = useState<string[]>([]);
- const [categoriesLoading, setCategoriesLoading] = useState(false);
+ const scopeOptions: ScopeOption[] = useMemo(
+ () => [planStateScopeOption(t), planStatusScopeOption(t)],
+ [t]
+ );
- useEffect(() => {
- setCategoriesLoading(true);
- const request = create(ListReleaseCategoriesRequestSchema, {
- parent: projectName,
- });
- releaseServiceClientConnect
- .listReleaseCategories(request)
- .then((resp) => setCategories(resp.categories))
- .catch(() => setCategories([]))
- .finally(() => setCategoriesLoading(false));
- }, [projectName]);
+ const planFind = useMemo(
+ () =>
+ buildPlanFindBySearchParams(
+ {
+ query: searchParams.query.trim().toLowerCase(),
+ scopes: [
+ ...searchParams.scopes.map((s) => ({ id: s.id, value: s.value })),
+ { id: "project", value: projectId },
+ ],
+ },
+ GITOPS_PLAN_FIND
+ ),
+ [searchParams, projectId]
+ );
- // Fetch releases
- const fetchReleaseList = useCallback(
+ const fetchPlanList = useCallback(
async (params: { pageSize: number; pageToken: string }) => {
- const filter = buildCategoryFilter(selectedCategory);
- const { nextPageToken, releases } = await listReleasesByProject(
- projectName,
- { pageSize: params.pageSize, pageToken: params.pageToken },
- false,
- filter
- );
- return { list: releases, nextPageToken };
+ const { nextPageToken, plans } = await useAppStore.getState().listPlans({
+ find: planFind,
+ pageSize: params.pageSize,
+ pageToken: params.pageToken,
+ });
+ return { list: plans, nextPageToken };
},
- [listReleasesByProject, projectName, selectedCategory]
+ [planFind]
);
- const paged = usePagedData<Release>({
- sessionKey: `project-${projectName}-releases`,
- fetchList: fetchReleaseList,
+ const paged = usePagedData<Plan>({
+ sessionKey: `bb.${projectName}.release-plan-table`,
+ cacheKey: JSON.stringify([
+ "project-releases",
+ projectName,
+ serializedSearch,
+ ]),
+ cacheScope: projectPlansPagedDataCacheScope(projectId),
+ cacheRestoreToken: listScrollRestorationKey,
+ fetchList: fetchPlanList,
});
useListScrollRestorationLoadMore(paged);
+ const isEmpty = !paged.isLoading && paged.dataList.length === 0;
+ const projectHasGitOpsPlan = useProjectHasGitOpsPlan(projectName, isEmpty);
+ const hasGitOpsPlan = paged.dataList.length > 0 || projectHasGitOpsPlan;
+
+ const columns = useReleaseColumns(isMobile);
+ const releaseNames = useMemo(
+ () => paged.dataList.map(getPlanReleaseName).filter(Boolean),
+ [paged.dataList]
+ );
+ // A role that can list plans but not read releases sees "-" in Source.
+ const [canGetReleases] = usePermissionCheck(GET_RELEASE_PERMISSIONS, project);
+ useFetchReleases(canGetReleases ? releaseNames : []);
+
+ const gitOpsSetupUrl = router.resolve({
+ name: PROJECT_V1_ROUTE_GITOPS,
+ params: { projectId },
+ }).fullPath;
+ const openGitOpsSetup = () => router.push(gitOpsSetupUrl);
+
+ let content;
+ if (paged.isLoading || (isEmpty && projectHasGitOpsPlan === undefined)) {
+ content = (
+ <div className="flex justify-center py-8 text-control-light">
+ <Loader2 className="size-5 animate-spin" />
+ </div>
+ );
+ } else if (isEmpty && !projectHasGitOpsPlan) {
+ content = (
+ <div
+ data-testid="release-setup-empty-state"
+ className="flex flex-col items-center gap-y-4 rounded-sm border border-dashed border-block-border px-4 py-16 text-center"
+ >
+ <div className="flex flex-col items-center gap-y-1">
+ <h2 className="text-base font-semibold text-main">
+ {t("release.empty.title")}
+ </h2>
+ <p className="max-w-md text-sm text-control-light">
+ {t("release.empty.description")}
+ </p>
+ </div>
+ <PermissionGuard
+ permissions={GITOPS_SETUP_PERMISSIONS}
+ project={project}
+ >
+ <Button disabled={!canSetUpGitOps} onClick={openGitOpsSetup}>
+ {t("release.empty.set-up")}
+ </Button>
+ </PermissionGuard>
+ <a
+ href={GITOPS_GUIDE_URL}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-sm text-accent hover:underline"
+ >
+ {t("release.empty.read-guide")}
+ </a>
+ </div>
+ );
+ } else if (isEmpty) {
+ content = (
+ <div className="flex flex-col items-center gap-y-2 py-8 text-control-light">
+ <span>{t("common.no-data")}</span>
+ {!isDefaultSearch && (
+ <Button
+ appearance="secondary"
+ size="sm"
+ onClick={() => setSearchParams(defaultSearchParams)}
+ >
+ {t("common.clear-filters")}
+ </Button>
+ )}
+ </div>
+ );
+ } else {
+ content = (
+ <PlanTable
+ plans={paged.dataList}
+ projectId={projectId}
+ columns={columns}
+ isMobile={isMobile}
+ resolvePlanUrl={resolveReleasePlanUrl}
+ onOpenPlan={markListScrollRestorationEntry}
+ />
+ );
+ }
+
return (
<ProjectPageLayout>
<div className="flex flex-col gap-y-2">
- <ProjectPageInfo
- description={
- <>
- <span>{t("release.usage-description")}</span>{" "}
- <LearnMoreLink href="https://docs.bytebase.com/gitops/migration-based-workflow/release/?source=console" />
- </>
- }
- />
-
- {(categories.length > 0 || selectedCategory) && (
- <div className="flex items-center gap-x-4">
- <CategorySelect
- value={selectedCategory}
- onChange={setSelectedCategory}
- categories={categories}
- loading={categoriesLoading}
+ <ProjectPageInfo description={t("release.list-description")} />
+ <div className="flex flex-wrap items-center gap-2">
+ <div className="min-w-0 basis-80 grow">
+ <AdvancedSearch
+ params={searchParams}
+ onParamsChange={setSearchParams}
+ scopeOptions={scopeOptions}
/>
- {selectedCategory && (
+ </div>
+ <TimeRangePicker
+ params={searchParams}
+ onParamsChange={setSearchParams}
+ />
+ {hasGitOpsPlan && (
+ <PermissionGuard
+ permissions={GITOPS_SETUP_PERMISSIONS}
+ project={project}
+ >
<Button
- appearance="secondary"
- size="sm"
- onClick={() => setSelectedCategory("")}
+ data-testid="release-gitops-setup"
+ appearance="outline"
+ disabled={!canSetUpGitOps}
+ onClick={openGitOpsSetup}
>
- {t("common.clear-filters")}
+ <Settings2 className="size-4 mr-1" />
+ {t("release.gitops-setup")}
</Button>
- )}
- </div>
- )}
+ </PermissionGuard>
+ )}
+ </div>
</div>
- {/* Release table */}
<ProjectPageContent>
- {paged.isLoading ? (
- <div className="flex justify-center py-8 text-control-light">
- <Loader2 className="size-5 animate-spin" />
- </div>
- ) : paged.dataList.length === 0 ? (
- <div className="flex justify-center py-8 text-control-light">
- {t("common.no-data")}
- </div>
- ) : (
- <ReleaseTable releases={paged.dataList} />
- )}
-
+ {content}
{paged.dataList.length > 0 && (
<ProjectPageFooter>
<PagedTableFooter
@@ -163,136 +306,170 @@ export function ProjectReleaseDashboardPage({
);
}
-// ---------------------------------------------------------------------------
-// CategorySelect
-// ---------------------------------------------------------------------------
-
-function CategorySelect({
- value,
- onChange,
- categories,
- loading,
-}: {
- value: string;
- onChange: (value: string) => void;
- categories: string[];
- loading: boolean;
-}) {
- return (
- <Select
- value={value}
- onValueChange={(nextValue: string | null) => {
- if (nextValue !== null) onChange(nextValue);
- }}
- disabled={loading}
- >
- <SelectTrigger className="w-64 rounded-sm px-3 text-sm">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="">All</SelectItem>
- {categories.map((cat) => (
- <SelectItem key={cat} value={cat}>
- {cat}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- );
+// Only asked when the filtered page is empty: it decides between the setup
+// empty state and the ordinary "No data" state.
+function useProjectHasGitOpsPlan(
+ projectName: string,
+ enabled: boolean
+): boolean | undefined {
+ const [result, setResult] = useState<{
+ projectName: string;
+ hasPlan: boolean;
+ }>();
+ useEffect(() => {
+ if (!enabled || result?.projectName === projectName) {
+ return;
+ }
+ let canceled = false;
+ planServiceClientConnect
+ .listPlans(
+ create(ListPlansRequestSchema, {
+ parent: projectName,
+ filter: buildPlanFilter({
+ project: projectName,
+ ...GITOPS_PLAN_FIND,
+ }),
+ pageSize: 1,
+ })
+ )
+ // On failure, fall back to "No data" rather than inviting a second setup.
+ .then(
+ (resp) => resp.plans.length > 0,
+ () => true
+ )
+ .then((hasPlan) => {
+ if (!canceled) setResult({ projectName, hasPlan });
+ });
+ return () => {
+ canceled = true;
+ };
+ }, [enabled, projectName, result?.projectName]);
+ return result?.projectName === projectName ? result.hasPlan : undefined;
}
-// ---------------------------------------------------------------------------
-// ReleaseTable
-// ---------------------------------------------------------------------------
+const getPlanReleaseName = (plan: Plan): string => {
+ for (const spec of plan.specs) {
+ if (
+ spec.config?.case === "changeDatabaseConfig" &&
+ spec.config.value.release
+ ) {
+ return spec.config.value.release;
+ }
+ }
+ return "";
+};
-function ReleaseTable({ releases }: { releases: Release[] }) {
- const { t } = useTranslation();
+const lastPathSegment = (value: string): string => {
+ const path = value.split(/[?#]/)[0].replace(/\/+$/, "");
+ return path.slice(path.lastIndexOf("/") + 1);
+};
- return (
- <div className="overflow-x-auto">
- <Table>
- <TableHeader>
- <TableRow className="bg-control-bg">
- <TableHead className="w-75">{t("common.name")}</TableHead>
- <TableHead>{t("release.files")}</TableHead>
- <TableHead className="w-32">{t("common.created-at")}</TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {releases.map((release) => (
- <ReleaseRow key={release.name} release={release} />
- ))}
- </TableBody>
- </Table>
- </div>
- );
-}
+const resolveReleasePlanUrl = (plan: Plan, projectId: string): string =>
+ router.resolve({
+ name: plan.hasRollout
+ ? PROJECT_V1_ROUTE_PLAN_ROLLOUT
+ : PROJECT_V1_ROUTE_PLAN_DETAIL,
+ params: { projectId, planId: extractPlanUID(plan.name) },
+ }).fullPath;
-// ---------------------------------------------------------------------------
-// ReleaseRow
-// ---------------------------------------------------------------------------
+// Each distinct release is fetched once per page; a failed fetch is not retried
+// and its row shows "-".
+function useFetchReleases(releaseNames: string[]) {
+ const fetchRelease = useAppStore((s) => s.fetchRelease);
+ const [failed] = useState(() => new Set<string>());
+ const key = [...new Set(releaseNames)].sort().join(",");
+ useEffect(() => {
+ if (!key) return;
+ const { releasesByName } = useAppStore.getState();
+ for (const name of key.split(",")) {
+ if (releasesByName[name] || failed.has(name)) continue;
+ fetchRelease(name, /* silent */ true).catch(() => failed.add(name));
+ }
+ }, [key, fetchRelease, failed]);
+}
-function ReleaseRow({ release }: { release: Release }) {
+function useReleaseColumns(isMobile: boolean): PlanColumn[] {
const { t } = useTranslation();
- const isDeleted = release.state === State.DELETED;
-
- const releaseName = useMemo(() => {
- const parts = release.name.split("/");
- return parts[parts.length - 1] || release.name;
- }, [release.name]);
-
- const showFiles = release.files.slice(0, MAX_SHOW_FILES_COUNT);
-
- const createTimeMs = getTimeForPbTimestampProtoEs(release.createTime);
-
- const url = `/${release.name}`;
-
- const onRowClick = useCallback(
- (e: React.MouseEvent) => {
- if (e.ctrlKey || e.metaKey) {
- window.open(url, "_blank");
- } else {
- markListScrollRestorationEntry();
- router.push(url);
- }
- },
- [url]
+ return useMemo<PlanColumn[]>(
+ () => [
+ {
+ key: "release",
+ title: t("release.self"),
+ defaultWidth: isMobile ? 200 : 360,
+ minWidth: 200,
+ resizable: !isMobile,
+ render: (plan, ctx) => (
+ <div className="flex items-center gap-x-2 overflow-hidden">
+ <span className="truncate min-w-0">
+ {lastPathSegment(getPlanReleaseName(plan))}
+ </span>
+ <PlanLifecycleBadges ctx={ctx} />
+ </div>
+ ),
+ },
+ {
+ key: "source",
+ title: t("release.source"),
+ defaultWidth: 160,
+ minWidth: 120,
+ resizable: true,
+ render: (plan) => (
+ <ReleaseSourceCell releaseName={getPlanReleaseName(plan)} />
+ ),
+ },
+ createPlanStagesColumn(t),
+ {
+ key: "created",
+ title: t("common.created-at"),
+ defaultWidth: 152,
+ minWidth: 100,
+ resizable: true,
+ render: (_plan, ctx) =>
+ ctx.createTimeMs === undefined ? (
+ <span className="text-control-light">-</span>
+ ) : (
+ <HumanizeTs
+ tsMs={ctx.createTimeMs}
+ className="text-control-light whitespace-nowrap"
+ />
+ ),
+ },
+ ],
+ [t, isMobile]
);
+}
+const VCS_ICONS: Partial<Record<VCSType, string>> = {
+ [VCSType.GITHUB]: githubIcon,
+ [VCSType.GITLAB]: gitlabIcon,
+ [VCSType.BITBUCKET]: bitbucketIcon,
+ [VCSType.AZURE_DEVOPS]: azureDevOpsIcon,
+};
+
+function ReleaseSourceCell({ releaseName }: { releaseName: string }) {
+ const release = useAppStore((s) => s.releasesByName[releaseName]);
+ const url = release?.vcsSource?.url ?? "";
+ const commit = lastPathSegment(url);
+ if (!release || release.state === State.DELETED || !commit) {
+ return <span className="text-control-light">-</span>;
+ }
+ const icon =
+ VCS_ICONS[release.vcsSource?.vcsType ?? VCSType.VCS_TYPE_UNSPECIFIED];
return (
- <TableRow className="cursor-pointer" onClick={onRowClick}>
- <TableCell>
- <span
- className={cn(
- "truncate",
- isDeleted && "text-control-light line-through"
- )}
- >
- {releaseName}
- </span>
- </TableCell>
- <TableCell>
- <div className="flex flex-col items-start gap-1">
- {showFiles.map((file, idx) => (
- <p key={idx} className="w-full truncate">
- {file.version && (
- <span className="mr-2 inline-flex items-center rounded-xs border border-transparent bg-control-bg px-1.5 py-0.5 text-xs">
- {file.version}
- </span>
- )}
- {file.path}
- </p>
- ))}
- {release.files.length > MAX_SHOW_FILES_COUNT && (
- <p className="text-control-placeholder text-xs italic">
- {t("release.total-files", { count: release.files.length })}
- </p>
- )}
- </div>
- </TableCell>
- <TableCell>
- {createTimeMs === undefined ? "-" : <HumanizeTs tsMs={createTimeMs} />}
- </TableCell>
- </TableRow>
+ <a
+ href={url}
+ target="_blank"
+ rel="noopener noreferrer"
+ title={url}
+ className="inline-flex items-center gap-x-1 text-accent hover:underline"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {icon ? (
+ <img src={icon} alt="" className="size-4" />
+ ) : (
+ <GitCommitHorizontal className="size-4" />
+ )}
+ <span className="font-mono text-sm">{commit.slice(0, 7)}</span>
+ </a>
);
}
diff --git a/frontend/src/routes/project/ProjectReleaseDetailPage.tsx b/frontend/src/routes/project/ProjectReleaseDetailPage.tsx
deleted file mode 100644
index f02d5d6337..0000000000
--- a/frontend/src/routes/project/ProjectReleaseDetailPage.tsx
+++ /dev/null
@@ -1,279 +0,0 @@
-import { Clock4, EllipsisVertical, Link2, LoaderCircle } from "lucide-react";
-import { useEffect, useMemo, useState } from "react";
-import { useTranslation } from "react-i18next";
-import { HumanizeTs } from "@/components/HumanizeTs";
-import { ReleaseFileDetailPanel } from "@/components/release/ReleaseFileDetailPanel";
-import { ReleaseFileTable } from "@/components/release/ReleaseFileTable";
-import {
- AlertDialog,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogTitle,
-} from "@/components/ui/alert-dialog";
-import { Button } from "@/components/ui/button";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@/components/ui/dropdown-menu";
-import {
- Sheet,
- SheetBody,
- SheetContent,
- SheetHeader,
- SheetTitle,
-} from "@/components/ui/sheet";
-import { useProjectByName } from "@/hooks/useProjectByName";
-import { pushNotification } from "@/stores";
-import { useAppStore } from "@/stores/app";
-import { projectNamePrefix } from "@/stores/modules/v1/common";
-import { getTimeForPbTimestampProtoEs } from "@/types";
-import { State, VCSType } from "@/types/proto-es/v1/common_pb";
-import type { Release_File } from "@/types/proto-es/v1/release_service_pb";
-import { setDocumentTitle } from "@/utils";
-
-export function ProjectReleaseDetailPage({
- projectId,
- releaseId,
-}: {
- projectId: string;
- releaseId: string;
-}) {
- const { t } = useTranslation();
- const fetchRelease = useAppStore((state) => state.fetchRelease);
- const deleteRelease = useAppStore((state) => state.deleteRelease);
- const undeleteRelease = useAppStore((state) => state.undeleteRelease);
- const projectsByName = useAppStore((s) => s.projectsByName);
-
- const projectName = `${projectNamePrefix}${projectId}`;
- const releaseName = `${projectName}/releases/${releaseId}`;
-
- const release = useAppStore((state) => state.getReleaseByName(releaseName));
- // subscribe to re-render on project cache change
- void projectsByName;
- const project = useProjectByName(projectName);
- const [isLoading, setIsLoading] = useState(true);
-
- useEffect(() => {
- let cancelled = false;
- setIsLoading(true);
- void useAppStore
- .getState()
- .getOrFetchProjectByName(projectName)
- .catch((error) => {
- if (!cancelled) console.error("Failed to fetch project", error);
- });
- void fetchRelease(releaseName)
- .catch((error) => {
- if (!cancelled) console.error("Failed to fetch release", error);
- })
- .finally(() => {
- if (!cancelled) setIsLoading(false);
- });
- return () => {
- cancelled = true;
- };
- }, [fetchRelease, projectName, releaseName]);
-
- useEffect(() => {
- if (project?.title) {
- setDocumentTitle(t("release.releases"), project.title);
- }
- }, [project?.title, t]);
-
- const [selectedReleaseFile, setSelectedReleaseFile] = useState<
- Release_File | undefined
- >();
- const [archiveOpen, setArchiveOpen] = useState(false);
-
- const releaseDisplayName = useMemo(() => {
- const name = release?.name ?? releaseName;
- const parts = name.split("/");
- return parts[parts.length - 1] || name;
- }, [release?.name, releaseName]);
-
- if (!release) {
- return (
- <div className="flex flex-col items-start gap-y-4 p-4">
- <h1 className="text-xl font-medium truncate">{releaseDisplayName}</h1>
- {isLoading ? (
- <div className="flex w-full items-center justify-center py-10">
- <LoaderCircle className="h-4 w-4 animate-spin text-control-light" />
- </div>
- ) : (
- <div className="text-control-light">{t("release.not-found")}</div>
- )}
- </div>
- );
- }
-
- const isActive = release.state === State.ACTIVE;
- const isDeleted = release.state === State.DELETED;
-
- const handleArchive = async () => {
- try {
- await deleteRelease(release.name);
- } catch (error) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("common.error"),
- description: error instanceof Error ? error.message : String(error),
- });
- } finally {
- setArchiveOpen(false);
- }
- };
-
- const handleRestore = async () => {
- try {
- await undeleteRelease(release.name);
- } catch (error) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("common.error"),
- description: error instanceof Error ? error.message : String(error),
- });
- }
- };
-
- return (
- <div className="flex flex-col items-start gap-y-4 p-4 relative">
- {isDeleted && (
- <div className="h-8 w-full text-base font-medium bg-main-hover text-main-text flex justify-center items-center">
- {t("common.archived")}
- </div>
- )}
-
- <div className="w-full flex flex-row items-center justify-between gap-x-4">
- <div className="flex-1 p-0.5 overflow-hidden">
- <h1 className="text-xl font-medium truncate">{releaseDisplayName}</h1>
- </div>
- <div className="flex items-center justify-end gap-x-2">
- {(isActive || isDeleted) && (
- <DropdownMenu>
- <DropdownMenuTrigger
- className="inline-flex items-center justify-center rounded-xs p-1 text-control hover:bg-control-bg focus:outline-hidden"
- aria-label="More actions"
- >
- <EllipsisVertical className="size-4" />
- </DropdownMenuTrigger>
- <DropdownMenuContent>
- {isActive && (
- <DropdownMenuItem onClick={() => setArchiveOpen(true)}>
- {t("common.archive")}
- </DropdownMenuItem>
- )}
- {isDeleted && (
- <DropdownMenuItem onClick={handleRestore}>
- {t("common.restore")}
- </DropdownMenuItem>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
- )}
- </div>
- </div>
-
- <ReleaseBasicInfo
- createTimeMs={getTimeForPbTimestampProtoEs(release.createTime)}
- vcsType={release.vcsSource?.vcsType}
- vcsUrl={release.vcsSource?.url}
- />
-
- <ReleaseFileTable
- files={release.files}
- releaseType={release.type}
- showSelection={false}
- onRowClick={(file) => setSelectedReleaseFile(file)}
- />
-
- <Sheet
- open={!!selectedReleaseFile}
- onOpenChange={(next) => !next && setSelectedReleaseFile(undefined)}
- >
- <SheetContent width="wide">
- <SheetHeader>
- <SheetTitle>{t("release.file")}</SheetTitle>
- </SheetHeader>
- <SheetBody>
- {selectedReleaseFile && (
- <ReleaseFileDetailPanel releaseFile={selectedReleaseFile} />
- )}
- </SheetBody>
- </SheetContent>
- </Sheet>
-
- <AlertDialog
- open={archiveOpen}
- onOpenChange={(next) => setArchiveOpen(next)}
- >
- <AlertDialogContent>
- <AlertDialogTitle>{t("common.confirm-archive")}</AlertDialogTitle>
- <AlertDialogDescription>
- {t("common.archive-description", { name: releaseDisplayName })}
- </AlertDialogDescription>
- <AlertDialogFooter>
- <Button appearance="outline" onClick={() => setArchiveOpen(false)}>
- {t("common.cancel")}
- </Button>
- <Button onClick={handleArchive}>{t("common.confirm")}</Button>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
- );
-}
-
-// ---------------------------------------------------------------------------
-// ReleaseBasicInfo
-// ---------------------------------------------------------------------------
-
-function beautifyUrl(url: string): string {
- try {
- const parsed = new URL(url);
- return parsed.pathname.length > 0
- ? parsed.pathname.substring(1)
- : parsed.pathname;
- } catch {
- return url;
- }
-}
-
-function ReleaseBasicInfo({
- createTimeMs,
- vcsType,
- vcsUrl,
-}: {
- createTimeMs: number | undefined;
- vcsType: VCSType | undefined;
- vcsUrl: string | undefined;
-}) {
- const showVcs =
- vcsType !== undefined && vcsType !== VCSType.VCS_TYPE_UNSPECIFIED && vcsUrl;
-
- return (
- <div className="flex flex-row items-center pl-1 gap-4">
- <div className="flex items-center gap-1">
- <Clock4 className="size-4 text-control-light" />
- <HumanizeTs tsMs={createTimeMs} className="text-sm text-control" />
- </div>
- {showVcs && (
- <div className="flex flex-row items-center gap-1">
- <Link2 className="size-4 text-control-light" />
- <a
- href={vcsUrl}
- target="_blank"
- rel="noreferrer"
- className="text-sm text-accent hover:underline truncate"
- >
- {beautifyUrl(vcsUrl)}
- </a>
- </div>
- )}
- </div>
- );
-}
diff --git a/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx b/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx
index 21dc28e80d..7dc0b9018c 100644
--- a/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx
+++ b/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx
@@ -13,6 +13,7 @@ import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { useOnKeyChange } from "@/hooks/useOnKeyChange";
import { cn } from "@/lib/utils";
+import { useAppStore } from "@/stores/app";
import { ApprovalStatus, IssueStatus } from "@/types/proto-es/v1/common_pb";
import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
import { getRolloutStatus } from "@/utils";
@@ -119,6 +120,12 @@ function ProjectPlanDetailPageInner({
ready: page.ready,
specs: page.plan.specs,
});
+ const setViewedPlan = useAppStore((s) => s.setViewedPlan);
+ const isReleaseBacked = isReleaseBackedPlan(page.plan.specs);
+ useEffect(() => {
+ if (!page.ready) return;
+ setViewedPlan({ name: page.plan.name, isReleaseBacked });
+ }, [page.ready, page.plan.name, isReleaseBacked, setViewedPlan]);
// Route-driven spec changes reset during render, so the first paint after a
// Back/Forward or tab navigation already shows the destination spec. The
// keyed provider remounts this subtree when the plan itself changes.
diff --git a/frontend/src/routes/project/planListSearch.tsx b/frontend/src/routes/project/planListSearch.tsx
new file mode 100644
index 0000000000..95b81392da
--- /dev/null
+++ b/frontend/src/routes/project/planListSearch.tsx
@@ -0,0 +1,43 @@
+import type { TFunction } from "i18next";
+import type { ScopeOption } from "@/components/AdvancedSearch";
+import type { PlanStatusScopeValue } from "@/stores/app/plan";
+
+export const planStateScopeOption = (t: TFunction): ScopeOption => ({
+ id: "state",
+ title: t("common.state"),
+ description: t("issue.advanced-search.scope.state.description"),
+ options: [
+ {
+ value: "ACTIVE",
+ keywords: ["active", "ACTIVE"],
+ render: () => <span>{t("common.active")}</span>,
+ },
+ {
+ value: "DELETED",
+ keywords: ["deleted", "DELETED", "closed", "CLOSED"],
+ render: () => <span>{t("common.closed")}</span>,
+ },
+ ],
+});
+
+export const planStatusScopeOption = (t: TFunction): ScopeOption => {
+ const labels: Record<PlanStatusScopeValue, string> = {
+ FAILED: t("task.status.failed"),
+ RUNNING: t("task.status.running"),
+ WAITING: t("plan.status-scope.waiting"),
+ DONE: t("task.status.done"),
+ };
+ return {
+ id: "status",
+ title: t("common.status"),
+ description: t("plan.status-scope.description"),
+ allowMultiple: true,
+ options: (Object.entries(labels) as [PlanStatusScopeValue, string][]).map(
+ ([value, label]) => ({
+ value,
+ keywords: [value.toLowerCase(), label.toLowerCase()],
+ render: () => <span>{label}</span>,
+ })
+ ),
+ };
+};
diff --git a/frontend/src/stores/app/plan.test.ts b/frontend/src/stores/app/plan.test.ts
index bd8e039bff..d04df5de71 100644
--- a/frontend/src/stores/app/plan.test.ts
+++ b/frontend/src/stores/app/plan.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
import { describe, expect, test } from "vitest";
-import { buildPlanFilter } from "./plan";
+import { buildPlanFilter, buildPlanFindBySearchParams } from "./plan";
const QUOTED = 'SELECT * FROM "users"';
const ESCAPED = 'SELECT * FROM \\"users\\"';
@@ -15,3 +15,76 @@ describe("buildPlanFilter", () => {
expect(filter).toContain(ESCAPED.toLowerCase());
});
});
+
+describe("buildPlanFilter release and status filters", () => {
+ test("adds has_release, release, and task_status", () => {
+ expect(
+ buildPlanFilter({
+ project: "projects/p",
+ hasRelease: true,
+ release: "projects/p/releases/r1",
+ taskStatuses: ["FAILED", "PENDING"],
+ })
+ ).toBe(
+ 'has_release == true && release == "projects/p/releases/r1" && task_status in ["FAILED", "PENDING"]'
+ );
+ });
+
+ test("keeps has_release == false and skips an empty status list", () => {
+ expect(
+ buildPlanFilter({
+ project: "projects/p",
+ hasRelease: false,
+ taskStatuses: [],
+ })
+ ).toBe("has_release == false");
+ });
+});
+
+describe("buildPlanFindBySearchParams", () => {
+ test("maps status scopes to task statuses", () => {
+ const find = buildPlanFindBySearchParams({
+ query: "",
+ scopes: [
+ { id: "project", value: "p" },
+ { id: "status", value: "WAITING" },
+ { id: "status", value: "FAILED" },
+ { id: "status", value: "UNKNOWN" },
+ ],
+ });
+ expect(find.taskStatuses).toEqual(["NOT_STARTED", "PENDING", "FAILED"]);
+ });
+
+ test("counts skipped tasks as done", () => {
+ const find = buildPlanFindBySearchParams({
+ query: "",
+ scopes: [
+ { id: "project", value: "p" },
+ { id: "status", value: "DONE" },
+ ],
+ });
+ expect(find.taskStatuses).toEqual(["DONE", "SKIPPED"]);
+ });
+
+ test("reads the release and created scopes", () => {
+ const find = buildPlanFindBySearchParams(
+ {
+ query: "",
+ scopes: [
+ { id: "project", value: "p" },
+ { id: "release", value: "projects/p/releases/r1" },
+ { id: "created", value: "1000,2000" },
+ ],
+ },
+ { hasRelease: true }
+ );
+ expect(find).toMatchObject({
+ project: "projects/p",
+ hasRelease: true,
+ release: "projects/p/releases/r1",
+ createdTsAfter: 1000,
+ createdTsBefore: 2000,
+ });
+ expect(find.taskStatuses).toBeUndefined();
+ });
+});
diff --git a/frontend/src/stores/app/plan.ts b/frontend/src/stores/app/plan.ts
index e428b193d4..6494e3c3fd 100644
--- a/frontend/src/stores/app/plan.ts
+++ b/frontend/src/stores/app/plan.ts
@@ -9,6 +9,7 @@ import {
import {
getTsRangeFromSearchParams,
getValueFromSearchParams,
+ getValuesFromSearchParams,
type SearchParams,
} from "@/utils";
import { celString } from "@/utils/v1/celLiteral";
@@ -37,6 +38,17 @@ export const buildPlanFilter = (find: PlanFind): string => {
if (find.hasRollout !== undefined) {
filter.push(`has_rollout == ${find.hasRollout}`);
}
+ if (find.hasRelease !== undefined) {
+ filter.push(`has_release == ${find.hasRelease}`);
+ }
+ if (find.release) {
+ filter.push(`release == ${celString(find.release)}`);
+ }
+ if (find.taskStatuses && find.taskStatuses.length > 0) {
+ filter.push(
+ `task_status in [${find.taskStatuses.map(celString).join(", ")}]`
+ );
+ }
if (find.specType) {
filter.push(`spec_type == ${celString(find.specType)}`);
}
@@ -46,6 +58,20 @@ export const buildPlanFilter = (find: PlanFind): string => {
return filter.join(" && ");
};
+// The `status` scope groups Task.Status values into the stages a reader scans for.
+export const PLAN_STATUS_SCOPE_TASK_STATUSES = {
+ FAILED: ["FAILED"],
+ RUNNING: ["RUNNING"],
+ WAITING: ["NOT_STARTED", "PENDING"],
+ // A skipped task is finished, as in rollout completion.
+ DONE: ["DONE", "SKIPPED"],
+} as const satisfies Record<string, readonly string[]>;
+
+export type PlanStatusScopeValue = keyof typeof PLAN_STATUS_SCOPE_TASK_STATUSES;
+
+const isPlanStatusScopeValue = (value: string): value is PlanStatusScopeValue =>
+ Object.hasOwn(PLAN_STATUS_SCOPE_TASK_STATUSES, value);
+
export const buildPlanFindBySearchParams = (
params: SearchParams,
defaultFind?: Partial<PlanFind>
@@ -58,6 +84,12 @@ export const buildPlanFindBySearchParams = (
"DELETED",
]) as "ACTIVE" | "DELETED" | "";
+ const taskStatuses = uniq(
+ getValuesFromSearchParams(params, "status")
+ .filter(isPlanStatusScopeValue)
+ .flatMap((value) => PLAN_STATUS_SCOPE_TASK_STATUSES[value])
+ );
+
const filter: PlanFind = {
...defaultFind,
project: `projects/${projectScope || "-"}`,
@@ -65,12 +97,27 @@ export const buildPlanFindBySearchParams = (
createdTsAfter: createdTsRange?.[0],
createdTsBefore: createdTsRange?.[1],
creator: getValueFromSearchParams(params, "creator", "users/"),
+ release:
+ getValueFromSearchParams(params, "release") || defaultFind?.release,
+ taskStatuses:
+ taskStatuses.length > 0 ? taskStatuses : defaultFind?.taskStatuses,
state: state || defaultFind?.state,
};
return filter;
};
-export const createPlanSlice: AppSliceCreator<PlanSlice> = (_set, get) => ({
+export const createPlanSlice: AppSliceCreator<PlanSlice> = (set, get) => ({
+ viewedPlan: undefined,
+ setViewedPlan: (viewedPlan) => {
+ const current = get().viewedPlan;
+ if (
+ current?.name === viewedPlan.name &&
+ current.isReleaseBacked === viewedPlan.isReleaseBacked
+ ) {
+ return;
+ }
+ set({ viewedPlan });
+ },
listPlans: async ({ find, pageSize, pageToken }) => {
const { plans, nextPageToken } = await planServiceClientConnect.listPlans(
createProto(ListPlansRequestSchema, {
diff --git a/frontend/src/stores/app/types.ts b/frontend/src/stores/app/types.ts
index b290639873..e0b26aa445 100644
--- a/frontend/src/stores/app/types.ts
+++ b/frontend/src/stores/app/types.ts
@@ -1173,6 +1173,11 @@ export interface PlanFind {
createdTsAfter?: number;
createdTsBefore?: number;
hasRollout?: boolean;
+ // Whether any spec references a Release, which separates GitOps from ClickOps Plans.
+ hasRelease?: boolean;
+ release?: string;
+ // Task.Status names; a Plan matches when any task is in one of them.
+ taskStatuses?: string[];
specType?: string;
state?: "ACTIVE" | "DELETED";
}
@@ -1187,6 +1192,13 @@ export type PlanSlice = {
listPlans: (
params: ListPlanParams
) => Promise<{ plans: Plan[]; nextPageToken: string }>;
+ // The Plan last opened in Plan Detail, so the sidebar can highlight Releases
+ // for a GitOps Plan and Plans for a ClickOps Plan.
+ viewedPlan?: { name: string; isReleaseBacked: boolean };
+ setViewedPlan: (viewedPlan: {
+ name: string;
+ isReleaseBacked: boolean;
+ }) => void;
};
export type RolloutSlice = {
diff --git a/frontend/src/utils/v1/advanced-search/common.ts b/frontend/src/utils/v1/advanced-search/common.ts
index 492651154b..17dd33ac0f 100644
--- a/frontend/src/utils/v1/advanced-search/common.ts
+++ b/frontend/src/utils/v1/advanced-search/common.ts
@@ -34,6 +34,8 @@ export const AllSearchScopeIdList = [
"port",
// rollout related search scopes.
"stage",
+ // plan related search scopes.
+ "release",
] as const;
export type SearchScopeId =
diff --git a/frontend/tests/e2e/framework/api-client.ts b/frontend/tests/e2e/framework/api-client.ts
index 28db92df81..ee9ecd9beb 100644
--- a/frontend/tests/e2e/framework/api-client.ts
+++ b/frontend/tests/e2e/framework/api-client.ts
@@ -603,6 +603,7 @@ export class BytebaseApiClient {
// the real ids here rather than assuming the ids they would have chosen.
async getPlan(planName: string): Promise<{
name: string;
+ title: string;
hasRollout: boolean;
issue: string;
state: string;
@@ -614,6 +615,63 @@ export class BytebaseApiClient {
return this.request("GET", `/v1/${planName}`);
}
+ async listPlans(project: string, filter: string): Promise<{ name: string; title: string }[]> {
+ const resp = await this.request<{ plans?: { name: string; title: string }[] }>(
+ "GET",
+ `/v1/${project}/plans?pageSize=100&filter=${encodeURIComponent(filter)}`,
+ );
+ return resp.plans ?? [];
+ }
+
+ // A GitOps Plan: one change spec that references a release instead of a sheet.
+ async createReleasePlan(project: string, title: string, spec: { id: string; targets: string[]; release: string }): Promise<{ name: string }> {
+ return this.request<{ name: string }>("POST", `/v1/${project}/plans`, {
+ title,
+ specs: [{ id: spec.id, changeDatabaseConfig: { targets: spec.targets, release: spec.release } }],
+ });
+ }
+
+ // Releases
+ async createRelease(
+ project: string,
+ release: { files: { path: string; version: string; statement: string }[]; vcsSource: { vcsType: string; url: string } },
+ ): Promise<{ name: string }> {
+ return this.request<{ name: string }>("POST", `/v1/${project}/releases`, {
+ type: "VERSIONED",
+ files: release.files.map((f) => ({
+ path: f.path,
+ version: f.version,
+ statement: Buffer.from(f.statement).toString("base64"),
+ })),
+ vcsSource: release.vcsSource,
+ });
+ }
+
+ // Rollouts
+ async createRollout(planName: string): Promise<{ name: string }> {
+ return this.request<{ name: string }>("POST", `/v1/${planName}/rollout`, {});
+ }
+
+ async getRollout(planName: string): Promise<{ stages?: { name: string; tasks?: { name: string }[] }[] }> {
+ return this.request("GET", `/v1/${planName}/rollout`);
+ }
+
+ async batchRunTasks(stage: string, tasks: string[]): Promise<void> {
+ await this.request("POST", `/v1/${stage}/tasks:batchRun`, { tasks });
+ }
+
+ async closePlan(planName: string): Promise<void> {
+ await this.request("PATCH", `/v1/${planName}?updateMask=state`, { state: "DELETED" });
+ }
+
+ async deleteRelease(releaseName: string): Promise<void> {
+ await this.request("DELETE", `/v1/${releaseName}`);
+ }
+
+ async deleteProject(project: string): Promise<void> {
+ await this.request("DELETE", `/v1/${project}`);
+ }
+
async runPlanChecks(planName: string): Promise<void> {
try {
await this.request("POST", `/v1/${planName}:runPlanChecks`, {});
diff --git a/frontend/tests/e2e/plan-list/plan-list.spec.ts b/frontend/tests/e2e/plan-list/plan-list.spec.ts
new file mode 100644
index 0000000000..70700c00b4
--- /dev/null
+++ b/frontend/tests/e2e/plan-list/plan-list.spec.ts
@@ -0,0 +1,193 @@
+// Plans lists ClickOps Plans and Releases lists GitOps Plans (BYT-10019).
+// Setup goes through the API; the browser checks which list shows each Plan,
+// the status filter, the Releases row target, the setup empty state, and the
+// redirect from the retired release detail URL.
+
+import { expect, test } from "@playwright/test";
+import { BytebaseApiClient } from "../framework/api-client";
+import { loadTestEnv, type TestEnv } from "../framework/env";
+import {
+ seedDraftPlan,
+ setPermissiveGates,
+ waitForRollout,
+} from "../plan-detail/plan-helpers";
+
+test.setTimeout(180_000);
+
+const SCREENSHOT_DIR = process.env.BYTEBASE_E2E_SCREENSHOT_DIR;
+const COMMIT_URL = "https://github.com/acme/app/commit/0123456789abcdef";
+
+let env: TestEnv & { api: BytebaseApiClient };
+let projectId: string;
+let emptyProjectId: string;
+let failedPlan: { id: string; title: string };
+let draftPlan: { id: string; title: string };
+let gitOpsPlan: { id: string; title: string; releaseId: string };
+let originalProjectSettings: Record<string, boolean> = {};
+// Closed or archived in afterAll so later suites see the sample project as before.
+const createdPlans: string[] = [];
+let createdRelease: string | undefined;
+let createdProject: string | undefined;
+let originalApprovalSetting: unknown = null;
+
+const planId = (name: string) => name.split("/").pop()!;
+
+async function waitForFailedTask(planName: string): Promise<void> {
+ const deadline = Date.now() + 60_000;
+ while (Date.now() < deadline) {
+ const plans = await env.api.listPlans(env.project, 'task_status in ["FAILED"]');
+ if (plans.some((plan) => plan.name === planName)) return;
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ }
+ throw new Error(`no task of ${planName} failed within 60s`);
+}
+
+async function screenshot(page: import("@playwright/test").Page, name: string) {
+ if (SCREENSHOT_DIR) {
+ await page.screenshot({ path: `${SCREENSHOT_DIR}/${name}.png`, fullPage: true });
+ }
+}
+
+test.beforeAll(async () => {
+ env = loadTestEnv();
+ projectId = planId(env.project);
+ await env.api.login(env.adminEmail, env.adminPassword);
+ const ts = `${Date.now()}`;
+
+ const project = await env.api.getProject(env.project);
+ originalProjectSettings = {
+ requireIssueApproval: !!project.requireIssueApproval,
+ requirePlanCheckNoError: !!project.requirePlanCheckNoError,
+ enforceSqlReview: !!project.enforceSqlReview,
+ forceIssueLabels: !!project.forceIssueLabels,
+ };
+ originalApprovalSetting =
+ (await env.api.getSetting("WORKSPACE_APPROVAL"))?.value ?? null;
+ await setPermissiveGates(env.api, env.project);
+
+ // A ClickOps Plan whose task fails: the table does not exist.
+ const failedTitle = `plan-list failed ${ts}`;
+ const failedSheet = await env.api.createSheet(
+ env.project,
+ `ALTER TABLE plan_list_missing_${ts} ADD COLUMN c INT;`,
+ );
+ const failed = await env.api.createPlan(env.project, failedTitle, [
+ { id: `failed-${ts}`, targets: [env.database], sheet: failedSheet },
+ ]);
+ await env.api.createIssue(env.project, failedTitle, failed.name);
+ await waitForRollout(env.api, failed.name);
+ const rollout = await env.api.getRollout(failed.name);
+ for (const stage of rollout.stages ?? []) {
+ const tasks = (stage.tasks ?? []).map((task) => task.name);
+ await env.api.batchRunTasks(stage.name, tasks).catch(() => {});
+ }
+ createdPlans.push(failed.name);
+ await waitForFailedTask(failed.name);
+ failedPlan = { id: planId(failed.name), title: failedTitle };
+
+ // A ClickOps Plan still in draft review, so it has no tasks.
+ const draft = await seedDraftPlan(env.api, env.project, env.database, {
+ prefix: "plan-list draft",
+ sql: "SELECT 1;",
+ });
+ createdPlans.push(draft.planName);
+ draftPlan = {
+ id: draft.planId,
+ title: (await env.api.getPlan(draft.planName)).title,
+ };
+
+ // A GitOps Plan, as bytebase-action creates one.
+ const release = await env.api.createRelease(env.project, {
+ files: [
+ {
+ path: `migrations/0001_plan_list_${ts}.sql`,
+ version: "0001",
+ statement: `CREATE TABLE plan_list_gitops_${ts} (id INT);`,
+ },
+ ],
+ vcsSource: { vcsType: "GITHUB", url: COMMIT_URL },
+ });
+ createdRelease = release.name;
+ const gitOpsTitle = `plan-list gitops ${ts}`;
+ const gitOps = await env.api.createReleasePlan(env.project, gitOpsTitle, {
+ id: `gitops-${ts}`,
+ targets: [env.database],
+ release: release.name,
+ });
+ createdPlans.push(gitOps.name);
+ await env.api.createRollout(gitOps.name);
+ gitOpsPlan = {
+ id: planId(gitOps.name),
+ title: gitOpsTitle,
+ releaseId: release.name.split("/").pop()!,
+ };
+
+ emptyProjectId = `plan-list-empty-${ts}`;
+ createdProject = (
+ await env.api.createProject(emptyProjectId, `Plan list empty ${ts}`)
+ ).name;
+});
+
+test.afterAll(async () => {
+ await env.api.updateProjectSettings(env.project, originalProjectSettings);
+ if (originalApprovalSetting) {
+ await env.api.upsertSetting(
+ "WORKSPACE_APPROVAL",
+ originalApprovalSetting,
+ "value.workspace_approval",
+ );
+ }
+ for (const plan of createdPlans) {
+ await env.api.closePlan(plan);
+ }
+ if (createdRelease) {
+ await env.api.deleteRelease(createdRelease);
+ }
+ if (createdProject) {
+ await env.api.deleteProject(createdProject);
+ }
+});
+
+test("Plans lists only ClickOps Plans and filters them by status", async ({ page }) => {
+ await page.goto(`${env.baseURL}/projects/${projectId}/plans`);
+ const rows = page.getByTestId("plan-list-item");
+ await expect(rows.filter({ hasText: failedPlan.title })).toBeVisible();
+ await expect(rows.filter({ hasText: draftPlan.title })).toBeVisible();
+ await expect(rows.filter({ hasText: gitOpsPlan.title })).toHaveCount(0);
+ await screenshot(page, "plans");
+
+ await page.goto(
+ `${env.baseURL}/projects/${projectId}/plans?q=${encodeURIComponent("state:ACTIVE status:FAILED")}`,
+ );
+ await expect(rows.filter({ hasText: failedPlan.title })).toBeVisible();
+ await expect(rows.filter({ hasText: draftPlan.title })).toHaveCount(0);
+ await screenshot(page, "plans-status-failed");
+});
+
+test("Releases lists GitOps Plans and opens a row's rollout", async ({ page }) => {
+ await page.goto(`${env.baseURL}/projects/${projectId}/releases`);
+ const rows = page.getByTestId("plan-list-item");
+ const row = rows.filter({ hasText: gitOpsPlan.releaseId });
+ await expect(row).toBeVisible();
+ await expect(row.locator(`a[href="${COMMIT_URL}"]`)).toHaveText("0123456");
+ await expect(rows.filter({ hasText: failedPlan.title })).toHaveCount(0);
+ await expect(page.getByTestId("release-gitops-setup")).toBeVisible();
+ await screenshot(page, "releases");
+
+ await row.click();
+ await page.waitForURL(`**/projects/${projectId}/plans/${gitOpsPlan.id}/rollout`);
+});
+
+test("Releases shows the setup empty state for a project without GitOps Plans", async ({ page }) => {
+ await page.goto(`${env.baseURL}/projects/${emptyProjectId}/releases`);
+ await expect(page.getByTestId("release-setup-empty-state")).toBeVisible();
+ await expect(page.getByTestId("release-gitops-setup")).toHaveCount(0);
+ await screenshot(page, "releases-empty");
+});
+
+test("an old release detail URL opens the Plan that used the release", async ({ page }) => {
+ await page.goto(
+ `${env.baseURL}/projects/${projectId}/releases/${gitOpsPlan.releaseId}`,
+ );
+ await page.waitForURL(`**/projects/${projectId}/plans/${gitOpsPlan.id}/rollout`);
+});