Skip to content

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

feat(plan): add target-derived change references (#21016)

boojack94dc8cb3f2ea
diff --git a/docs/plans/2026-07-24-byt-9805-plan-change-reference-implementation.md b/docs/plans/2026-07-24-byt-9805-plan-change-reference-implementation.md
new file mode 100644
index 0000000000..e9c09d0787
--- /dev/null
+++ b/docs/plans/2026-07-24-byt-9805-plan-change-reference-implementation.md
@@ -0,0 +1,186 @@
+# BYT-9805 Plan Change Reference Implementation
+
+## Goal
+
+Replace generic Plan Detail change labels such as `1. Database Change` with
+readable, target-derived references ordered as optional disambiguating change
+number, type icon, and computed title, while keeping `spec.id` as the only
+stable identity for selection, navigation, and React keys.
+
+## Scope
+
+This implementation is frontend-only and owned by the Plan Detail route.
+
+In scope:
+
+- The Plan Detail Changes tab strip.
+- Plan-update activity in Issue Detail comments and the Plan Detail review
+ timeline.
+- Target-derived labels for change, export, create-database, release-backed,
+ empty, and partially resolvable specs.
+- Environment and instance qualifiers when cached resource data is available.
+- Width-aware fallback from database names to a database-count summary.
+- Accessible full labels and route-local tests.
+
+Out of scope:
+
+- Backend or protobuf changes.
+- User-authored change titles.
+- Backend-provided identity factors.
+- SQL Review result attribution, which still requires the originating
+ `spec.id` contract tracked separately.
+- Other activity/history surfaces that do not render plan-update issue
+ comments.
+
+## Design
+
+### Route-local ownership
+
+Add the implementation under
+`frontend/src/routes/project/plan-detail/`:
+
+- `utils/changeReference.ts` derives a structured reference from a spec, its
+ siblings, and currently loaded resources.
+- `hooks/usePlanChangeReferenceData.ts` performs one deduplicated resource
+ hydration pass for all visible specs.
+- `components/PlanChangeReference.tsx` renders the compact visual reference.
+
+Plan-update issue comments reuse this Plan Detail-owned implementation through
+a renderer callback on the shared issue-activity component. This keeps the
+shared activity renderer independent of route code while allowing Issue Detail
+and Plan Review to render the same change identity. Activity references derive
+their index and title from the event's before/after spec snapshots, while links
+continue to use the live plan and `spec.id`.
+
+### Identity contract
+
+- Stable identity: `spec.id`.
+- Display identity: type icon and derived label, plus a one-based change number
+ only when the final visible references would otherwise collide.
+- Display labels are never persisted or used as keys.
+- Resource hydration may improve a label but must not change selection or
+ navigation identity.
+- Historical activity uses event snapshots for display identity and the live
+ plan only to determine whether a spec link remains valid.
+- Surviving activity references link to the canonical spec detail route.
+ Deleted changes remain plain text because their historical `spec.id` has no
+ corresponding live change.
+
+### Derivation rules
+
+1. Database group: use the group resource ID.
+2. One database: use the database name.
+3. Several databases: produce both a full name list and a count-based option.
+ The renderer uses the list when it fits and the count otherwise.
+4. Create database: use the new database name.
+5. Export and release-backed changes: use the same target rules with the
+ appropriate type icon.
+6. Empty draft: use localized `New change`.
+7. Missing target: use the last readable resource segment, then the raw target,
+ then a short `spec.id`.
+8. Duplicate sibling labels: add environment, then instance when those values
+ distinguish the siblings. Identical target sets remain distinguishable by
+ the change number.
+
+For multi-environment batches, list the environment that deploys last and the
+remaining environment count. This follows configured environment order and
+does not imply risk.
+
+### Data loading
+
+- Render an immediate zero-fetch label from resource strings.
+- Batch direct database targets through the app store.
+- Deduplicate database-group requests, expand their cached members, and batch
+ those databases for qualifiers.
+- Treat enrichment failures as non-blocking; retain the base label and keep
+ both database and nested project hydration silent.
+
+### Layout and accessibility
+
+- Bound each label so a long change cannot dominate the horizontal strip.
+- Keep each Change tab between 160px and 256px, including its optional action,
+ so short labels retain a stable hit target and the widest and narrowest tabs
+ differ by at most 96px. Within that tab, measure the title's actual available
+ width before deciding whether it overflows.
+- Keep inline activity references at no more than 320px.
+- Render the type icon and computed title by default. When an index is required
+ for disambiguation, render it before the icon.
+- In issue activity sentences, keep the localized `Change` noun before the
+ icon and computed title. The Plan tab uses only the compact identity.
+- Keep activity links visually neutral at rest. Reveal accent link color and
+ an underline only on hover or keyboard focus.
+- Keep the change number on the same baseline and at the same 14px scale as the
+ title. Use tabular numerals, placeholder color, and normal weight to lower its
+ emphasis without making it look detached. Do not use a badge, background, or
+ border that competes with the title.
+- Detect full-title and width-dependent database-count collisions separately,
+ so an index appears only for the label currently being rendered. Different
+ type icons are sufficient disambiguation and do not require an index.
+- Keep the type icon at the secondary text color and make the computed title the
+ visual subject; inline activity references use main text with medium weight.
+- Fall back from a multi-database name list to the count option on overflow.
+- Keep the full-label measurement layer clipped and in flow so it preserves the
+ available title width without expanding the tab strip's scrollable area.
+ Re-evaluate that stable layer on resize so a count fallback returns to the
+ full label when space becomes available.
+- Preserve the meaningful suffix of a long single name with a grapheme-safe
+ middle ellipsis. Apply the same behavior if a count label or qualifier is
+ itself too long.
+- Put the complete localized reference on the tab's accessible name and
+ show the structured tooltip only when the visible reference overflows.
+ Short, fully visible references do not add a redundant tooltip.
+- Format the tooltip as a compact change header, complete wrapping title, and
+ multi-target summary. Cap it at 384px (or the viewport width minus 16px) so
+ full information remains readable without creating an unbounded overlay.
+
+## Tests
+
+Add unit coverage for:
+
+- Database group, one database, multi-database, create, export,
+ release-backed, empty, and malformed inputs.
+- Duplicate labels with environment and instance disambiguation.
+- Environment deployment ordering.
+- Unicode-safe middle splitting.
+- Density-specific maximum widths and complete, untruncated tooltip content.
+- Partial and failed resource hydration with base-label fallback.
+- Full-label remeasurement after an overflowing reference or its container
+ width changes, without adding hidden horizontal overflow.
+- Indexes omitted for distinct references and shown only for collisions,
+ including equal count fallbacks.
+- Activity events use the `toSpecs` snapshot for SQL and target updates and the
+ `fromSpecs` snapshot for removed changes.
+
+Update `PlanDetailChangesBranch.test.tsx` to verify:
+
+- Generic `Database Change` labels are replaced with target-derived labels.
+- Same-target changes remain distinct by number.
+- Pending drafts and target edits update the display without changing the
+ selected `spec.id`.
+- Resource loading is deduplicated across the visible spec list.
+
+Update issue-activity tests to verify:
+
+- SQL updates replace the generic `Change` chip with the computed reference.
+- Target updates derive the title from the new target.
+- Removed changes retain their historical index and target title.
+- Surviving changes link to their canonical spec detail route, including from
+ the Plan review timeline; removed changes do not render a link.
+
+## Verification
+
+Run:
+
+```bash
+pnpm -C frontend exec vitest run \
+ src/components/issue-activity/IssueCommentActivity.test.tsx \
+ src/routes/project/plan-detail/utils/changeReference.test.ts \
+ src/routes/project/plan-detail/components/PlanChangeReference.test.tsx \
+ src/routes/project/plan-detail/components/PlanDetailChangesBranch.test.tsx \
+ src/routes/project/plan-detail/components/review/ReviewActivityTimeline.test.tsx
+pnpm --dir frontend fix
+pnpm --dir frontend check
+pnpm --dir frontend type-check
+pnpm --dir frontend test
+git diff --check
+```
diff --git a/frontend/src/app/router/routeHelpers.ts b/frontend/src/app/router/routeHelpers.ts
index 0ccfdba9b6..1239d31d70 100644
--- a/frontend/src/app/router/routeHelpers.ts
+++ b/frontend/src/app/router/routeHelpers.ts
@@ -79,6 +79,18 @@ export const buildSpecDetailRouteForCurrentPage = (
},
});
+export const buildSpecDetailRouteFromPlanName = (
+ planName: string,
+ specId: string
+): RouteTarget => ({
+ name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
+ params: {
+ projectId: extractProjectResourceName(planName),
+ planId: extractPlanUID(planName) || "_",
+ specId,
+ },
+});
+
export const buildPlanRolloutRouteFromPlanName = (
planName: string
): RouteTarget =>
diff --git a/frontend/src/components/issue-activity/IssueCommentActivity.test.tsx b/frontend/src/components/issue-activity/IssueCommentActivity.test.tsx
index 6324c2f23e..2208c8d331 100644
--- a/frontend/src/components/issue-activity/IssueCommentActivity.test.tsx
+++ b/frontend/src/components/issue-activity/IssueCommentActivity.test.tsx
@@ -1,14 +1,21 @@
import { create } from "@bufbuild/protobuf";
import { render, screen } from "@testing-library/react";
+import type { AnchorHTMLAttributes, ReactNode } from "react";
import { describe, expect, test, vi } from "vitest";
+import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/app/router/handles";
import {
+ IssueComment_PlanUpdateSchema,
Issue_Type,
IssueComment_ReviewSubmissionSchema,
IssueCommentSchema,
IssueSchema,
IssueStatus,
} from "@/types/proto-es/v1/issue_service_pb";
-import { PlanSchema } from "@/types/proto-es/v1/plan_service_pb";
+import {
+ Plan_ChangeDatabaseConfigSchema,
+ Plan_SpecSchema,
+ PlanSchema,
+} from "@/types/proto-es/v1/plan_service_pb";
import {
getIssueCommentType,
IssueCommentType,
@@ -18,10 +25,15 @@ import { IssueCommentRow } from "./IssueCommentActivity";
vi.mock("react-i18next", async (importOriginal) => ({
...(await importOriginal<typeof import("react-i18next")>()),
useTranslation: () => ({
- t: (key: string) =>
- key === "plan.review.activity.marked-ready-for-review"
- ? "marked this plan ready for review"
- : key,
+ t: (key: string) => {
+ if (key === "plan.review.activity.marked-ready-for-review") {
+ return "marked this plan ready for review";
+ }
+ if (key === "plan.spec.change") {
+ return "Change";
+ }
+ return key;
+ },
}),
}));
@@ -54,6 +66,27 @@ vi.mock("@/components/UserAvatar", () => ({
UserAvatar: () => <span data-testid="user-avatar" />,
}));
+vi.mock("@/components/RouterLink", () => ({
+ RouterLink: ({
+ children,
+ preventScrollReset,
+ to,
+ ...props
+ }: AnchorHTMLAttributes<HTMLAnchorElement> & {
+ children: ReactNode;
+ preventScrollReset?: boolean;
+ to: unknown;
+ }) => (
+ <a
+ {...props}
+ data-prevent-scroll-reset={preventScrollReset || undefined}
+ data-to={JSON.stringify(to)}
+ >
+ {children}
+ </a>
+ ),
+}));
+
const reviewSubmission = create(IssueCommentSchema, {
name: "projects/p1/issues/1/issueComments/1",
creator: "users/[email protected]",
@@ -63,6 +96,26 @@ const reviewSubmission = create(IssueCommentSchema, {
},
});
+const changeSpec = ({
+ id = "spec-1",
+ sheet,
+ target,
+}: {
+ id?: string;
+ sheet: string;
+ target: string;
+}) =>
+ create(Plan_SpecSchema, {
+ id,
+ config: {
+ case: "changeDatabaseConfig",
+ value: create(Plan_ChangeDatabaseConfigSchema, {
+ sheet,
+ targets: [`instances/instance-1/databases/${target}`],
+ }),
+ },
+ });
+
describe("IssueCommentRow", () => {
test("shows who bypassed review and created the rollout", () => {
const issue = create(IssueSchema, {
@@ -112,4 +165,161 @@ describe("IssueCommentRow", () => {
expect(container.querySelectorAll(".lucide-send")).toHaveLength(1);
expect(container.querySelector("[data-testid='user-avatar']")).toBeNull();
});
+
+ test("links a computed change reference from the plan timeline", () => {
+ const fromSpec = changeSpec({
+ sheet: "sheets/1",
+ target: "orders",
+ });
+ const toSpec = changeSpec({
+ sheet: "sheets/2",
+ target: "orders",
+ });
+ const comment = create(IssueCommentSchema, {
+ creator: "users/[email protected]",
+ event: {
+ case: "planUpdate",
+ value: create(IssueComment_PlanUpdateSchema, {
+ fromSpecs: [fromSpec],
+ toSpecs: [toSpec],
+ }),
+ },
+ });
+
+ render(
+ <IssueCommentRow
+ comment={comment}
+ isLast
+ linkless
+ plan={create(PlanSchema, {
+ name: "projects/p1/plans/1",
+ specs: [toSpec],
+ })}
+ renderPlanChangeReference={({ siblings, spec }) => (
+ <span data-testid="change-reference">
+ {siblings.indexOf(spec) + 1}{" "}
+ {spec.config.case === "changeDatabaseConfig"
+ ? spec.config.value.targets[0].split("/").at(-1)
+ : ""}
+ </span>
+ )}
+ />
+ );
+
+ expect(
+ screen.getByText("activity.sentence.modified-sql-of")
+ ).toBeInTheDocument();
+ const reference = screen.getByTestId("change-reference");
+ expect(reference).toHaveTextContent("1 orders");
+ expect(screen.getByText("Change")).toHaveAttribute("aria-hidden", "true");
+ const link = reference.closest("a");
+ expect(JSON.parse(link?.dataset.to ?? "")).toEqual({
+ name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
+ params: {
+ planId: "1",
+ projectId: "p1",
+ specId: "spec-1",
+ },
+ });
+ expect(link).toHaveClass(
+ "text-main",
+ "hover:text-accent",
+ "hover:underline"
+ );
+ expect(link).not.toHaveAttribute("data-prevent-scroll-reset");
+ });
+
+ test("uses the new target in a changed-targets reference", () => {
+ const fromSpec = changeSpec({
+ sheet: "sheets/1",
+ target: "orders",
+ });
+ const toSpec = changeSpec({
+ sheet: "sheets/1",
+ target: "employees",
+ });
+ const comment = create(IssueCommentSchema, {
+ creator: "users/[email protected]",
+ event: {
+ case: "planUpdate",
+ value: create(IssueComment_PlanUpdateSchema, {
+ fromSpecs: [fromSpec],
+ toSpecs: [toSpec],
+ }),
+ },
+ });
+
+ render(
+ <IssueCommentRow
+ comment={comment}
+ isLast
+ plan={create(PlanSchema, {
+ name: "projects/p1/plans/1",
+ specs: [toSpec],
+ })}
+ renderPlanChangeReference={({ spec }) => (
+ <span data-testid="change-reference">
+ {spec.config.case === "changeDatabaseConfig"
+ ? spec.config.value.targets[0].split("/").at(-1)
+ : ""}
+ </span>
+ )}
+ />
+ );
+
+ expect(
+ screen.getByText("activity.sentence.changed-targets-of")
+ ).toBeInTheDocument();
+ const reference = screen.getByTestId("change-reference");
+ expect(reference).toHaveTextContent("employees");
+ expect(reference.closest("a")).not.toHaveAttribute(
+ "data-prevent-scroll-reset"
+ );
+ });
+
+ test("uses the historical index and target for a removed change", () => {
+ const remainingSpec = changeSpec({
+ sheet: "sheets/1",
+ target: "orders",
+ });
+ const removedSpec = changeSpec({
+ id: "spec-2",
+ sheet: "sheets/2",
+ target: "employees",
+ });
+ const comment = create(IssueCommentSchema, {
+ creator: "users/[email protected]",
+ event: {
+ case: "planUpdate",
+ value: create(IssueComment_PlanUpdateSchema, {
+ fromSpecs: [remainingSpec, removedSpec],
+ toSpecs: [remainingSpec],
+ }),
+ },
+ });
+
+ render(
+ <IssueCommentRow
+ comment={comment}
+ isLast
+ plan={create(PlanSchema, {
+ name: "projects/p1/plans/1",
+ specs: [remainingSpec],
+ })}
+ renderPlanChangeReference={({ siblings, spec }) => (
+ <span data-testid="change-reference">
+ {siblings.indexOf(spec) + 1}{" "}
+ {spec.config.case === "changeDatabaseConfig"
+ ? spec.config.value.targets[0].split("/").at(-1)
+ : ""}
+ </span>
+ )}
+ />
+ );
+
+ expect(screen.getByText("activity.sentence.removed-spec")).toBeVisible();
+ const reference = screen.getByTestId("change-reference");
+ expect(reference).toHaveTextContent("2 employees");
+ expect(reference.closest("a")).toBeNull();
+ });
});
diff --git a/frontend/src/components/issue-activity/IssueCommentActivity.tsx b/frontend/src/components/issue-activity/IssueCommentActivity.tsx
index 3214f67a18..7dc96f7d56 100644
--- a/frontend/src/components/issue-activity/IssueCommentActivity.tsx
+++ b/frontend/src/components/issue-activity/IssueCommentActivity.tsx
@@ -5,8 +5,10 @@
import { Loader2, Send } from "lucide-react";
import { Fragment, type ReactNode, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
-import { router } from "@/app/router";
-import { buildPlanRolloutRouteFromPlanName } from "@/app/router/routeHelpers";
+import {
+ buildPlanRolloutRouteFromPlanName,
+ buildSpecDetailRouteFromPlanName,
+} from "@/app/router/routeHelpers";
import { HumanizeTs } from "@/components/HumanizeTs";
import {
type ActivityIconSpec,
@@ -55,13 +57,21 @@ interface ActivityProps {
issue?: Issue;
plan?: Plan;
comment: IssueComment;
- // When true (the plan-detail review timeline, which already sits on the
- // plan), spec/plan references render as plain text instead of links — the
- // links would only redirect to the page you're already on (BYT-9710). The
- // issue-detail page leaves this off so its navigation links stay.
+ // When true, plan and rollout references render as plain text in the
+ // plan-detail review timeline. Surviving change references still link to
+ // their canonical spec detail route.
linkless?: boolean;
+ renderPlanChangeReference?: PlanChangeReferenceRenderer;
}
+export type PlanChangeReferenceRenderer = ({
+ siblings,
+ spec,
+}: {
+ siblings: Plan_Spec[];
+ spec: Plan_Spec;
+}) => ReactNode;
+
// A DONE issue-update that created the rollout for a database-change plan — the
// timeline renders this as a "review done, rollout created" line rather than a
// plain "resolved issue".
@@ -183,6 +193,7 @@ function IssueCommentHeader({
issue,
linkless,
plan,
+ renderPlanChangeReference,
similarCount,
}: ActivityProps & { similarCount?: number }) {
const { t } = useTranslation();
@@ -204,6 +215,7 @@ function IssueCommentHeader({
issue={issue}
linkless={linkless}
plan={plan}
+ renderPlanChangeReference={renderPlanChangeReference}
/>
{similarCount !== undefined && similarCount > 1 && (
<Badge className="px-2 text-xs" variant="default">
@@ -229,6 +241,7 @@ export function IssueCommentRow({
issue,
linkless,
plan,
+ renderPlanChangeReference,
similarCount,
subjectSuffix,
}: ActivityProps & {
@@ -246,6 +259,7 @@ export function IssueCommentRow({
issue={issue}
linkless={linkless}
plan={plan}
+ renderPlanChangeReference={renderPlanChangeReference}
similarCount={similarCount}
/>
}
@@ -398,6 +412,7 @@ function IssueCommentActionSentence({
plan,
comment,
linkless,
+ renderPlanChangeReference,
}: ActivityProps) {
const { t } = useTranslation();
const commentType = getIssueCommentType(comment);
@@ -539,6 +554,7 @@ function IssueCommentActionSentence({
commentType === IssueCommentType.PLAN_UPDATE &&
comment.event.case === "planUpdate"
) {
+ const { fromSpecs, toSpecs } = comment.event.value;
const entries = diffPlanSpecsForEvent(comment.event.value);
if (entries.length === 0) return null;
if (entries.length === 1) {
@@ -548,6 +564,8 @@ function IssueCommentActionSentence({
linkless={linkless}
multi={false}
plan={plan}
+ referenceSpecs={entries[0].kind === "removed" ? fromSpecs : toSpecs}
+ renderPlanChangeReference={renderPlanChangeReference}
/>
);
}
@@ -560,6 +578,8 @@ function IssueCommentActionSentence({
linkless={linkless}
multi
plan={plan}
+ referenceSpecs={entry.kind === "removed" ? fromSpecs : toSpecs}
+ renderPlanChangeReference={renderPlanChangeReference}
/>
))}
</div>
@@ -574,11 +594,15 @@ function SpecDiffRow({
linkless,
multi,
plan,
+ referenceSpecs,
+ renderPlanChangeReference,
}: {
entry: SpecDiffEntry;
linkless?: boolean;
multi?: boolean;
plan?: Plan;
+ referenceSpecs: Plan_Spec[];
+ renderPlanChangeReference?: PlanChangeReferenceRenderer;
}) {
const { t } = useTranslation();
const planName = plan?.name ?? "";
@@ -588,6 +612,10 @@ function SpecDiffRow({
<SpecChangeRow
linkless={linkless}
plan={plan}
+ reference={renderPlanChangeReference?.({
+ siblings: referenceSpecs,
+ spec: entry.spec,
+ })}
showIndex={multi}
specRef={specResourceName(planName, entry.spec)}
>
@@ -601,6 +629,10 @@ function SpecDiffRow({
<SpecChangeRow
linkless={linkless}
plan={plan}
+ reference={renderPlanChangeReference?.({
+ siblings: referenceSpecs,
+ spec: entry.spec,
+ })}
showIndex={multi}
specRef={specResourceName(planName, entry.spec)}
>
@@ -672,6 +704,10 @@ function SpecDiffRow({
<SpecChangeRow
linkless={linkless}
plan={plan}
+ reference={renderPlanChangeReference?.({
+ siblings: referenceSpecs,
+ spec: entry.to,
+ })}
showIndex={multi}
specRef={specResourceName(planName, entry.to)}
>
@@ -692,6 +728,10 @@ function SpecDiffRow({
<SpecChangeRow
linkless={linkless}
plan={plan}
+ reference={renderPlanChangeReference?.({
+ siblings: referenceSpecs,
+ spec: entry.to,
+ })}
showIndex={multi}
specRef={specResourceName(planName, entry.to)}
trailing={trailingItems.length > 0 ? <>{trailingItems}</> : null}
@@ -709,6 +749,7 @@ function SpecChangeRow({
children,
linkless,
plan,
+ reference,
showIndex,
specRef,
trailing,
@@ -716,6 +757,7 @@ function SpecChangeRow({
children: ReactNode;
linkless?: boolean;
plan?: Plan;
+ reference?: ReactNode;
showIndex?: boolean;
specRef: string;
trailing?: ReactNode;
@@ -727,17 +769,10 @@ function SpecChangeRow({
const specId = specInfo?.specId ?? specIdFromRef;
const specIdShort = specId.slice(0, 8);
// Only link to specs that still exist in the live plan — otherwise the spec
- // view would silently bounce back to specs[0]. On the plan-detail timeline
- // (linkless) we're already on the plan, so the link would just re-navigate to
- // the current page and the id slice is meaningless noise — render plain text.
+ // view would silently bounce back to specs[0].
const specRoute =
- !linkless && specInfo?.specId
- ? {
- query: {
- ...router.currentRoute.value.query,
- spec: specInfo.specId,
- },
- }
+ plan?.name && specInfo?.specId
+ ? buildSpecDetailRouteFromPlanName(plan.name, specInfo.specId)
: null;
// On the plan-detail timeline (linkless) we identify the change by its 1-based
@@ -767,25 +802,35 @@ function SpecChangeRow({
);
}
- const chip = (
+ const fallbackChip = (
<span className="inline-flex items-center gap-1">
{t("plan.spec.change")}
{chipSuffix}
</span>
);
+ const chip = reference ? (
+ <span className="inline-flex items-center gap-1">
+ <span aria-hidden="true">{t("plan.spec.change")}</span>
+ {reference}
+ </span>
+ ) : (
+ fallbackChip
+ );
return (
<span className="inline-flex items-center gap-1 whitespace-nowrap text-gray-600">
{children}{" "}
{specRoute != null ? (
<RouterLink
- className="inline-flex items-center gap-1 hover:underline"
+ className="inline-flex min-w-0 items-center gap-1 text-main transition-colors hover:text-accent hover:underline focus-visible:text-accent focus-visible:underline focus-visible:outline-hidden"
to={specRoute}
>
{chip}
</RouterLink>
) : (
- chip
+ <span className="inline-flex min-w-0 items-center gap-1 text-main">
+ {chip}
+ </span>
)}
{trailing != null ? <> {trailing}</> : null}
</span>
diff --git a/frontend/src/components/ui/tooltip.test.tsx b/frontend/src/components/ui/tooltip.test.tsx
index 107965882b..d80785727a 100644
--- a/frontend/src/components/ui/tooltip.test.tsx
+++ b/frontend/src/components/ui/tooltip.test.tsx
@@ -21,7 +21,7 @@ describe("Tooltip", () => {
act(() => {
root.render(
- <Tooltip content="Tip content">
+ <Tooltip content="Tip content" popupClassName="max-w-96">
<button type="button">Trigger</button>
</Tooltip>
);
@@ -38,6 +38,9 @@ describe("Tooltip", () => {
const overlayRoot = document.getElementById("bb-react-layer-overlay");
expect(overlayRoot).toBeInstanceOf(HTMLDivElement);
expect(overlayRoot?.textContent).toContain("Tip content");
+ expect(overlayRoot?.querySelector(".max-w-96")).toBeInstanceOf(
+ HTMLDivElement
+ );
act(() => {
root.unmount();
diff --git a/frontend/src/components/ui/tooltip.tsx b/frontend/src/components/ui/tooltip.tsx
index 040ef534ef..47d1c2c037 100644
--- a/frontend/src/components/ui/tooltip.tsx
+++ b/frontend/src/components/ui/tooltip.tsx
@@ -1,5 +1,6 @@
import { Tooltip as BaseTooltip } from "@base-ui/react/tooltip";
import type { ReactNode } from "react";
+import { cn } from "@/lib/utils";
import { getLayerRoot, LAYER_SURFACE_CLASS } from "./layer";
interface TooltipProps {
@@ -7,6 +8,7 @@ interface TooltipProps {
readonly children: ReactNode;
readonly side?: "top" | "bottom" | "left" | "right";
readonly delayDuration?: number;
+ readonly popupClassName?: string;
}
export function Tooltip({
@@ -14,6 +16,7 @@ export function Tooltip({
children,
side = "top",
delayDuration = 100,
+ popupClassName,
}: TooltipProps) {
if (!content) {
return <>{children}</>;
@@ -31,7 +34,12 @@ export function Tooltip({
sideOffset={4}
className={LAYER_SURFACE_CLASS}
>
- <BaseTooltip.Popup className="max-w-56 rounded-sm bg-main px-2.5 py-1.5 text-xs text-main-text shadow-md">
+ <BaseTooltip.Popup
+ className={cn(
+ "max-w-56 rounded-sm bg-main px-2.5 py-1.5 text-xs text-main-text shadow-md",
+ popupClassName
+ )}
+ >
{content}
<BaseTooltip.Arrow className="fill-main" />
</BaseTooltip.Popup>
@@ -52,6 +60,7 @@ export function BlockTooltip({
children,
side = "top",
delayDuration = 100,
+ popupClassName,
}: TooltipProps) {
if (!content) {
return <>{children}</>;
@@ -69,7 +78,12 @@ export function BlockTooltip({
sideOffset={4}
className={LAYER_SURFACE_CLASS}
>
- <BaseTooltip.Popup className="max-w-56 rounded-sm bg-main px-2.5 py-1.5 text-xs text-main-text shadow-md">
+ <BaseTooltip.Popup
+ className={cn(
+ "max-w-56 rounded-sm bg-main px-2.5 py-1.5 text-xs text-main-text shadow-md",
+ popupClassName
+ )}
+ >
{content}
<BaseTooltip.Arrow className="fill-main" />
</BaseTooltip.Popup>
diff --git a/frontend/src/lib/plan/diffPlanSpecs.ts b/frontend/src/lib/plan/diffPlanSpecs.ts
index 040a3a3441..de995f555e 100644
--- a/frontend/src/lib/plan/diffPlanSpecs.ts
+++ b/frontend/src/lib/plan/diffPlanSpecs.ts
@@ -1,5 +1,6 @@
import { clone, equals } from "@bufbuild/protobuf";
import { isEqual } from "lodash-es";
+import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";
import {
type Plan_Spec,
Plan_SpecSchema,
@@ -63,6 +64,20 @@ export function diffPlanSpecsForEvent(eventValue: {
return fresh;
}
+export function collectPlanUpdateSpecs(comments: IssueComment[]): Plan_Spec[] {
+ const specs: Plan_Spec[] = [];
+ for (const comment of comments) {
+ if (comment.event.case !== "planUpdate") {
+ continue;
+ }
+ specs.push(
+ ...comment.event.value.fromSpecs,
+ ...comment.event.value.toSpecs
+ );
+ }
+ return specs;
+}
+
export function diffPlanSpecs(
from: Plan_Spec[],
to: Plan_Spec[]
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index f9702e9998..610877bb46 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1683,6 +1683,15 @@
"select-targets": "Select Targets",
"spec": {
"change": "Change",
+ "change-reference": {
+ "accessible-label": "Change {{index}}: {{label}}",
+ "database-count_one": "{{count}} database",
+ "database-count_other": "{{count}} databases",
+ "environment-overflow_one": "{{environment}} +{{count}} environment",
+ "environment-overflow_other": "{{environment}} +{{count}} environments",
+ "new-change": "New change",
+ "tooltip-title": "Change {{index}}"
+ },
"type": {
"database-change": "Database Change"
}
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index a98a7ee2fa..707d669c0d 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1683,6 +1683,15 @@
"select-targets": "Seleccionar destinos",
"spec": {
"change": "Cambio",
+ "change-reference": {
+ "accessible-label": "Cambio {{index}}: {{label}}",
+ "database-count_one": "{{count}} base de datos",
+ "database-count_other": "{{count}} bases de datos",
+ "environment-overflow_one": "{{environment}} +{{count}} entorno",
+ "environment-overflow_other": "{{environment}} +{{count}} entornos",
+ "new-change": "Nuevo cambio",
+ "tooltip-title": "Cambio {{index}}"
+ },
"type": {
"database-change": "Cambio de base de datos"
}
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index f4fdd76fab..dbc54a8c2f 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -1683,6 +1683,15 @@
"select-targets": "対象を選択",
"spec": {
"change": "変更",
+ "change-reference": {
+ "accessible-label": "変更 {{index}}: {{label}}",
+ "database-count_one": "{{count}} 個のデータベース",
+ "database-count_other": "{{count}} 個のデータベース",
+ "environment-overflow_one": "{{environment}} +{{count}} 環境",
+ "environment-overflow_other": "{{environment}} +{{count}} 環境",
+ "new-change": "新しい変更",
+ "tooltip-title": "変更 {{index}}"
+ },
"type": {
"database-change": "データベース変更"
}
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 612a68c43f..c4790d61c8 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -1683,6 +1683,15 @@
"select-targets": "Chọn mục tiêu",
"spec": {
"change": "Thay đổi",
+ "change-reference": {
+ "accessible-label": "Thay đổi {{index}}: {{label}}",
+ "database-count_one": "{{count}} cơ sở dữ liệu",
+ "database-count_other": "{{count}} cơ sở dữ liệu",
+ "environment-overflow_one": "{{environment}} +{{count}} môi trường",
+ "environment-overflow_other": "{{environment}} +{{count}} môi trường",
+ "new-change": "Thay đổi mới",
+ "tooltip-title": "Thay đổi {{index}}"
+ },
"type": {
"database-change": "Thay đổi cơ sở dữ liệu"
}
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index a9bca5d91e..9a3608f0d2 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1683,6 +1683,15 @@
"select-targets": "选择目标",
"spec": {
"change": "变更",
+ "change-reference": {
+ "accessible-label": "变更 {{index}}:{{label}}",
+ "database-count_one": "{{count}} 个数据库",
+ "database-count_other": "{{count}} 个数据库",
+ "environment-overflow_one": "{{environment}} +{{count}} 个环境",
+ "environment-overflow_other": "{{environment}} +{{count}} 个环境",
+ "new-change": "新变更",
+ "tooltip-title": "变更 {{index}}"
+ },
"type": {
"database-change": "数据库变更"
}
diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsx
index 2240257749..c4dc9f5b0d 100644
--- a/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsx
+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailCommentList.tsx
@@ -9,12 +9,14 @@ import {
CommentCreator,
canEditIssueComment,
IssueCommentRow,
+ type PlanChangeReferenceRenderer,
} from "@/components/issue-activity/IssueCommentActivity";
import { MarkdownEditor } from "@/components/MarkdownEditor";
import { UserAvatar } from "@/components/UserAvatar";
import { Button } from "@/components/ui/button";
import { useCurrentUser } from "@/hooks/useAppState";
import { useProjectByName } from "@/hooks/useProjectByName";
+import { collectPlanUpdateSpecs } from "@/lib/plan/diffPlanSpecs";
import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
import { projectNamePrefix } from "@/stores/modules/v1/common";
@@ -27,6 +29,8 @@ import {
} from "@/types/proto-es/v1/issue_service_pb";
import { extractProjectResourceName } from "@/utils";
import { hasProjectPermissionV2 } from "@/utils/iam/permission";
+import { PlanSpecChangeReference } from "../../plan-detail/components/PlanChangeReference";
+import { usePlanChangeReferenceData } from "../../plan-detail/hooks/usePlanChangeReferenceData";
import { useIssueDetailContext } from "../context/IssueDetailContext";
// Stable empty reference for the no-issue branch of the comments selector.
@@ -75,6 +79,22 @@ export function IssueDetailCommentList() {
const issueComments = useAppStore((state) =>
issueName ? state.getIssueComments(issueName) : EMPTY_ISSUE_COMMENTS
);
+ const planUpdateSpecs = useMemo(
+ () => collectPlanUpdateSpecs(issueComments),
+ [issueComments]
+ );
+ const changeReferenceResources = usePlanChangeReferenceData(planUpdateSpecs);
+ const renderPlanChangeReference = useCallback<PlanChangeReferenceRenderer>(
+ ({ siblings, spec }) => (
+ <PlanSpecChangeReference
+ className="font-medium"
+ resources={changeReferenceResources}
+ siblings={siblings}
+ spec={spec}
+ />
+ ),
+ [changeReferenceResources]
+ );
const issueUpdateKey = `${page.issue?.updateTime?.seconds ?? ""}:${page.issue?.updateTime?.nanos ?? ""}`;
const [activeCommentName, setActiveCommentName] = useState<string>();
const [editContent, setEditContent] = useState("");
@@ -233,6 +253,7 @@ export function IssueDetailCommentList() {
isLast={index === issueComments.length - 1}
issue={page.issue}
plan={page.plan}
+ renderPlanChangeReference={renderPlanChangeReference}
subjectSuffix={
allowEditComment(item) && !activeCommentName ? (
<Button
diff --git a/frontend/src/routes/project/plan-detail/components/PlanChangeReference.test.tsx b/frontend/src/routes/project/plan-detail/components/PlanChangeReference.test.tsx
new file mode 100644
index 0000000000..8195e4c038
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/components/PlanChangeReference.test.tsx
@@ -0,0 +1,292 @@
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { PlanChangeReference as PlanChangeReferenceModel } from "../utils/changeReference";
+import {
+ PlanChangeReference,
+ PlanChangeReferenceTooltip,
+} from "./PlanChangeReference";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+let resizeObserverCallback: ResizeObserverCallback | undefined;
+
+class ResizeObserverStub implements ResizeObserver {
+ constructor(callback: ResizeObserverCallback) {
+ resizeObserverCallback = callback;
+ }
+ disconnect() {}
+ observe() {}
+ takeRecords(): ResizeObserverEntry[] {
+ return [];
+ }
+ unobserve() {}
+}
+
+describe("PlanChangeReference", () => {
+ let container: HTMLDivElement;
+ let root: Root;
+ let clientWidthSpy: {
+ mockRestore: () => void;
+ mockReturnValue: (value: number) => unknown;
+ };
+ let scrollWidthSpy: {
+ mockRestore: () => void;
+ mockReturnValue: (value: number) => unknown;
+ };
+
+ beforeEach(() => {
+ globalThis.ResizeObserver = ResizeObserverStub;
+ resizeObserverCallback = undefined;
+ clientWidthSpy = vi
+ .spyOn(HTMLElement.prototype, "clientWidth", "get")
+ .mockReturnValue(280);
+ scrollWidthSpy = vi
+ .spyOn(HTMLElement.prototype, "scrollWidth", "get")
+ .mockReturnValue(120);
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => root.unmount());
+ clientWidthSpy.mockRestore();
+ scrollWidthSpy.mockRestore();
+ document.body.removeChild(container);
+ });
+
+ it("switches a long database list to its count label", async () => {
+ clientWidthSpy.mockReturnValue(120);
+ scrollWidthSpy.mockReturnValue(280);
+ const reference: PlanChangeReferenceModel = {
+ accessibleLabel: "Change 1: orders, customers, audit",
+ countLabel: "3 databases · Production",
+ fullLabel: "orders, customers, audit",
+ icon: "database",
+ index: 1,
+ label: "orders, customers, audit",
+ showIndex: false,
+ showIndexWithCountLabel: true,
+ specId: "spec-1",
+ };
+
+ await act(async () => {
+ root.render(<PlanChangeReference reference={reference} />);
+ await Promise.resolve();
+ });
+
+ const element = container.querySelector("[data-plan-change-reference]");
+ expect(element?.getAttribute("data-plan-change-reference-label")).toBe(
+ "3 databases · Production"
+ );
+ expect(element).toHaveAttribute(
+ "data-plan-change-reference-overflow",
+ "true"
+ );
+ expect(
+ element?.children[0]?.textContent
+ ).toBe("1");
+ });
+
+ it("restores the full label when its available width increases", async () => {
+ clientWidthSpy.mockReturnValue(120);
+ scrollWidthSpy.mockReturnValue(280);
+ const reference: PlanChangeReferenceModel = {
+ accessibleLabel: "Change 1: orders, customers, audit",
+ countLabel: "3 databases",
+ fullLabel: "orders, customers, audit",
+ icon: "database",
+ index: 1,
+ label: "orders, customers, audit",
+ showIndex: false,
+ showIndexWithCountLabel: false,
+ specId: "spec-1",
+ };
+
+ await act(async () => {
+ root.render(<PlanChangeReference reference={reference} />);
+ await Promise.resolve();
+ });
+ expect(
+ container
+ .querySelector("[data-plan-change-reference]")
+ ?.getAttribute("data-plan-change-reference-label")
+ ).toBe("3 databases");
+
+ clientWidthSpy.mockReturnValue(280);
+ scrollWidthSpy.mockReturnValue(200);
+ await act(async () => {
+ resizeObserverCallback?.([], {} as ResizeObserver);
+ await Promise.resolve();
+ });
+
+ const element = container.querySelector("[data-plan-change-reference]");
+ expect(element?.getAttribute("data-plan-change-reference-label")).toBe(
+ "orders, customers, audit"
+ );
+ expect(element).not.toHaveAttribute("data-plan-change-reference-overflow");
+ });
+
+ it("remeasures the full label when an overflowing reference changes", async () => {
+ clientWidthSpy.mockReturnValue(120);
+ scrollWidthSpy.mockReturnValue(280);
+ const reference: PlanChangeReferenceModel = {
+ accessibleLabel: "Change 1: orders, customers, audit",
+ countLabel: "3 databases",
+ fullLabel: "orders, customers, audit",
+ icon: "database",
+ index: 1,
+ label: "orders, customers, audit",
+ showIndex: false,
+ showIndexWithCountLabel: true,
+ specId: "spec-1",
+ };
+
+ await act(async () => {
+ root.render(<PlanChangeReference reference={reference} />);
+ await Promise.resolve();
+ });
+ expect(
+ container
+ .querySelector("[data-plan-change-reference]")
+ ?.getAttribute("data-plan-change-reference-label")
+ ).toBe("3 databases");
+
+ clientWidthSpy.mockReturnValue(180);
+ scrollWidthSpy.mockReturnValue(100);
+ await act(async () => {
+ root.render(
+ <PlanChangeReference
+ reference={{
+ ...reference,
+ accessibleLabel: "Change 1: orders, audit",
+ countLabel: "2 databases",
+ fullLabel: "orders, audit",
+ label: "orders, audit",
+ }}
+ />
+ );
+ await Promise.resolve();
+ });
+
+ const element = container.querySelector("[data-plan-change-reference]");
+ expect(element?.getAttribute("data-plan-change-reference-label")).toBe(
+ "orders, audit"
+ );
+ expect(element).not.toHaveAttribute("data-plan-change-reference-overflow");
+ });
+
+ it("omits the index and tooltip when the reference fully fits", async () => {
+ const reference: PlanChangeReferenceModel = {
+ accessibleLabel: "Change 1: orders",
+ fullLabel: "orders",
+ icon: "database",
+ index: 1,
+ label: "orders",
+ showIndex: false,
+ showIndexWithCountLabel: false,
+ specId: "spec-1",
+ };
+
+ await act(async () => {
+ root.render(<PlanChangeReference reference={reference} />);
+ await Promise.resolve();
+ });
+
+ const element = container.querySelector("[data-plan-change-reference]");
+ expect(element).toHaveClass("max-w-80");
+ expect(element?.children[0]?.querySelector("svg")).not.toBeNull();
+ expect(element?.children[1]).toHaveClass("max-w-72");
+ expect(element?.children[1]?.textContent).toBe("orders");
+ expect(element?.textContent).toBe("orders");
+ expect(element?.getAttribute("aria-label")).toBe("Change 1: orders");
+ expect(element).not.toHaveAttribute("data-plan-change-reference-overflow");
+ const measurement = container.querySelector(
+ "[data-plan-change-reference-measure]"
+ );
+ expect(measurement).toHaveClass("invisible", "overflow-hidden");
+ expect(measurement).not.toHaveClass("absolute");
+ });
+
+ it("renders a subdued index when references collide", async () => {
+ const reference: PlanChangeReferenceModel = {
+ accessibleLabel: "Change 2: orders",
+ fullLabel: "orders",
+ icon: "database",
+ index: 2,
+ label: "orders",
+ showIndex: true,
+ showIndexWithCountLabel: false,
+ specId: "spec-2",
+ };
+
+ await act(async () => {
+ root.render(<PlanChangeReference reference={reference} />);
+ await Promise.resolve();
+ });
+
+ const element = container.querySelector("[data-plan-change-reference]");
+ expect(element?.children[0]?.textContent).toBe("2");
+ expect(element?.children[0]?.className).toContain("text-sm");
+ expect(element?.children[0]?.className).toContain(
+ "text-control-placeholder"
+ );
+ expect(element?.children[0]?.className).toContain("tabular-nums");
+ expect(element?.children[1]?.querySelector("svg")).not.toBeNull();
+ expect(element?.children[2]?.textContent).toBe("orders");
+ });
+
+ it("uses the compact width limit in the plan tab", async () => {
+ const reference: PlanChangeReferenceModel = {
+ accessibleLabel: "Change 1: customer_orders_production_archive",
+ fullLabel: "customer_orders_production_archive",
+ icon: "database",
+ index: 1,
+ label: "customer_orders_production_archive",
+ showIndex: false,
+ showIndexWithCountLabel: false,
+ specId: "spec-1",
+ };
+
+ await act(async () => {
+ root.render(
+ <PlanChangeReference density="tab" reference={reference} />
+ );
+ await Promise.resolve();
+ });
+
+ const element = container.querySelector("[data-plan-change-reference]");
+ expect(element).toHaveClass("max-w-64");
+ expect(element?.children[1]).toHaveClass("max-w-56");
+ expect(element?.textContent).toBe("customer_orders_production_archive");
+ });
+
+ it("shows the complete label and summary in the structured tooltip", async () => {
+ const reference: PlanChangeReferenceModel = {
+ accessibleLabel: "Change 4: orders, customers, audit",
+ countLabel: "3 databases · Production",
+ fullLabel: "orders, customers, audit",
+ icon: "database",
+ index: 4,
+ label: "orders, customers, audit",
+ showIndex: false,
+ showIndexWithCountLabel: false,
+ specId: "spec-4",
+ };
+
+ await act(async () => {
+ root.render(<PlanChangeReferenceTooltip reference={reference} />);
+ await Promise.resolve();
+ });
+
+ expect(container.textContent).toContain("Change 4");
+ expect(container.textContent).toContain("orders, customers, audit");
+ expect(container.textContent).toContain("3 databases · Production");
+ expect(container.querySelector('[dir="auto"]')?.textContent).toBe(
+ reference.fullLabel
+ );
+ });
+});
diff --git a/frontend/src/routes/project/plan-detail/components/PlanChangeReference.tsx b/frontend/src/routes/project/plan-detail/components/PlanChangeReference.tsx
new file mode 100644
index 0000000000..6c83cdcb7f
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/components/PlanChangeReference.tsx
@@ -0,0 +1,255 @@
+import { DatabaseIcon, Download, FolderTree } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Tooltip } from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
+import type {
+ PlanChangeReferenceIcon,
+ PlanChangeReference as PlanChangeReferenceModel,
+ PlanChangeReferenceResources,
+} from "../utils/changeReference";
+import {
+ derivePlanChangeReference,
+ splitPlanChangeReferenceLabel,
+} from "../utils/changeReference";
+
+export const PLAN_CHANGE_REFERENCE_TOOLTIP_CLASS =
+ "max-w-[min(24rem,calc(100vw-1rem))] px-3 py-2.5";
+
+type PlanChangeReferenceDensity = "activity" | "tab";
+
+const DENSITY_CLASS: Record<
+ PlanChangeReferenceDensity,
+ { label: string; reference: string }
+> = {
+ activity: {
+ label: "max-w-72",
+ reference: "max-w-80",
+ },
+ tab: {
+ label: "max-w-56",
+ reference: "max-w-64",
+ },
+};
+
+export function PlanChangeReference({
+ ariaHidden = false,
+ className,
+ density = "activity",
+ reference,
+}: {
+ ariaHidden?: boolean;
+ className?: string;
+ density?: PlanChangeReferenceDensity;
+ reference: PlanChangeReferenceModel;
+}) {
+ const measureRef = useRef<HTMLSpanElement>(null);
+ const densityClass = DENSITY_CLASS[density];
+ const overflowKey = [
+ density,
+ reference.label,
+ reference.countLabel ?? "",
+ reference.showIndex ? "1" : "0",
+ reference.showIndexWithCountLabel ? "1" : "0",
+ ].join("\u0000");
+ const [overflowState, setOverflowState] = useState({
+ key: "",
+ value: false,
+ });
+ const isOverflowing =
+ overflowState.key === overflowKey && overflowState.value;
+ const useCountLabel = Boolean(isOverflowing && reference.countLabel);
+ const displayLabel =
+ useCountLabel && reference.countLabel
+ ? reference.countLabel
+ : reference.label;
+ const showIndex = useCountLabel
+ ? reference.showIndexWithCountLabel
+ : reference.showIndex;
+
+ useEffect(() => {
+ const element = measureRef.current;
+ if (!element) {
+ setOverflowState({ key: overflowKey, value: false });
+ return;
+ }
+ const measure = () => {
+ const overflowing = element.scrollWidth > element.clientWidth;
+ setOverflowState((current) =>
+ current.key === overflowKey && current.value === overflowing
+ ? current
+ : { key: overflowKey, value: overflowing }
+ );
+ };
+ measure();
+ if (typeof ResizeObserver === "undefined") {
+ return;
+ }
+ const observer = new ResizeObserver(measure);
+ observer.observe(element);
+ return () => observer.disconnect();
+ }, [overflowKey]);
+
+ const content = (
+ <span
+ aria-hidden={ariaHidden || undefined}
+ aria-label={ariaHidden ? undefined : reference.accessibleLabel}
+ className={cn(
+ "inline-flex w-full min-w-0 items-center gap-1 leading-5",
+ densityClass.reference,
+ className
+ )}
+ data-plan-change-reference={reference.specId}
+ data-plan-change-reference-label={displayLabel}
+ data-plan-change-reference-overflow={isOverflowing || undefined}
+ >
+ {showIndex && (
+ <span className="shrink-0 text-sm font-normal tabular-nums text-control-placeholder">
+ {reference.index}
+ </span>
+ )}
+ <span className="mr-0.5 shrink-0 text-control-light">
+ <ChangeTypeIcon icon={reference.icon} />
+ </span>
+ <MiddleEllipsisLabel className={densityClass.label} text={displayLabel} />
+ </span>
+ );
+
+ return (
+ <span className={cn("inline-grid min-w-0", densityClass.reference)}>
+ <span
+ aria-hidden="true"
+ className={cn(
+ "invisible col-start-1 row-start-1 inline-flex min-w-0 items-center gap-1 overflow-hidden leading-5",
+ className
+ )}
+ data-plan-change-reference-measure
+ >
+ {reference.showIndex && (
+ <span className="shrink-0 text-sm font-normal tabular-nums text-control-placeholder">
+ {reference.index}
+ </span>
+ )}
+ <span className="mr-0.5 shrink-0 text-control-light">
+ <ChangeTypeIcon icon={reference.icon} />
+ </span>
+ <span
+ ref={measureRef}
+ className={cn(
+ "min-w-0 overflow-hidden whitespace-nowrap",
+ densityClass.label
+ )}
+ >
+ {reference.label}
+ </span>
+ </span>
+ <span className="col-start-1 row-start-1 inline-flex min-w-0">
+ {isOverflowing ? (
+ <Tooltip
+ content={<PlanChangeReferenceTooltip reference={reference} />}
+ delayDuration={250}
+ popupClassName={PLAN_CHANGE_REFERENCE_TOOLTIP_CLASS}
+ >
+ {content}
+ </Tooltip>
+ ) : (
+ content
+ )}
+ </span>
+ </span>
+ );
+}
+
+export function PlanSpecChangeReference({
+ className,
+ resources,
+ siblings,
+ spec,
+}: {
+ className?: string;
+ resources: PlanChangeReferenceResources;
+ siblings: Plan_Spec[];
+ spec: Plan_Spec;
+}) {
+ const { t } = useTranslation();
+ const index = siblings.findIndex((sibling) => sibling.id === spec.id);
+ if (index < 0) {
+ return null;
+ }
+ const reference = derivePlanChangeReference({
+ index,
+ resources,
+ siblings,
+ spec,
+ t,
+ });
+ return <PlanChangeReference className={className} reference={reference} />;
+}
+
+export function PlanChangeReferenceTooltip({
+ reference,
+}: {
+ reference: PlanChangeReferenceModel;
+}) {
+ const { t } = useTranslation();
+ return (
+ <div className="flex w-80 max-w-full flex-col gap-1.5">
+ <div className="flex items-center gap-1.5 text-main-text/70">
+ <ChangeTypeIcon icon={reference.icon} />
+ <span>
+ {t("plan.spec.change-reference.tooltip-title", {
+ index: reference.index,
+ })}
+ </span>
+ </div>
+ <div
+ className="wrap-break-word text-sm font-medium leading-5 text-main-text"
+ dir="auto"
+ >
+ {reference.fullLabel}
+ </div>
+ {reference.countLabel && reference.countLabel !== reference.fullLabel && (
+ <div
+ className="wrap-break-word border-main-text/15 border-t pt-1.5 text-[11px] leading-4 text-main-text/70"
+ dir="auto"
+ >
+ {reference.countLabel}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function ChangeTypeIcon({ icon }: { icon: PlanChangeReferenceIcon }) {
+ if (icon === "database-group") {
+ return <FolderTree className="size-3.5" />;
+ }
+ if (icon === "export") {
+ return <Download className="size-3.5" />;
+ }
+ return <DatabaseIcon className="size-3.5" />;
+}
+
+function MiddleEllipsisLabel({
+ className,
+ text,
+}: {
+ className: string;
+ text: string;
+}) {
+ const { prefix, suffix } = splitPlanChangeReferenceLabel(text);
+ if (!suffix) {
+ return (
+ <span className={cn("min-w-0 truncate", className)} dir="auto">
+ {prefix}
+ </span>
+ );
+ }
+ return (
+ <span className={cn("flex min-w-0", className)} dir="auto">
+ <span className="min-w-0 truncate">{prefix}</span>
+ <span className="shrink-0">{suffix}</span>
+ </span>
+ );
+}
diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.test.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.test.tsx
index 899ceda646..a29469bea8 100644
--- a/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.test.tsx
+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.test.tsx
@@ -65,7 +65,26 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock("react-i18next", () => ({
- useTranslation: () => ({ t: (key: string) => key }),
+ useTranslation: () => ({
+ t: (
+ key: string,
+ options?: Record<string, string | number>
+ ): string => {
+ if (key === "plan.spec.change-reference.accessible-label") {
+ return `Change ${options?.index}: ${options?.label}`;
+ }
+ if (key === "plan.spec.change-reference.database-count") {
+ return `${options?.count} databases`;
+ }
+ if (key === "plan.spec.change-reference.environment-overflow") {
+ return `${options?.environment} +${options?.count} environments`;
+ }
+ if (key === "plan.spec.change-reference.new-change") {
+ return "New change";
+ }
+ return key;
+ },
+ }),
}));
vi.mock("@bufbuild/protobuf", () => ({
@@ -469,12 +488,18 @@ vi.mock("./PlanDetailStatementSection", () => ({
vi.mock("./PlanDetailTabStrip", () => ({
PlanDetailTabItem: ({
+ accessibleLabel,
children,
onSelect,
}: {
+ accessibleLabel?: string;
children: ReactNode;
onSelect?: () => void;
- }) => <button onClick={onSelect}>{children}</button>,
+ }) => (
+ <button aria-label={accessibleLabel} onClick={onSelect}>
+ {children}
+ </button>
+ ),
PlanDetailTabStrip: ({
action,
trailing,
@@ -678,6 +703,188 @@ async function flush() {
}
describe("PlanDetailChangesBranch", () => {
+ it("renders target-derived change references instead of generic types", async () => {
+ const page = buildPageState();
+ page.plan.specs = [
+ {
+ id: "spec-orders",
+ config: {
+ case: "changeDatabaseConfig",
+ value: { targets: [DB_WIDGETS] },
+ },
+ },
+ {
+ id: "spec-cogs",
+ config: {
+ case: "changeDatabaseConfig",
+ value: { targets: [DB_COGS] },
+ },
+ },
+ ] as unknown as PlanDetailPageState["plan"]["specs"];
+
+ act(() => {
+ root.render(
+ <PlanDetailProvider value={page}>
+ <PlanDetailChangesBranch
+ selectedSpecId="spec-orders"
+ onSelectedSpecIdChange={vi.fn()}
+ />
+ </PlanDetailProvider>
+ );
+ });
+ await flush();
+
+ const references = [
+ ...container.querySelectorAll("[data-plan-change-reference]"),
+ ];
+ expect(
+ references.map((reference) =>
+ reference.getAttribute("data-plan-change-reference-label")
+ )
+ ).toEqual(["widgets", "cogs"]);
+ expect(references.map((reference) => reference.textContent)).toEqual([
+ "widgets",
+ "cogs",
+ ]);
+ expect(container.textContent).not.toContain(
+ "plan.spec.type.database-change"
+ );
+ expect(mocks.databaseStore.batchGetOrFetchDatabases).toHaveBeenCalledWith([
+ DB_WIDGETS,
+ DB_COGS,
+ ], true);
+ });
+
+ it("keeps base references when database enrichment fails", async () => {
+ mocks.databaseStore.batchGetOrFetchDatabases.mockRejectedValueOnce(
+ new Error("database enrichment failed")
+ );
+ const page = buildPageState();
+ page.plan.specs = [
+ {
+ id: "spec-widgets",
+ config: {
+ case: "changeDatabaseConfig",
+ value: { targets: [DB_WIDGETS] },
+ },
+ },
+ ] as unknown as PlanDetailPageState["plan"]["specs"];
+
+ act(() => {
+ root.render(
+ <PlanDetailProvider value={page}>
+ <PlanDetailChangesBranch
+ selectedSpecId="spec-widgets"
+ onSelectedSpecIdChange={vi.fn()}
+ />
+ </PlanDetailProvider>
+ );
+ });
+ await flush();
+
+ expect(mocks.databaseStore.batchGetOrFetchDatabases).toHaveBeenCalledWith(
+ [DB_WIDGETS],
+ true
+ );
+ expect(
+ container
+ .querySelector("[data-plan-change-reference]")
+ ?.getAttribute("data-plan-change-reference-label")
+ ).toBe("widgets");
+ });
+
+ it("keeps same-target changes distinct through their accessible indexes", async () => {
+ const page = buildPageState();
+ page.plan.specs = [
+ {
+ id: "spec-1",
+ config: {
+ case: "changeDatabaseConfig",
+ value: { targets: [DB_WIDGETS] },
+ },
+ },
+ {
+ id: "spec-2",
+ config: {
+ case: "changeDatabaseConfig",
+ value: { targets: [DB_WIDGETS] },
+ },
+ },
+ ] as unknown as PlanDetailPageState["plan"]["specs"];
+
+ act(() => {
+ root.render(
+ <PlanDetailProvider value={page}>
+ <PlanDetailChangesBranch
+ selectedSpecId="spec-1"
+ onSelectedSpecIdChange={vi.fn()}
+ />
+ </PlanDetailProvider>
+ );
+ });
+ await flush();
+
+ const referenceButtons = [
+ ...container.querySelectorAll("[data-plan-change-reference]"),
+ ].map((reference) => reference.closest("button"));
+ expect(
+ referenceButtons.map((button) => button?.getAttribute("aria-label"))
+ ).toEqual(["Change 1: widgets", "Change 2: widgets"]);
+ expect(
+ [...container.querySelectorAll("[data-plan-change-reference]")].map(
+ (reference) => reference.textContent
+ )
+ ).toEqual(["1widgets", "2widgets"]);
+ });
+
+ it("updates the reference when targets change without changing selection", async () => {
+ const page = buildPageState();
+ page.plan.specs = [
+ {
+ id: "spec-1",
+ config: {
+ case: "changeDatabaseConfig",
+ value: { targets: [DB_WIDGETS] },
+ },
+ },
+ ] as unknown as PlanDetailPageState["plan"]["specs"];
+ const render = () =>
+ root.render(
+ <PlanDetailProvider value={page}>
+ <PlanDetailChangesBranch
+ selectedSpecId="spec-1"
+ onSelectedSpecIdChange={vi.fn()}
+ />
+ </PlanDetailProvider>
+ );
+
+ act(render);
+ await flush();
+ expect(
+ container
+ .querySelector("[data-plan-change-reference]")
+ ?.getAttribute("data-plan-change-reference-label")
+ ).toBe("widgets");
+
+ page.plan.specs = [
+ {
+ id: "spec-1",
+ config: {
+ case: "changeDatabaseConfig",
+ value: { targets: [DB_COGS] },
+ },
+ },
+ ] as unknown as PlanDetailPageState["plan"]["specs"];
+ act(render);
+ await flush();
+
+ expect(
+ container
+ .querySelector("[data-plan-change-reference]")
+ ?.getAttribute("data-plan-change-reference-label")
+ ).toBe("cogs");
+ });
+
it("renders all targets in a single scrollable sheet list", async () => {
const page = buildPageState();
const targets = Array.from(
@@ -864,9 +1071,15 @@ describe("PlanDetailChangesBranch", () => {
expect(
[...container.querySelectorAll("button")].filter((button) =>
- button.textContent?.includes("plan.spec.type.database-change")
+ button.querySelector("[data-plan-change-reference]")
)
).toHaveLength(2);
+ expect(
+ [...container.querySelectorAll("[data-plan-change-reference]")].map(
+ (reference) =>
+ reference.getAttribute("data-plan-change-reference-label")
+ )
+ ).toEqual(["New change", "group-a"]);
expect(
(
[...container.querySelectorAll("button")].find(
@@ -894,7 +1107,7 @@ describe("PlanDetailChangesBranch", () => {
expect(
[...container.querySelectorAll("button")].filter((button) =>
- button.textContent?.includes("plan.spec.type.database-change")
+ button.querySelector("[data-plan-change-reference]")
)
).toHaveLength(1);
expect(
@@ -1066,7 +1279,7 @@ describe("PlanDetailChangesBranch", () => {
expect(container.textContent).toContain("spec-1:check-run-for-spec-1");
const specTabs = [...container.querySelectorAll("button")].filter(
- (button) => button.textContent?.includes("plan.spec.type.database-change")
+ (button) => button.querySelector("[data-plan-change-reference]")
);
expect(specTabs.length).toBe(2);
@@ -1095,7 +1308,7 @@ describe("PlanDetailChangesBranch", () => {
).toBeNull();
const specTabs = [...container.querySelectorAll("button")].filter(
- (button) => button.textContent?.includes("plan.spec.type.database-change")
+ (button) => button.querySelector("[data-plan-change-reference]")
);
expect(specTabs.length).toBe(2);
diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx
index 44432b8e57..9f9e87229f 100644
--- a/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx
+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx
@@ -111,7 +111,9 @@ import { getStatementSize } from "@/utils/sheet";
import { extractDatabaseGroupName } from "@/utils/v1/databaseGroup";
import { sheetNameOfSpec } from "@/utils/v1/issue/plan";
import { extractSheetUID, getSheetStatement } from "@/utils/v1/sheet";
+import { usePlanChangeReferenceData } from "../hooks/usePlanChangeReferenceData";
import { usePlanDetailContext } from "../shell/PlanDetailContext";
+import { derivePlanChangeReference } from "../utils/changeReference";
import {
getDefaultGhostConfig,
getGhostConfig as getGhostConfigFromStatement,
@@ -132,17 +134,14 @@ import {
allowGhostForDatabase,
getPlanOptionVisibility,
} from "../utils/options";
-import {
- getSelectedSpec,
- getSpecTitle,
- isReleaseBackedPlan,
-} from "../utils/spec";
+import { getSelectedSpec, isReleaseBackedPlan } from "../utils/spec";
import { updateSpecSheetWithStatement } from "../utils/specMutation";
import {
filterPlanTargets,
getDatabaseGroupRouteParams,
splitInlineDatabases,
} from "../utils/targets";
+import { PlanChangeReference } from "./PlanChangeReference";
import { PlanDetailAggregateChecks } from "./PlanDetailAggregateChecks";
import { PlanDetailDraftChecks } from "./PlanDetailDraftChecks";
import { PlanDetailStatementSection } from "./PlanDetailStatementSection";
@@ -246,6 +245,7 @@ export function PlanDetailChangesBranch({
() => (pendingNewSpec ? [...specs, pendingNewSpec] : specs),
[specs, pendingNewSpec]
);
+ const changeReferenceResources = usePlanChangeReferenceData(visibleSpecs);
const selectedSpec = useMemo(() => {
if (pendingNewSpec && isPendingSelected) {
return pendingNewSpec;
@@ -600,8 +600,17 @@ export function PlanDetailChangesBranch({
{visibleSpecs.map((spec, index) => {
const isSelected = selectedSpec.id === spec.id;
const isPending = pendingNewSpec?.id === spec.id;
+ const reference = derivePlanChangeReference({
+ index,
+ resources: changeReferenceResources,
+ siblings: visibleSpecs,
+ spec,
+ t,
+ });
return (
<PlanDetailTabItem
+ accessibleLabel={reference.accessibleLabel}
+ boundedWidth
key={spec.id}
action={
canModifySpecs && visibleSpecs.length > 1 ? (
@@ -648,15 +657,15 @@ export function PlanDetailChangesBranch({
}}
selected={isSelected}
>
- <span
+ <PlanChangeReference
+ ariaHidden
className={cn(
- "flex items-center gap-1 text-sm font-medium transition-colors",
+ "text-sm font-medium transition-colors",
isSelected ? "" : "text-control-light hover:text-control"
)}
- >
- <span className="opacity-80">{index + 1}.</span>
- <span>{getSpecTitle(spec, t)}</span>
- </span>
+ density="tab"
+ reference={reference}
+ />
</PlanDetailTabItem>
);
})}
diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailTabStrip.test.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailTabStrip.test.tsx
new file mode 100644
index 0000000000..f365c49611
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailTabStrip.test.tsx
@@ -0,0 +1,45 @@
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { PlanDetailTabItem } from "./PlanDetailTabStrip";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe("PlanDetailTabItem", () => {
+ let container: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => root.unmount());
+ document.body.removeChild(container);
+ });
+
+ it("bounds Change tab width without making every tab equal", () => {
+ act(() => {
+ root.render(
+ <PlanDetailTabItem
+ action={<span data-testid="action">Action</span>}
+ boundedWidth
+ onSelect={() => {}}
+ selected
+ >
+ <span>orders</span>
+ </PlanDetailTabItem>
+ );
+ });
+
+ const tab = container.firstElementChild;
+ const button = tab?.querySelector("button");
+ expect(tab).toHaveClass("min-w-40", "max-w-64");
+ expect(button).toHaveClass("min-w-0", "flex-1");
+ expect(button).not.toHaveClass("w-full");
+ });
+});
diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailTabStrip.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailTabStrip.tsx
index def11fcb29..682212d381 100644
--- a/frontend/src/routes/project/plan-detail/components/PlanDetailTabStrip.tsx
+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailTabStrip.tsx
@@ -38,12 +38,16 @@ export function PlanDetailTabStrip({
}
export function PlanDetailTabItem({
+ accessibleLabel,
action,
+ boundedWidth = false,
children,
onSelect,
selected,
}: {
+ accessibleLabel?: string;
action?: ReactNode;
+ boundedWidth?: boolean;
children: ReactNode;
onSelect: () => void;
selected: boolean;
@@ -54,13 +58,18 @@ export function PlanDetailTabItem({
// No transition here: the tab body swaps in the same commit, so a
// color fade makes the highlight lag the content and read as flicker.
"relative flex shrink-0 items-center rounded-t-lg border",
+ boundedWidth && "min-w-40 max-w-64",
selected
? "border-gray-200 border-b-transparent bg-white"
: "border-b-gray-200 border-transparent hover:opacity-80"
)}
>
<button
- className="flex min-h-9 shrink-0 items-center gap-2 px-4 py-2 text-left"
+ aria-label={accessibleLabel}
+ className={cn(
+ "flex min-h-9 min-w-0 items-center gap-2 px-4 py-2 text-left",
+ boundedWidth ? "flex-1" : "shrink-0"
+ )}
onClick={onSelect}
type="button"
>
diff --git a/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.test.tsx b/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.test.tsx
index 53acfdc9c9..2a1e53271d 100644
--- a/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.test.tsx
+++ b/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.test.tsx
@@ -91,10 +91,22 @@ vi.mock("@/utils/iam/permission", () => ({
hasProjectPermissionV2: () => false,
}));
+vi.mock("../../hooks/usePlanChangeReferenceData", () => ({
+ usePlanChangeReferenceData: () => ({
+ databaseGroupsByName: {},
+ databasesByName: {},
+ environmentList: [],
+ }),
+}));
+
vi.mock("../../shell/PlanDetailContext", () => ({
usePlanDetailContext: () => ({ projectId: "p1" }),
}));
+vi.mock("../PlanChangeReference", () => ({
+ PlanSpecChangeReference: () => <span data-testid="change-reference" />,
+}));
+
vi.mock("./ReviewCommentComposer", () => ({
ReviewCommentComposer: () => null,
}));
diff --git a/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsx b/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsx
index 67798582aa..1a03003035 100644
--- a/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsx
+++ b/frontend/src/routes/project/plan-detail/components/review/ReviewActivityTimeline.tsx
@@ -1,5 +1,12 @@
import { FileText, Loader2, Pencil } from "lucide-react";
-import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
+import {
+ type ReactNode,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import { useTranslation } from "react-i18next";
import { HumanizeTs } from "@/components/HumanizeTs";
import {
@@ -8,6 +15,7 @@ import {
CommentIconBadge,
canEditIssueComment,
IssueCommentRow,
+ type PlanChangeReferenceRenderer,
ReviewSubmissionIcon,
ReviewSubmissionSentence,
} from "@/components/issue-activity/IssueCommentActivity";
@@ -15,7 +23,10 @@ import { MarkdownEditor } from "@/components/MarkdownEditor";
import { Button } from "@/components/ui/button";
import { useCurrentUser } from "@/hooks/useAppState";
import { useProjectByName } from "@/hooks/useProjectByName";
-import { diffPlanSpecsForEvent } from "@/lib/plan/diffPlanSpecs";
+import {
+ collectPlanUpdateSpecs,
+ diffPlanSpecsForEvent,
+} from "@/lib/plan/diffPlanSpecs";
import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
import {
@@ -27,7 +38,9 @@ import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";
import type { Issue, IssueComment } from "@/types/proto-es/v1/issue_service_pb";
import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
import { hasProjectPermissionV2 } from "@/utils/iam/permission";
+import { usePlanChangeReferenceData } from "../../hooks/usePlanChangeReferenceData";
import { usePlanDetailContext } from "../../shell/PlanDetailContext";
+import { PlanSpecChangeReference } from "../PlanChangeReference";
import { consolidateConsecutive } from "./consolidateTimeline";
import { foldTimeline } from "./foldTimeline";
import { ReviewCommentComposer } from "./ReviewCommentComposer";
@@ -50,6 +63,22 @@ export function ReviewActivityTimeline({
const page = usePlanDetailContext();
const project = useProjectByName(`${projectNamePrefix}${page.projectId}`);
const [expanded, setExpanded] = useState(false);
+ const planUpdateSpecs = useMemo(
+ () => collectPlanUpdateSpecs(comments),
+ [comments]
+ );
+ const changeReferenceResources = usePlanChangeReferenceData(planUpdateSpecs);
+ const renderPlanChangeReference = useCallback<PlanChangeReferenceRenderer>(
+ ({ siblings, spec }) => (
+ <PlanSpecChangeReference
+ className="font-medium"
+ resources={changeReferenceResources}
+ siblings={siblings}
+ spec={spec}
+ />
+ ),
+ [changeReferenceResources]
+ );
useEffect(() => {
setExpanded(false);
@@ -111,6 +140,7 @@ export function ReviewActivityTimeline({
isLast={isLast}
key={item.entry.id}
plan={plan}
+ renderPlanChangeReference={renderPlanChangeReference}
/>
);
})}
@@ -178,11 +208,13 @@ function ActivityRow({
issue,
isLast,
plan,
+ renderPlanChangeReference,
}: {
entry: TimelineEntry;
issue: Issue;
isLast: boolean;
plan: Plan;
+ renderPlanChangeReference: PlanChangeReferenceRenderer;
}) {
const source = entry.source;
if (source.type === "comment") {
@@ -192,6 +224,7 @@ function ActivityRow({
isLast={isLast}
issue={issue}
plan={plan}
+ renderPlanChangeReference={renderPlanChangeReference}
similarCount={entry.similarCount}
/>
);
@@ -264,12 +297,14 @@ function ReviewCommentRow({
isLast,
issue,
plan,
+ renderPlanChangeReference,
similarCount,
}: {
comment: IssueComment;
isLast: boolean;
issue: Issue;
plan: Plan;
+ renderPlanChangeReference: PlanChangeReferenceRenderer;
similarCount?: number;
}) {
const { t } = useTranslation();
@@ -399,6 +434,7 @@ function ReviewCommentRow({
issue={issue}
linkless
plan={plan}
+ renderPlanChangeReference={renderPlanChangeReference}
similarCount={similarCount}
subjectSuffix={subjectSuffix}
/>
diff --git a/frontend/src/routes/project/plan-detail/hooks/usePlanChangeReferenceData.ts b/frontend/src/routes/project/plan-detail/hooks/usePlanChangeReferenceData.ts
new file mode 100644
index 0000000000..02549dde44
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/hooks/usePlanChangeReferenceData.ts
@@ -0,0 +1,79 @@
+import { useEffect, useMemo } from "react";
+import { useAppStore } from "@/stores/app";
+import { isValidDatabaseGroupName, isValidDatabaseName } from "@/types";
+import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";
+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
+import type { PlanChangeReferenceResources } from "../utils/changeReference";
+
+export const usePlanChangeReferenceData = (
+ specs: Plan_Spec[]
+): PlanChangeReferenceResources => {
+ const databasesByName = useAppStore((state) => state.databasesByName);
+ const databaseGroupsByName = useAppStore((state) => state.dbGroupsByName);
+ const environmentList = useAppStore((state) => state.environmentList);
+ const targets = useMemo(() => collectTargets(specs), [specs]);
+ const targetKey = targets.join("\n");
+
+ useEffect(() => {
+ let canceled = false;
+
+ const hydrate = async () => {
+ const databaseNames = new Set(targets.filter(isValidDatabaseName));
+ const databaseGroupNames = targets.filter(isValidDatabaseGroupName);
+ const groupResults = await Promise.allSettled(
+ databaseGroupNames.map((name) =>
+ useAppStore.getState().getOrFetchDBGroupByName(name, {
+ silent: true,
+ view: DatabaseGroupView.FULL,
+ })
+ )
+ );
+ if (canceled) {
+ return;
+ }
+
+ for (const result of groupResults) {
+ if (result.status !== "fulfilled") {
+ continue;
+ }
+ for (const database of result.value.matchedDatabases ?? []) {
+ databaseNames.add(database.name);
+ }
+ }
+ if (databaseNames.size > 0) {
+ await useAppStore
+ .getState()
+ .batchGetOrFetchDatabases([...databaseNames], true);
+ }
+ };
+
+ void hydrate().catch(() => {
+ // Resource-path labels remain usable when optional enrichment fails.
+ });
+ return () => {
+ canceled = true;
+ };
+ }, [targetKey, targets]);
+
+ return {
+ databaseGroupsByName,
+ databasesByName,
+ environmentList,
+ };
+};
+
+const collectTargets = (specs: Plan_Spec[]): string[] => {
+ const targets = new Set<string>();
+ for (const spec of specs) {
+ if (
+ spec.config.case !== "changeDatabaseConfig" &&
+ spec.config.case !== "exportDataConfig"
+ ) {
+ continue;
+ }
+ for (const target of spec.config.value.targets ?? []) {
+ targets.add(target);
+ }
+ }
+ return [...targets];
+};
diff --git a/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsx b/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsx
index f830597dd6..0696964027 100644
--- a/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsx
+++ b/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsx
@@ -115,6 +115,22 @@ describe("usePlanDetailPage", () => {
vi.restoreAllMocks();
});
+ test("defaults to every phase before review begins", async () => {
+ const { result } = renderHook(
+ () =>
+ usePlanDetailPage({
+ projectId: "foo",
+ planId: "plan-1",
+ }),
+ { wrapper }
+ );
+
+ await waitFor(() => expect(result.current.ready).toBe(true));
+ expect(result.current.activePhases).toEqual(
+ new Set(["changes", "review", "deploy"])
+ );
+ });
+
test("defaults to only the deploy phase on the deploy route query", async () => {
const { result } = renderHook(
() =>
@@ -137,7 +153,7 @@ describe("usePlanDetailPage", () => {
);
});
- test("keeps the specs collection focused on Changes without a phase query", async () => {
+ test("expands every phase when entering through the specs collection", async () => {
mocks.fetchPlanSnapshot.mockResolvedValue(
buildSnapshotPatch({
planId: "plan-1",
@@ -158,7 +174,9 @@ describe("usePlanDetailPage", () => {
);
await waitFor(() => expect(result.current.ready).toBe(true));
- expect(result.current.activePhases).toEqual(new Set(["changes"]));
+ expect(result.current.activePhases).toEqual(
+ new Set(["changes", "review", "deploy"])
+ );
expect(mocks.routerPush).not.toHaveBeenCalled();
expect(mocks.routerReplace).not.toHaveBeenCalled();
});
@@ -227,11 +245,11 @@ describe("usePlanDetailPage", () => {
await waitFor(() => expect(result.current.pageKey).toBe("foo/plan-2"));
await waitFor(() => expect(result.current.ready).toBe(true));
expect(result.current.activePhases).toEqual(
- new Set(["changes", "review"])
+ new Set(["changes", "review", "deploy"])
);
});
- test("defaults to the changes and review phases after an issue is created", async () => {
+ test("defaults to every phase after an issue is created", async () => {
mocks.fetchPlanSnapshot.mockResolvedValue(
buildSnapshotPatch({
issue: {
@@ -253,7 +271,7 @@ describe("usePlanDetailPage", () => {
await waitFor(() => expect(result.current.ready).toBe(true));
expect(result.current.activePhases.has("changes")).toBe(true);
expect(result.current.activePhases.has("review")).toBe(true);
- expect(result.current.activePhases.has("deploy")).toBe(false);
+ expect(result.current.activePhases.has("deploy")).toBe(true);
});
test("defaults to deploy while rollout creation is pending", async () => {
@@ -291,7 +309,7 @@ describe("usePlanDetailPage", () => {
expect(mocks.routerReplace).not.toHaveBeenCalled();
});
- test("keeps an explicit review phase on a reviewed rollout plan", async () => {
+ test("expands every phase for an explicit review route", async () => {
mocks.fetchPlanSnapshot.mockResolvedValue(
buildSnapshotPatch({
issue: {
@@ -320,23 +338,22 @@ describe("usePlanDetailPage", () => {
await waitFor(() => expect(result.current.ready).toBe(true));
expect(result.current.activePhases).toEqual(
- new Set(["changes", "review"])
+ new Set(["changes", "review", "deploy"])
);
expect(mocks.routerPush).not.toHaveBeenCalled();
expect(mocks.routerReplace).not.toHaveBeenCalled();
});
- test("lets a spec resource override a reviewed rollout plan's default", async () => {
+ test("expands every phase when entering a review-stage plan through a spec", async () => {
mocks.fetchPlanSnapshot.mockResolvedValue(
buildSnapshotPatch({
issue: {
name: "projects/foo/issues/1",
+ approvalStatus: ApprovalStatus.CHECKING,
+ draft: false,
+ status: IssueStatus.OPEN,
} as PlanDetailPageSnapshot["issue"],
planId: "plan-1",
- rollout: {
- name: "projects/foo/rollouts/1",
- stages: [],
- } as unknown as PlanDetailPageSnapshot["rollout"],
})
);
@@ -353,11 +370,11 @@ describe("usePlanDetailPage", () => {
await waitFor(() => expect(result.current.ready).toBe(true));
expect(result.current.activePhases.has("changes")).toBe(true);
- expect(result.current.activePhases.has("review")).toBe(false);
- expect(result.current.activePhases.has("deploy")).toBe(false);
+ expect(result.current.activePhases.has("review")).toBe(true);
+ expect(result.current.activePhases.has("deploy")).toBe(true);
});
- test("has review default phases on the first ready render", async () => {
+ test("has every phase on the first ready render for review plans", async () => {
mocks.fetchPlanSnapshot.mockResolvedValue(
buildSnapshotPatch({
issue: {
@@ -385,7 +402,7 @@ describe("usePlanDetailPage", () => {
await waitFor(() => expect(result.current.ready).toBe(true));
expect(readyRenders[0].has("changes")).toBe(true);
expect(readyRenders[0].has("review")).toBe(true);
- expect(readyRenders[0].has("deploy")).toBe(false);
+ expect(readyRenders[0].has("deploy")).toBe(true);
});
test("has deploy as the only phase on the first ready render for rollout plans", async () => {
@@ -743,7 +760,7 @@ describe("usePlanDetailPage", () => {
await waitFor(() => expect(result.current.ready).toBe(true));
expect(result.current.activePhases).toEqual(
- new Set(["changes", "review"])
+ new Set(["changes", "review", "deploy"])
);
act(() => result.current.togglePhase("review"));
diff --git a/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.ts b/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.ts
index ad88adb8a4..5181c6f939 100644
--- a/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.ts
+++ b/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.ts
@@ -135,10 +135,14 @@ const preserveSnapshotIdentities = (
};
const getDefaultActivePhases = (phase: PlanDetailPhase): PlanDetailPhase[] => {
- if (phase === PLAN_DETAIL_PHASE_REVIEW) {
- return [PLAN_DETAIL_PHASE_CHANGES, PLAN_DETAIL_PHASE_REVIEW];
+ if (phase === PLAN_DETAIL_PHASE_DEPLOY) {
+ return [PLAN_DETAIL_PHASE_DEPLOY];
}
- return [phase];
+ return [
+ PLAN_DETAIL_PHASE_CHANGES,
+ PLAN_DETAIL_PHASE_REVIEW,
+ PLAN_DETAIL_PHASE_DEPLOY,
+ ];
};
type PhaseSelection = {
diff --git a/frontend/src/routes/project/plan-detail/utils/changeReference.test.ts b/frontend/src/routes/project/plan-detail/utils/changeReference.test.ts
new file mode 100644
index 0000000000..67bfa4eaf3
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/utils/changeReference.test.ts
@@ -0,0 +1,480 @@
+import type { TFunction } from "i18next";
+import { describe, expect, it } from "vitest";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
+import type { Environment } from "@/types/v1/environment";
+import {
+ derivePlanChangeReference,
+ type PlanChangeReferenceResources,
+ splitPlanChangeReferenceLabel,
+} from "./changeReference";
+
+const t = ((key: string, options?: Record<string, string | number>): string => {
+ if (key === "plan.spec.change-reference.accessible-label") {
+ return `Change ${options?.index}: ${options?.label}`;
+ }
+ if (key === "plan.spec.change-reference.database-count") {
+ return `${options?.count} databases`;
+ }
+ if (key === "plan.spec.change-reference.environment-overflow") {
+ return `${options?.environment} +${options?.count} environments`;
+ }
+ if (key === "plan.spec.change-reference.new-change") {
+ return "New change";
+ }
+ return key;
+}) as TFunction;
+
+const DB_ORDERS = "instances/prod/databases/orders";
+const DB_CUSTOMERS = "instances/staging/databases/customers";
+const DB_AUDIT = "instances/dev/databases/audit";
+
+const resources = ({
+ databases = [],
+ environments = [],
+}: {
+ databases?: Database[];
+ environments?: Environment[];
+} = {}): PlanChangeReferenceResources => ({
+ databaseGroupsByName: {},
+ databasesByName: Object.fromEntries(
+ databases.map((database) => [database.name, database])
+ ),
+ environmentList: environments,
+});
+
+const changeSpec = (id: string, targets: string[]): Plan_Spec =>
+ ({
+ id,
+ config: {
+ case: "changeDatabaseConfig",
+ value: { targets },
+ },
+ }) as Plan_Spec;
+
+describe("derivePlanChangeReference", () => {
+ it("uses the database name for one database", () => {
+ const spec = changeSpec("spec-1", [DB_ORDERS]);
+ const reference = derivePlanChangeReference({
+ index: 0,
+ resources: resources(),
+ siblings: [spec],
+ spec,
+ t,
+ });
+
+ expect(reference).toMatchObject({
+ accessibleLabel: "Change 1: orders",
+ icon: "database",
+ index: 1,
+ label: "orders",
+ showIndex: false,
+ showIndexWithCountLabel: false,
+ specId: "spec-1",
+ });
+ expect(reference.countLabel).toBeUndefined();
+ });
+
+ it("provides a count and deployment-ordered environment fallback", () => {
+ const spec = changeSpec("spec-1", [DB_ORDERS, DB_CUSTOMERS, DB_AUDIT]);
+ const reference = derivePlanChangeReference({
+ index: 0,
+ resources: resources({
+ databases: [
+ {
+ name: DB_ORDERS,
+ effectiveEnvironment: "environments/prod",
+ } as Database,
+ {
+ name: DB_CUSTOMERS,
+ effectiveEnvironment: "environments/staging",
+ } as Database,
+ {
+ name: DB_AUDIT,
+ effectiveEnvironment: "environments/dev",
+ } as Database,
+ ],
+ environments: [
+ {
+ name: "environments/dev",
+ order: 0,
+ title: "Development",
+ } as Environment,
+ {
+ name: "environments/staging",
+ order: 1,
+ title: "Staging",
+ } as Environment,
+ {
+ name: "environments/prod",
+ order: 2,
+ title: "Production",
+ } as Environment,
+ ],
+ }),
+ siblings: [spec],
+ spec,
+ t,
+ });
+
+ expect(reference.label).toBe("orders, customers, audit");
+ expect(reference.countLabel).toBe(
+ "3 databases · Production +2 environments"
+ );
+ });
+
+ it("uses the database group resource ID without requiring hydration", () => {
+ const spec = changeSpec("spec-1", [
+ "projects/acme/databaseGroups/tenant-prod",
+ ]);
+ const reference = derivePlanChangeReference({
+ index: 0,
+ resources: resources(),
+ siblings: [spec],
+ spec,
+ t,
+ });
+
+ expect(reference).toMatchObject({
+ icon: "database-group",
+ label: "tenant-prod",
+ });
+ });
+
+ it("supports create-database and export specs", () => {
+ const createSpec = {
+ id: "spec-create",
+ config: {
+ case: "createDatabaseConfig",
+ value: {
+ database: "reporting",
+ target: "instances/prod",
+ },
+ },
+ } as Plan_Spec;
+ const exportSpec = {
+ id: "spec-export",
+ config: {
+ case: "exportDataConfig",
+ value: { targets: [DB_ORDERS] },
+ },
+ } as Plan_Spec;
+
+ expect(
+ derivePlanChangeReference({
+ index: 0,
+ resources: resources(),
+ siblings: [createSpec],
+ spec: createSpec,
+ t,
+ })
+ ).toMatchObject({
+ icon: "create-database",
+ label: "reporting",
+ });
+ expect(
+ derivePlanChangeReference({
+ index: 0,
+ resources: resources(),
+ siblings: [exportSpec],
+ spec: exportSpec,
+ t,
+ })
+ ).toMatchObject({
+ icon: "export",
+ label: "orders",
+ });
+ });
+
+ it("keeps release-backed changes target-derived", () => {
+ const spec = {
+ id: "spec-release",
+ config: {
+ case: "changeDatabaseConfig",
+ value: {
+ release: "projects/acme/releases/release-1",
+ targets: [DB_ORDERS],
+ },
+ },
+ } as Plan_Spec;
+
+ expect(
+ derivePlanChangeReference({
+ index: 0,
+ resources: resources(),
+ siblings: [spec],
+ spec,
+ t,
+ })
+ ).toMatchObject({
+ icon: "database",
+ label: "orders",
+ });
+ });
+
+ it("uses New change for an empty draft", () => {
+ const spec = changeSpec("spec-1", []);
+ const reference = derivePlanChangeReference({
+ index: 0,
+ resources: resources(),
+ siblings: [spec],
+ spec,
+ t,
+ });
+
+ expect(reference.label).toBe("New change");
+ });
+
+ it("falls back to readable resource text and then a short spec ID", () => {
+ const malformedTarget = changeSpec("spec-target", [
+ "legacy/targets/orphaned",
+ ]);
+ const unknownConfig = {
+ id: "2f2894b5-50e8-4d7b-9c58-5f5f08109460",
+ config: { case: undefined, value: undefined },
+ } as unknown as Plan_Spec;
+
+ expect(
+ derivePlanChangeReference({
+ index: 0,
+ resources: resources(),
+ siblings: [malformedTarget],
+ spec: malformedTarget,
+ t,
+ }).label
+ ).toBe("orphaned");
+ expect(
+ derivePlanChangeReference({
+ index: 0,
+ resources: resources(),
+ siblings: [unknownConfig],
+ spec: unknownConfig,
+ t,
+ }).label
+ ).toBe("2f2894b5");
+ });
+
+ it("keeps a usable count when resource enrichment is unavailable", () => {
+ const spec = changeSpec("spec-1", [DB_ORDERS, DB_CUSTOMERS]);
+ const reference = derivePlanChangeReference({
+ index: 0,
+ resources: resources(),
+ siblings: [spec],
+ spec,
+ t,
+ });
+
+ expect(reference.label).toBe("orders, customers");
+ expect(reference.countLabel).toBe("2 databases");
+ });
+
+ it("adds an environment qualifier when sibling labels collide", () => {
+ const prodSpec = changeSpec("spec-prod", [
+ "instances/prod/databases/orders",
+ ]);
+ const stagingSpec = changeSpec("spec-staging", [
+ "instances/staging/databases/orders",
+ ]);
+ const reference = derivePlanChangeReference({
+ index: 0,
+ resources: resources({
+ databases: [
+ {
+ name: "instances/prod/databases/orders",
+ effectiveEnvironment: "environments/prod",
+ } as Database,
+ {
+ name: "instances/staging/databases/orders",
+ effectiveEnvironment: "environments/staging",
+ } as Database,
+ ],
+ environments: [
+ {
+ name: "environments/staging",
+ order: 0,
+ title: "Staging",
+ } as Environment,
+ {
+ name: "environments/prod",
+ order: 1,
+ title: "Production",
+ } as Environment,
+ ],
+ }),
+ siblings: [prodSpec, stagingSpec],
+ spec: prodSpec,
+ t,
+ });
+
+ expect(reference.label).toBe("orders · Production");
+ expect(reference.showIndex).toBe(false);
+ expect(reference.showIndexWithCountLabel).toBe(false);
+ });
+
+ it("uses the instance when duplicate labels share an environment", () => {
+ const primarySpec = changeSpec("spec-primary", [
+ "instances/primary/databases/orders",
+ ]);
+ const replicaSpec = changeSpec("spec-replica", [
+ "instances/replica/databases/orders",
+ ]);
+ const reference = derivePlanChangeReference({
+ index: 0,
+ resources: resources({
+ databases: [
+ {
+ name: "instances/primary/databases/orders",
+ effectiveEnvironment: "environments/prod",
+ instanceResource: { title: "Primary" },
+ } as Database,
+ {
+ name: "instances/replica/databases/orders",
+ effectiveEnvironment: "environments/prod",
+ instanceResource: { title: "Replica" },
+ } as Database,
+ ],
+ environments: [
+ {
+ name: "environments/prod",
+ order: 0,
+ title: "Production",
+ } as Environment,
+ ],
+ }),
+ siblings: [primarySpec, replicaSpec],
+ spec: primarySpec,
+ t,
+ });
+
+ expect(reference.label).toBe("orders · Primary");
+ expect(reference.showIndex).toBe(false);
+ expect(reference.showIndexWithCountLabel).toBe(false);
+ });
+
+ it("keeps identical-target siblings distinct through their indexes", () => {
+ const first = changeSpec("spec-1", [DB_ORDERS]);
+ const second = changeSpec("spec-2", [DB_ORDERS]);
+
+ expect(
+ derivePlanChangeReference({
+ index: 0,
+ resources: resources(),
+ siblings: [first, second],
+ spec: first,
+ t,
+ })
+ ).toMatchObject({
+ accessibleLabel: "Change 1: orders",
+ label: "orders",
+ showIndex: true,
+ showIndexWithCountLabel: false,
+ });
+ expect(
+ derivePlanChangeReference({
+ index: 1,
+ resources: resources(),
+ siblings: [first, second],
+ spec: second,
+ t,
+ })
+ ).toMatchObject({
+ accessibleLabel: "Change 2: orders",
+ label: "orders",
+ showIndex: true,
+ showIndexWithCountLabel: false,
+ });
+ });
+
+ it("shows indexes when different long labels share a count fallback", () => {
+ const first = changeSpec("spec-1", [DB_ORDERS, DB_CUSTOMERS]);
+ const second = changeSpec("spec-2", [
+ DB_AUDIT,
+ "instances/prod/databases/payments",
+ ]);
+
+ expect(
+ derivePlanChangeReference({
+ index: 0,
+ resources: resources(),
+ siblings: [first, second],
+ spec: first,
+ t,
+ })
+ ).toMatchObject({
+ showIndex: false,
+ showIndexWithCountLabel: true,
+ });
+ expect(
+ derivePlanChangeReference({
+ index: 1,
+ resources: resources(),
+ siblings: [first, second],
+ spec: second,
+ t,
+ })
+ ).toMatchObject({
+ showIndex: false,
+ showIndexWithCountLabel: true,
+ });
+ });
+
+ it("does not show indexes when icons distinguish equal titles", () => {
+ const change = changeSpec("spec-change", [DB_ORDERS]);
+ const dataExport = {
+ id: "spec-export",
+ config: {
+ case: "exportDataConfig",
+ value: { targets: [DB_ORDERS] },
+ },
+ } as Plan_Spec;
+
+ expect(
+ derivePlanChangeReference({
+ index: 0,
+ resources: resources(),
+ siblings: [change, dataExport],
+ spec: change,
+ t,
+ }).showIndex
+ ).toBe(false);
+ expect(
+ derivePlanChangeReference({
+ index: 1,
+ resources: resources(),
+ siblings: [change, dataExport],
+ spec: dataExport,
+ t,
+ }).showIndex
+ ).toBe(false);
+ });
+});
+
+describe("splitPlanChangeReferenceLabel", () => {
+ it("splits without breaking a grapheme cluster", () => {
+ const text = "customer_orders_👨‍👩‍👧‍👦_production_archive";
+ const split = splitPlanChangeReferenceLabel(text);
+
+ expect(split.prefix + split.suffix).toBe(text);
+ expect(split.suffix).toBe("on_archive");
+ });
+
+ it("falls back to end truncation without Intl.Segmenter", () => {
+ const segmenter = Intl.Segmenter;
+ Object.defineProperty(Intl, "Segmenter", {
+ configurable: true,
+ value: undefined,
+ });
+ try {
+ const text = "customer_orders_production_archive";
+ expect(splitPlanChangeReferenceLabel(text)).toEqual({
+ prefix: text,
+ suffix: "",
+ });
+ } finally {
+ Object.defineProperty(Intl, "Segmenter", {
+ configurable: true,
+ value: segmenter,
+ });
+ }
+ });
+});
diff --git a/frontend/src/routes/project/plan-detail/utils/changeReference.ts b/frontend/src/routes/project/plan-detail/utils/changeReference.ts
new file mode 100644
index 0000000000..8f56430c4d
--- /dev/null
+++ b/frontend/src/routes/project/plan-detail/utils/changeReference.ts
@@ -0,0 +1,344 @@
+import type { TFunction } from "i18next";
+import { isValidDatabaseGroupName, isValidDatabaseName } from "@/types";
+import type { DatabaseGroup } from "@/types/proto-es/v1/database_group_service_pb";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
+import type { Environment } from "@/types/v1/environment";
+import { extractDatabaseResourceName } from "@/utils";
+import { extractDatabaseGroupName } from "@/utils/v1/databaseGroup";
+
+export type PlanChangeReferenceIcon =
+ | "create-database"
+ | "database"
+ | "database-group"
+ | "export";
+
+export interface PlanChangeReferenceResources {
+ databasesByName: Record<string, Database | undefined>;
+ databaseGroupsByName: Record<string, DatabaseGroup | undefined>;
+ environmentList: Environment[];
+}
+
+export interface PlanChangeReference {
+ accessibleLabel: string;
+ countLabel?: string;
+ fullLabel: string;
+ icon: PlanChangeReferenceIcon;
+ index: number;
+ label: string;
+ showIndex: boolean;
+ showIndexWithCountLabel: boolean;
+ specId: string;
+}
+
+interface BaseReference {
+ countLabel?: string;
+ environmentSummary: string;
+ icon: PlanChangeReferenceIcon;
+ instanceSummary: string;
+ label: string;
+}
+
+const SHORT_SPEC_ID_LENGTH = 8;
+const MIDDLE_ELLIPSIS_SUFFIX_LENGTH = 10;
+const MIDDLE_ELLIPSIS_MIN_LENGTH = 18;
+
+export const derivePlanChangeReference = ({
+ index,
+ resources,
+ siblings,
+ spec,
+ t,
+}: {
+ index: number;
+ resources: PlanChangeReferenceResources;
+ siblings: Plan_Spec[];
+ spec: Plan_Spec;
+ t: TFunction;
+}): PlanChangeReference => {
+ const reference = deriveQualifiedReference(spec, siblings, resources, t);
+ const siblingReferences = siblings
+ .filter((sibling) => sibling.id !== spec.id)
+ .map((sibling) => deriveQualifiedReference(sibling, siblings, resources, t))
+ .filter((sibling) => sibling.icon === reference.icon);
+ const showIndex = siblingReferences.some(
+ (sibling) => sibling.label === reference.label
+ );
+ const showIndexWithCountLabel = Boolean(
+ reference.countLabel &&
+ siblingReferences.some(
+ (sibling) => sibling.countLabel === reference.countLabel
+ )
+ );
+
+ const fullLabel = reference.label;
+ return {
+ accessibleLabel: t("plan.spec.change-reference.accessible-label", {
+ index: index + 1,
+ label: fullLabel,
+ }),
+ countLabel: reference.countLabel,
+ fullLabel,
+ icon: reference.icon,
+ index: index + 1,
+ label: reference.label,
+ showIndex,
+ showIndexWithCountLabel,
+ specId: spec.id,
+ };
+};
+
+const deriveQualifiedReference = (
+ spec: Plan_Spec,
+ siblings: Plan_Spec[],
+ resources: PlanChangeReferenceResources,
+ t: TFunction
+): BaseReference => {
+ const base = deriveBaseReference(spec, resources, t);
+ const matchingSiblings = siblings
+ .filter((sibling) => sibling.id !== spec.id)
+ .map((sibling) => deriveBaseReference(sibling, resources, t))
+ .filter(
+ (sibling) => sibling.icon === base.icon && sibling.label === base.label
+ );
+
+ let label = base.label;
+ let countLabel = base.countLabel;
+ if (matchingSiblings.length > 0) {
+ const environments = new Set(
+ matchingSiblings.map((sibling) => sibling.environmentSummary)
+ );
+ environments.add(base.environmentSummary);
+ if (base.environmentSummary && environments.size > 1) {
+ label = appendQualifier(label, base.environmentSummary);
+ countLabel = appendQualifier(countLabel, base.environmentSummary);
+ } else {
+ const instances = new Set(
+ matchingSiblings.map((sibling) => sibling.instanceSummary)
+ );
+ instances.add(base.instanceSummary);
+ if (base.instanceSummary && instances.size > 1) {
+ label = appendQualifier(label, base.instanceSummary);
+ countLabel = appendQualifier(countLabel, base.instanceSummary);
+ }
+ }
+ }
+
+ return {
+ ...base,
+ countLabel,
+ label,
+ };
+};
+
+export const splitPlanChangeReferenceLabel = (
+ text: string
+): { prefix: string; suffix: string } => {
+ if (typeof Intl === "undefined" || typeof Intl.Segmenter !== "function") {
+ return { prefix: text, suffix: "" };
+ }
+ const graphemes = Array.from(
+ new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(text),
+ ({ segment }) => segment
+ );
+ if (graphemes.length <= MIDDLE_ELLIPSIS_MIN_LENGTH) {
+ return { prefix: text, suffix: "" };
+ }
+ const suffixStart = Math.max(
+ 1,
+ graphemes.length - MIDDLE_ELLIPSIS_SUFFIX_LENGTH
+ );
+ return {
+ prefix: graphemes.slice(0, suffixStart).join(""),
+ suffix: graphemes.slice(suffixStart).join(""),
+ };
+};
+
+const deriveBaseReference = (
+ spec: Plan_Spec,
+ resources: PlanChangeReferenceResources,
+ t: TFunction
+): BaseReference => {
+ if (spec.config.case === "createDatabaseConfig") {
+ return {
+ environmentSummary: environmentTitle(
+ spec.config.value.environment,
+ resources.environmentList
+ ),
+ icon: "create-database",
+ instanceSummary: resourceTail(spec.config.value.target),
+ label:
+ spec.config.value.database.trim() ||
+ t("plan.spec.change-reference.new-change"),
+ };
+ }
+
+ if (
+ spec.config.case !== "changeDatabaseConfig" &&
+ spec.config.case !== "exportDataConfig"
+ ) {
+ return {
+ environmentSummary: "",
+ icon: "database",
+ instanceSummary: "",
+ label:
+ spec.id.slice(0, SHORT_SPEC_ID_LENGTH) ||
+ t("plan.spec.change-reference.new-change"),
+ };
+ }
+
+ const targets = spec.config.value.targets ?? [];
+ const groupTarget = targets.find(isValidDatabaseGroupName);
+ const icon: PlanChangeReferenceIcon =
+ spec.config.case === "exportDataConfig"
+ ? "export"
+ : groupTarget
+ ? "database-group"
+ : "database";
+
+ if (groupTarget) {
+ const databaseNames =
+ resources.databaseGroupsByName[groupTarget]?.matchedDatabases?.map(
+ (database) => database.name
+ ) ?? [];
+ return {
+ environmentSummary: environmentSummary(databaseNames, resources, t),
+ icon,
+ instanceSummary: instanceSummary(databaseNames, resources),
+ label:
+ extractDatabaseGroupName(groupTarget) ||
+ resourceTail(groupTarget) ||
+ groupTarget,
+ };
+ }
+
+ const databaseNames = targets.filter(isValidDatabaseName);
+ const labels = targets
+ .map(targetLabel)
+ .filter((label): label is string => Boolean(label));
+ const label =
+ labels.length > 0
+ ? labels.join(", ")
+ : t("plan.spec.change-reference.new-change");
+ const environment = environmentSummary(databaseNames, resources, t);
+ const countLabel =
+ labels.length > 1
+ ? appendQualifier(
+ t("plan.spec.change-reference.database-count", {
+ count: labels.length,
+ }),
+ environment
+ )
+ : undefined;
+
+ return {
+ countLabel,
+ environmentSummary: environment,
+ icon,
+ instanceSummary: instanceSummary(databaseNames, resources),
+ label,
+ };
+};
+
+function appendQualifier(label: string, qualifier: string): string;
+function appendQualifier(
+ label: string | undefined,
+ qualifier: string
+): string | undefined;
+function appendQualifier(
+ label: string | undefined,
+ qualifier: string
+): string | undefined {
+ if (!label || !qualifier || label.endsWith(` · ${qualifier}`)) {
+ return label;
+ }
+ return `${label} · ${qualifier}`;
+}
+
+const targetLabel = (target: string): string => {
+ if (isValidDatabaseName(target)) {
+ return extractDatabaseResourceName(target).databaseName;
+ }
+ if (isValidDatabaseGroupName(target)) {
+ return extractDatabaseGroupName(target);
+ }
+ return resourceTail(target) || target;
+};
+
+const resourceTail = (resource: string): string => {
+ return resource.split("/").filter(Boolean).at(-1) ?? "";
+};
+
+const environmentSummary = (
+ databaseNames: string[],
+ resources: PlanChangeReferenceResources,
+ t: TFunction
+): string => {
+ const environmentNames = new Set(
+ databaseNames
+ .map((name) => resources.databasesByName[name])
+ .map(
+ (database) =>
+ database?.effectiveEnvironment ??
+ database?.instanceResource?.environment ??
+ ""
+ )
+ .filter(Boolean)
+ );
+ const environments = [...environmentNames]
+ .map((name) => ({
+ name,
+ order:
+ resources.environmentList.find(
+ (environment) => environment.name === name
+ )?.order ?? Number.MAX_SAFE_INTEGER,
+ title: environmentTitle(name, resources.environmentList),
+ }))
+ .sort(
+ (left, right) =>
+ left.order - right.order || left.name.localeCompare(right.name)
+ );
+ const lastEnvironment = environments.at(-1);
+ if (!lastEnvironment) {
+ return "";
+ }
+ if (environments.length === 1) {
+ return lastEnvironment.title;
+ }
+ return t("plan.spec.change-reference.environment-overflow", {
+ count: environments.length - 1,
+ environment: lastEnvironment.title,
+ });
+};
+
+const environmentTitle = (
+ name: string,
+ environmentList: Environment[]
+): string => {
+ if (!name) {
+ return "";
+ }
+ return (
+ environmentList.find((environment) => environment.name === name)?.title ||
+ resourceTail(name) ||
+ name
+ );
+};
+
+const instanceSummary = (
+ databaseNames: string[],
+ resources: PlanChangeReferenceResources
+): string => {
+ const instances = new Set(
+ databaseNames
+ .map((name) => {
+ const database = resources.databasesByName[name];
+ return (
+ database?.instanceResource?.title ||
+ extractDatabaseResourceName(name).instanceName
+ );
+ })
+ .filter(Boolean)
+ );
+ return instances.size === 1 ? ([...instances][0] ?? "") : "";
+};
diff --git a/frontend/src/routes/project/plan-detail/utils/spec.ts b/frontend/src/routes/project/plan-detail/utils/spec.ts
index 7d9924445d..15f392b6c8 100644
--- a/frontend/src/routes/project/plan-detail/utils/spec.ts
+++ b/frontend/src/routes/project/plan-detail/utils/spec.ts
@@ -1,4 +1,3 @@
-import type { TFunction } from "i18next";
import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
export const getSelectedSpec = ({
@@ -20,16 +19,3 @@ export const isReleaseBackedPlan = (specs: Plan_Spec[]): boolean => {
!!spec.config.value.release
);
};
-
-export const getSpecTitle = (spec: Plan_Spec, t: TFunction): string => {
- if (spec.config.case === "createDatabaseConfig") {
- return t("common.database");
- }
- if (spec.config.case === "changeDatabaseConfig") {
- return t("plan.spec.type.database-change");
- }
- if (spec.config.case === "exportDataConfig") {
- return t("common.export");
- }
- return t("common.unknown");
-};
diff --git a/frontend/src/stores/app/database.ts b/frontend/src/stores/app/database.ts
index ebc1eed324..131dab2778 100644
--- a/frontend/src/stores/app/database.ts
+++ b/frontend/src/stores/app/database.ts
@@ -49,9 +49,13 @@ export const createDatabaseSlice: AppSliceCreator<DatabaseSlice> = (
// projects and guarantees `instanceResource` is populated (with a fallback)
// so consumers can read engine / instance off any database.
const composeDatabases = async (
- databases: Database[]
+ databases: Database[],
+ silent = false
): Promise<Database[]> => {
- await get().batchFetchProjects(databases.map((db) => db.project));
+ await get().batchFetchProjects(
+ databases.map((db) => db.project),
+ silent
+ );
for (const database of databases) {
if (!database.instanceResource) {
database.instanceResource = {
@@ -66,9 +70,10 @@ export const createDatabaseSlice: AppSliceCreator<DatabaseSlice> = (
// Compose then immutably merge into the by-name cache; returns the composed
// list so callers can hand it straight back to their consumers.
const upsertDatabases = async (
- databases: Database[]
+ databases: Database[],
+ silent = false
): Promise<Database[]> => {
- const composed = await composeDatabases(databases);
+ const composed = await composeDatabases(databases, silent);
set((state) => {
const next = { ...state.databasesByName };
for (const db of composed) {
@@ -94,7 +99,7 @@ export const createDatabaseSlice: AppSliceCreator<DatabaseSlice> = (
contextValues: createContextValues().set(silentContextKey, silent),
})
.then(async (database: Database) => {
- const [composed] = await composeDatabases([database]);
+ const [composed] = await composeDatabases([database], silent);
set((state) => {
const { [name]: _, ...databaseRequests } = state.databaseRequests;
return {
@@ -156,16 +161,19 @@ export const createDatabaseSlice: AppSliceCreator<DatabaseSlice> = (
getOrFetchDatabaseByName: async (name, silent = true) =>
(await fetchByName(name, silent)) ?? getUnknownDatabase(),
- batchFetchDatabases: async (names) => {
+ batchFetchDatabases: async (names, silent = false) => {
const validNames = uniq(names).filter(isValidDatabaseName);
if (!validNames.length) return [];
const response = await databaseServiceClientConnect.batchGetDatabases(
createProto(BatchGetDatabasesRequestSchema, {
parent: "-",
names: validNames,
- })
+ }),
+ {
+ contextValues: createContextValues().set(silentContextKey, silent),
+ }
);
- const composed = await composeDatabases(response.databases);
+ const composed = await composeDatabases(response.databases, silent);
set((state) => {
const next = { ...state.databasesByName };
for (const db of composed) {
@@ -176,13 +184,13 @@ export const createDatabaseSlice: AppSliceCreator<DatabaseSlice> = (
return composed;
},
- batchGetOrFetchDatabases: async (names) => {
+ batchGetOrFetchDatabases: async (names, silent = false) => {
const validNames = uniq(names).filter(isValidDatabaseName);
const pending = validNames.filter((name) => {
const cached = get().databasesByName[name];
return !(cached && isValidDatabaseName(cached.name));
});
- await get().batchFetchDatabases(pending);
+ await get().batchFetchDatabases(pending, silent);
return validNames.map((name) => get().getDatabaseByName(name));
},
@@ -222,7 +230,10 @@ export const createDatabaseSlice: AppSliceCreator<DatabaseSlice> = (
if (parent.startsWith("instances/") && !skipCacheRemoval) {
get().removeCacheByInstance(parent);
}
- const composed = await upsertDatabases(response.databases);
+ const composed = await upsertDatabases(
+ response.databases,
+ silent ?? false
+ );
return {
databases: composed,
nextPageToken: response.nextPageToken,
diff --git a/frontend/src/stores/app/databaseAccess.ts b/frontend/src/stores/app/databaseAccess.ts
index 912f837683..ecd7e6934a 100644
--- a/frontend/src/stores/app/databaseAccess.ts
+++ b/frontend/src/stores/app/databaseAccess.ts
@@ -33,7 +33,10 @@ type DatabaseAccess = {
name: string,
silent?: boolean
) => Promise<Database>;
- batchGetOrFetchDatabases: (names: string[]) => Promise<Database[]>;
+ batchGetOrFetchDatabases: (
+ names: string[],
+ silent?: boolean
+ ) => Promise<Database[]>;
fetchDatabases: (params: DatabaseListParams) => Promise<{
databases: Database[];
nextPageToken: string;
@@ -63,8 +66,8 @@ export const getDatabaseByName = (name: string) =>
export const getOrFetchDatabaseByName = (name: string, silent?: boolean) =>
databaseAccess.getOrFetchDatabaseByName(name, silent);
-export const batchGetOrFetchDatabases = (names: string[]) =>
- databaseAccess.batchGetOrFetchDatabases(names);
+export const batchGetOrFetchDatabases = (names: string[], silent?: boolean) =>
+ databaseAccess.batchGetOrFetchDatabases(names, silent);
export const fetchDatabases = (params: DatabaseListParams) =>
databaseAccess.fetchDatabases(params);
diff --git a/frontend/src/stores/app/index.test.ts b/frontend/src/stores/app/index.test.ts
index be154a1f86..60d4231a3e 100644
--- a/frontend/src/stores/app/index.test.ts
+++ b/frontend/src/stores/app/index.test.ts
@@ -1,5 +1,6 @@
import { create as createProto } from "@bufbuild/protobuf";
import { beforeEach, describe, expect, test, vi } from "vitest";
+import { silentContextKey } from "@/api/context-key";
import { isValidDatabaseGroupName, UNKNOWN_PROJECT_NAME } from "@/types";
import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";
import {
@@ -1423,11 +1424,21 @@ describe("useAppStore", () => {
const projects = await store
.getState()
- .batchFetchProjects([projectA.name, projectB.name]);
+ .batchFetchProjects([projectA.name, projectB.name], true);
expect(projects).toEqual([projectA, projectB]);
expect(mocks.batchGetProjects).toHaveBeenCalledTimes(1);
expect(mocks.getProject).toHaveBeenCalledTimes(2);
+ expect(
+ mocks.batchGetProjects.mock.calls[0]?.[1]?.contextValues.get(
+ silentContextKey
+ )
+ ).toBe(true);
+ expect(
+ mocks.getProject.mock.calls.every(
+ (call) => call[1]?.contextValues.get(silentContextKey) === true
+ )
+ ).toBe(true);
});
test("keeps default project only when searchProjects opts in", async () => {
@@ -1878,6 +1889,30 @@ describe("useAppStore", () => {
expect(store.getState().databasesByName[dbName]).toEqual(database);
});
+ test("keeps database and project batch enrichment silent", async () => {
+ const dbName = "instances/i1/databases/db1";
+ const database = createProto(DatabaseSchema$, {
+ name: dbName,
+ project: projectA.name,
+ });
+ mocks.batchGetDatabases.mockResolvedValue({ databases: [database] });
+ mocks.batchGetProjects.mockResolvedValue({ projects: [projectA] });
+ const store = createAppStore();
+
+ await store.getState().batchGetOrFetchDatabases([dbName], true);
+
+ expect(
+ mocks.batchGetDatabases.mock.calls[0]?.[1]?.contextValues.get(
+ silentContextKey
+ )
+ ).toBe(true);
+ expect(
+ mocks.batchGetProjects.mock.calls[0]?.[1]?.contextValues.get(
+ silentContextKey
+ )
+ ).toBe(true);
+ });
+
test("fetchDatabases populates databasesByName from the list response", async () => {
const dbA = createProto(DatabaseSchema$, {
name: "instances/i1/databases/db1",
diff --git a/frontend/src/stores/app/project.ts b/frontend/src/stores/app/project.ts
index 0d9b049a72..f0e4232daf 100644
--- a/frontend/src/stores/app/project.ts
+++ b/frontend/src/stores/app/project.ts
@@ -186,7 +186,7 @@ export const createProjectSlice: AppSliceCreator<ProjectSlice> = (set, get) => {
return request;
},
- batchFetchProjects: async (names) => {
+ batchFetchProjects: async (names, silent = false) => {
const validNames = [...new Set(names)].filter(
(name) => isValidProjectName(name) && name !== defaultProjectName(get)
);
@@ -194,7 +194,10 @@ export const createProjectSlice: AppSliceCreator<ProjectSlice> = (set, get) => {
try {
const response = await projectServiceClientConnect.batchGetProjects(
- createProto(BatchGetProjectsRequestSchema, { names: validNames })
+ createProto(BatchGetProjectsRequestSchema, { names: validNames }),
+ {
+ contextValues: createContextValues().set(silentContextKey, silent),
+ }
);
set((state) => ({
projectsByName: {
@@ -207,7 +210,7 @@ export const createProjectSlice: AppSliceCreator<ProjectSlice> = (set, get) => {
return response.projects;
} catch {
const projects = await Promise.all(
- validNames.map((name) => get().fetchProject(name))
+ validNames.map((name) => get().fetchProject(name, silent))
);
return projects.filter(
(project): project is NonNullable<typeof project> => Boolean(project)
diff --git a/frontend/src/stores/app/types.ts b/frontend/src/stores/app/types.ts
index 88e929ca36..25f2214c45 100644
--- a/frontend/src/stores/app/types.ts
+++ b/frontend/src/stores/app/types.ts
@@ -391,7 +391,7 @@ export type ProjectSlice = {
silent?: boolean
) => Promise<Project | undefined>;
getOrFetchProjectByName: (name: string, silent?: boolean) => Promise<Project>;
- batchFetchProjects: (names: string[]) => Promise<Project[]>;
+ batchFetchProjects: (names: string[], silent?: boolean) => Promise<Project[]>;
// Returns ALL requested projects (fetching the missing ones first),
// resolved through `getProjectByName` so the placeholder is filled in.
batchGetOrFetchProjects: (names: string[]) => Promise<Project[]>;
@@ -522,8 +522,14 @@ export type DatabaseSlice = {
name: string,
silent?: boolean
) => Promise<Database>;
- batchFetchDatabases: (names: string[]) => Promise<Database[]>;
- batchGetOrFetchDatabases: (names: string[]) => Promise<Database[]>;
+ batchFetchDatabases: (
+ names: string[],
+ silent?: boolean
+ ) => Promise<Database[]>;
+ batchGetOrFetchDatabases: (
+ names: string[],
+ silent?: boolean
+ ) => Promise<Database[]>;
fetchDatabases: (params: DatabaseListParams) => Promise<{
databases: Database[];
nextPageToken: string;