Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(plan-detail): stabilize resource routing and phase transitions (#21004)
boojackde717fbd0517
diff --git a/docs/plans/2026-07-22-plan-detail-resource-routing-design.md b/docs/plans/2026-07-22-plan-detail-resource-routing-design.mdnew file mode 100644index 0000000000..0133072578--- /dev/null+++ b/docs/plans/2026-07-22-plan-detail-resource-routing-design.md@@ -0,0 +1,443 @@+# Plan Detail Resource Routing Design++**Date:** 2026-07-22+**Status:** Implemented+**Issue:** [BYT-9913](https://linear.app/bytebase/issue/BYT-9913/plan-detail-clicking-a-spec-tab-in-changes-collapses-the-section)++## Summary++Plan Detail should use one persistent route shell for a plan and nested routes+for resources owned by that plan. Resource identity belongs in the path; UI+phase disclosure stays local. Existing `?phase=changes|review|deploy` bookmarks+remain readable for compatibility, but the application does not create new+phase queries.++The design preserves Bytebase resource-name structure:++```text+projects/{project}/plans/{plan}+projects/{project}/plans/{plan}/specs+projects/{project}/plans/{plan}/specs/{spec}+projects/{project}/plans/{plan}/rollout+projects/{project}/plans/{plan}/rollout/stages/{stage}+projects/{project}/plans/{plan}/rollout/stages/{stage}/tasks/{task}+projects/{project}/issues/{issue}+```++Navigating among a plan, its specs, rollout, stages, and tasks must not remount+the Plan Detail shell, clear its snapshot, restart its initial fetch, or reset+the user's phase disclosure state.++## Problem++The current router registers the plan root, specs collection, and spec detail as+sibling routes that each render `ProjectPlanDetailPage`. Moving from+`/plans/{plan}` to `/plans/{plan}/specs/{spec}` therefore replaces the route+component and recreates `PlanDetailStoreProvider`.++For a plan with a rollout, the new page fetches the same plan again and derives+Deploy as its default phase. This resets `activePhases` and collapses Changes,+which is the behavior reported in BYT-9913. The delayed collapse can look like a+polling update, but the underlying problem is route ownership and remounting.++The current URL model is also inconsistent:++- A spec is selected through a resource-shaped path.+- A stage or task is selected through `stageId` and `taskId` query parameters.+- Legacy rollout resource paths redirect back to the plan root.+- A plan-backed issue always redirects to Review, even after the plan lifecycle+ has advanced to Deploy.++This mixes resource identity with view state and makes selection, disclosure,+history, and polling unnecessarily coupled.++## Goals++1. Keep URLs aligned with Bytebase resource-name ownership.+2. Keep one Plan Detail shell alive for every navigation within the same plan.+3. Make spec, rollout, stage, task, and plan-backed issue entry points reliably+ deep-linkable.+4. Preserve user disclosure and per-resource UI state while the URL selection+ changes.+5. Prevent route-driven empty, stale, or flashing content during rapid+ navigation.+6. Preserve existing bookmarks through canonical redirects.++## Non-goals++- Changing backend, proto, or API resource names.+- Adding a new Plan, Spec, Rollout, Stage, Task, or Issue data model.+- Encoding every expanded phase, task card, filter, or drawer in the URL.+- Redesigning the Plan Detail visual layout.+- Changing which issue types belong on Plan Detail versus Issue Detail.++## Canonical route model++```text+/projects/{project}/plans/{plan}+├── specs+│ └── {spec}+└── rollout+ └── stages/{stage}+ └── tasks/{task}++/projects/{project}/issues/{issue}+```++| User intent | Canonical URL | Implied phase |+| --- | --- | --- |+| Open a plan using its lifecycle default | `/projects/p/plans/123` | Derived once on entry |+| Open the specs collection | `/projects/p/plans/123/specs` | Changes |+| Open a specific spec | `/projects/p/plans/123/specs/spec-2` | Changes |+| Open the rollout | `/projects/p/plans/123/rollout` | Deploy |+| Open a specific stage | `/projects/p/plans/123/rollout/stages/prod` | Deploy |+| Open a specific task | `/projects/p/plans/123/rollout/stages/prod/tasks/42` | Deploy |+| Open a specific issue | `/projects/p/issues/456` | Determined by issue workflow |+| Open an old phase bookmark | `/projects/p/plans/123?phase=review` | Legacy compatibility only |++`changes`, `review`, and `deploy` are UI phases, not resources. They must not be+introduced as path segments such as `/plans/{plan}/changes` or written as new+query state. Conversely, `specs`, `rollout`, `stages`, and `tasks` identify+plan-owned resources and must not be represented only by query parameters.++### Phase precedence++The matched resource path is authoritative:++1. A task, stage, or rollout path selects Deploy.+2. A specs collection or spec path selects Changes.+3. On the plan root, a valid legacy `phase` query selects that phase.+4. On the plan root without `phase`, the initial lifecycle state selects the+ default: a present, committed, or expected rollout -> Deploy; issue -> Review;+ otherwise Changes.++A resource path and a contradictory `phase` query must not coexist. For example:++```text+/plans/123/specs/spec-2?phase=deploy+```++The resource path wins and the router removes the redundant query with+`replace`, producing `/plans/123/specs/spec-2`.++The lifecycle default is derived only when entering a plan without an explicit+selection. Later polling updates do not change resource selection or refocus the+page. When a rollout materializes for a plan that is already open, Deploy is+revealed once without collapsing other phases, writing the URL, or scrolling.++## Route ownership++`plans/{plan}` is the route boundary that owns the Plan Detail page. Its nested+routes describe selection only.++Conceptually:++```tsx+{+ path: "plans/:planId",+ element: <PlanDetailRouteShell />,+ children: [+ { index: true },+ { path: "specs" },+ { path: "specs/:specId" },+ {+ path: "rollout",+ children: [+ { index: true },+ { path: "stages/:stageId" },+ { path: "stages/:stageId/tasks/:taskId" },+ ],+ },+ ],+}+```++The exact route configuration is an implementation detail, but the ownership+contract is not:++- `PlanDetailRouteShell` owns `PlanDetailStoreProvider`, the plan snapshot,+ polling, editing scopes, leave guards, phase disclosure, and the page layout.+- The shell identity is `{projectId}/{planId}`.+- Child matches only update `{phase, specId, stageId, taskId}`.+- Only a project or plan identity change may recreate the shell or run the+ initial plan fetch.+- Child routes must not introduce loaders or lazy page components that delay the+ selection commit or replace the shell.++Because Plan Detail renders all phases in one page, nested leaf routes do not+own separate page bodies. They provide route selection to the persistent shell.++## Issue entry++Issue is a project-level resource:++```text+projects/{project}/issues/{issue}+```++It must not be duplicated under a plan as+`/plans/{plan}/issues/{issue}`. The current Plan model has at most one linked+issue, so carrying both IDs after resolution would create invalid combinations+such as a plan paired with an unrelated issue.++When `/projects/{project}/issues/{issue}` is opened:++- A plan-backed draft review issue redirects with `replace` to+ `/projects/{project}/plans/{plan}`. Its snapshot naturally defaults to Review.+- A submitted schema/data change issue that belongs on Plan Detail redirects to+ `/projects/{project}/plans/{plan}`. The plan snapshot selects its current+ lifecycle phase.+- A valid phase already present on an old issue URL is preserved through the+ redirect. New issue links do not add one.+- Create-database, export, grant, and other workflows owned by Issue Detail stay+ on the issue route.+- A route-neutral activity anchor, such as a review comment ID, may be preserved+ through the redirect as a query or fragment. Spec, stage, and task selectors+ from the issue URL are not preserved.++This keeps the issue URL valid as an entry point while making the plan the+canonical identity of the Plan Detail surface. Generic list and shared issue+links follow lifecycle progress, while existing phase bookmarks and resource+links keep their narrower focus.++## Selection and disclosure contract++The URL identifies the user's primary focus. It does not serialize the entire+expanded/collapsed state of the page.++- Arriving at a spec route ensures Changes is expanded and selects that spec.+- Arriving at rollout, stage, or task ensures Deploy and the selected resource+ are visible.+- Arriving with a legacy `?phase=review` ensures Review is expanded.+- Selecting a resource may expand its owning phase but must not collapse other+ phases the user opened.+- Manually selecting, showing, or hiding a phase only changes local disclosure;+ it does not write the URL.+- Refreshing or externally opening a focused URL expands its implied phase+ again.++Within one plan, disclosure state and per-resource UI state remain owned by the+persistent store. Navigating to another plan starts with a new disclosure state.++Disclosure synchronization is keyed by semantic resource identity, not only by+the implied phase: `plan + phase`, `spec + specId`, `rollout`, `stage + stageId`,+or `task + taskId`. Legacy query selectors and their canonical resource paths+produce the same key, while secondary state such as line, task run, or fragment+does not affect it.++### History writes++- Explicit user selection of a spec, stage, or task uses `push`.+- User phase selection is local and creates no history or query state.+- Alias redirects, legacy URL migration, contradictory-query cleanup, and+ invalid-selection fallback use `replace`.+- Automatic default selection, automatic frontier-stage selection, and polling+ do not write the URL.+- Back and Forward restore the resource selection and ensure its phase is+ expanded without resetting the rest of the same-plan store.+- Same-plan resource writes prevent the router's default scroll reset so the+ persistent shell keeps its live position. Plan Detail does not save or replay+ scroll positions; history-based scroll restoration remains opt-in for list+ pages such as Issues and Plans.++### Editing guards++- A spec change that would discard an unsaved statement remains guarded. The+ tab and statement stay on the current spec if navigation is canceled.+- After navigation is accepted, the URL selection, tab highlight, and statement+ body update in one render commit.+- Stage navigation does not discard stage-local state because stage contents+ remain mounted; it must not show an unnecessary leave confirmation.++## Rendering and flicker contract++Changing the URL does not inherently cause flicker. Flicker occurs when a route+change remounts ownership, clears data, temporarily renders the wrong entity, or+lets asynchronous work settle out of order.++Plan Detail navigation must satisfy the following:++- Initial disclosure is committed before the first ready render. Same-plan+ resource arrivals expand their destination in a layout effect before paint;+ disclosure synchronization never writes the URL.+- Route-driven spec selection resets during render, not in a post-paint effect,+ so the previous spec cannot appear for an intermediate frame.+- The page header, phase rail, snapshot, and polling loop stay mounted for every+ same-plan child navigation.+- The page never returns to its initializing/invisible state for a spec, stage,+ or task selection.+- Spec tab highlight and spec body change together.+- A cached sheet statement is available synchronously on the first render of the+ selected spec. An uncached statement shows a stable loading state, never an+ empty "No data" flash or the previous spec's SQL.+- The spec body may be keyed by stable spec ID to reset spec-local state, but+ the surrounding Changes phase remains mounted and dimensionally stable.+- Stage contents remain mounted and are shown/hidden by selection so task-card+ expansion, filters, Monaco instances, and fetched logs survive stage switches.+- Rapid A -> B -> A navigation cannot allow an earlier route transition or+ asynchronous fetch to overwrite the latest selection.+- Polling preserves unchanged object identities and never changes selection.+ A newly materialized rollout may expand Deploy once, while subsequent polls+ preserve the user's disclosure choices.++## Edge cases++### Plan root++- A plan root with no explicit phase derives its default once on entry.+- If approval and plan-check gates have passed but rollout creation is still+ pending, the initial lifecycle default is Deploy. This state is committed+ before the first ready render and does not require a follow-up navigation.+- A newly appearing issue updates lifecycle data without changing the user's+ current focus. A newly materialized rollout reveals Deploy once without+ changing focus, URL, scroll, or other phase disclosure.+- A deleted but readable plan keeps its canonical URL and renders its deleted+ state.+- Plan-level not-found and permission-denied errors are handled by the parent+ shell.++### Spec++- A legacy `?phase=changes` bookmark shows the first available spec or the+ Changes empty state.+- An unknown spec ID is evaluated only after the plan snapshot is ready. The+ page reports that the spec no longer exists and replaces the URL with the plan+ root while retaining the already-visible Changes disclosure.+- Same-target specs remain distinguishable by stable spec ID; target is not a+ substitute for route identity.+- An unsaved spec uses client-local selection and has no fake resource path.+ After persistence, the route is replaced with the real spec path.+- Plan creation remains an action route such as `/plans/create`; it must not use+ a placeholder spec ID in the URL.++### Rollout++- If `plan.hasRollout`, issue state, or another committed signal proves that a+ rollout is expected but the rollout snapshot is not visible yet, a rollout,+ stage, or task URL is retained and shows a pending state while active polling+ continues.+- If no rollout exists and none is expected, `/plans/{plan}/rollout` is replaced+ with the plan root while retaining the already-visible Deploy disclosure.++### Stage and task++- Stage and task IDs are resolved within the current plan's rollout; they are not+ treated as globally unique.+- An unknown stage falls back with `replace` to the rollout route after the+ rollout has finished loading.+- An unknown task falls back to its valid stage route. If neither is valid, it+ falls back to the rollout route.+- If a task exists under a different stage from the URL, its full task resource+ name determines the correct stage and the URL is replaced with the canonical+ path.+- Task-run history remains secondary UI state, for example `?taskRunId={run}` or+ a drawer. It becomes a path resource only if Task Run receives a dedicated+ page-level contract.++### Query and fragment state++Queries and fragments may encode view details that do not replace resource+identity, such as:++```text+/plans/123/specs/spec-2?line=42&planCheckResult=abc+/plans/123?phase=review#comment-456 (legacy)+/plans/123/rollout/stages/prod/tasks/42?taskRunId=7+```++Navigation preserves only parameters owned by the destination view. It must not+blindly carry incompatible spec, stage, task, or phase selection across resource+boundaries.++## Compatibility and canonicalization++Existing links remain valid and normalize without committing the legacy URL.+Direct entries use `replace`; in-app navigation keeps the referring history+entry and commits only the canonical destination:++```text+/plans/{plan}/specs+-> unchanged compatibility resource-collection URL++/plans/{plan}/specs/{spec}+-> unchanged URL, matched beneath the persistent plan shell++/plans/{plan}?stageId={stage}+-> /plans/{plan}/rollout/stages/{stage}++/plans/{plan}?stageId={stage}&taskId={task}+-> /plans/{plan}/rollout/stages/{stage}/tasks/{task}++/plans/{plan}/rollout+-> unchanged URL, rendered by the persistent plan shell++/plans/{plan}/rollout/stages/{stage}+-> unchanged URL, rendered by the persistent plan shell++/plans/{plan}/rollout/stages/{stage}/tasks/{task}+-> unchanged URL, rendered by the persistent plan shell+```++Existing route-name constants for plan, spec, rollout, stage, and task should+remain stable where their resource meaning is unchanged. Compatibility concerns+must not preserve the current sibling-page ownership or query-only stage/task+selection.++## Rejected alternatives++### Phase paths++```text+/plans/{plan}/changes/{spec}+/plans/{plan}/review+/plans/{plan}/deploy/stages/{stage}+```++Rejected because Changes, Review, and Deploy are UI phases rather than Bytebase+resources, and the paths obscure the actual Spec and Rollout resource names.++### Query-only resource selection++```text+/plans/{plan}?specId={spec}&stageId={stage}&taskId={task}+```++Rejected because it permits contradictory selections, loses parent-resource+scope, and treats real resource identity as presentation state.++### Duplicate issue identity under a plan++```text+/plans/{plan}/issues/{issue}+```++Rejected because Issue is owned by Project, not Plan, and the current model does+not require two identities to select Review.++### Full sibling page routes++Rejected because rendering the complete Plan Detail page independently at the+plan, spec, and rollout routes recreates page ownership during an internal+selection and is the direct cause of BYT-9913.++## Acceptance criteria++1. Opening a plan root with an existing rollout, expanding Changes, and selecting+ a non-selected spec updates the URL to the spec resource while Changes remains+ expanded and the selected SQL is visible.+2. Spec, stage, and task navigation within a plan preserves the Plan Detail shell+ and does not repeat the initial plan fetch.+3. A generic plan-backed issue entry opens the current lifecycle phase; an+ existing `?phase=review` bookmark continues to open Review.+4. Rollout, stage, and task resource URLs are directly shareable and survive+ refresh.+5. Rapid resource switching and Back/Forward never show stale selection,+ collapse unrelated phases, or snap back to an older route.+6. Spec switching never flashes empty or previous-spec SQL; stage switching+ preserves task-card and editor state.+7. Invalid child resources degrade to the nearest valid route without turning a+ valid plan into a page-level 404.+8. Existing spec and rollout bookmarks remain valid, and query-based stage/task+ links canonicalize without adding extra browser history entries.+9. No runtime interaction, redirect, or invalid-resource fallback creates a new+ `phase` query.diff --git a/frontend/src/app/router/NavigationScrollRestoration.test.tsx b/frontend/src/app/router/NavigationScrollRestoration.test.tsxindex 76ba7f402c..92a9e59bf0 100644--- a/frontend/src/app/router/NavigationScrollRestoration.test.tsx+++ b/frontend/src/app/router/NavigationScrollRestoration.test.tsx@@ -6,9 +6,9 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";import { setAppRouter } from "./navigation";import {MAIN_SCROLL_RESTORATION_ID,- markScrollRestorationEntry,+ markListScrollRestorationEntry,NavigationScrollRestoration,- useScrollRestorationLoadMore,+ useListScrollRestorationLoadMore,} from "./NavigationScrollRestoration";(@@ -204,13 +204,76 @@ describe("NavigationScrollRestoration", () => {unmount();});+ test("restores the list on Back but never restores the detail on Forward", async () => {+ const { main, router, unmount } = await renderRouter();++ recordScroll(main, 240);+ markListScrollRestorationEntry(router.state.location);+ await act(async () => {+ await router.navigate("/second");+ });++ recordScroll(main, 500);+ await act(async () => {+ await router.navigate(-1);+ });+ expect(main.scrollTop).toBe(240);++ await act(async () => {+ await router.navigate(1);+ });+ expect(main.scrollTop).toBe(0);++ unmount();+ });++ test("persists positions only for marked list entries", async () => {+ const { main, router, unmount } = await renderRouter();++ recordScroll(main, 240);+ window.dispatchEvent(new Event("pagehide"));+ expect(+ JSON.parse(+ sessionStorage.getItem("bb.navigation-scroll-restoration") ?? "{}"+ )+ ).toEqual({});++ markListScrollRestorationEntry(router.state.location);+ window.dispatchEvent(new Event("pagehide"));+ expect(+ JSON.parse(+ sessionStorage.getItem("bb.navigation-scroll-restoration") ?? "{}"+ )+ ).toMatchObject({+ "first-entry": {+ "custom:main": { y: 240 },+ },+ });++ unmount();+ });++ test("marks the current list entry when location is omitted", async () => {+ const { main, router, unmount } = await renderRouter();++ recordScroll(main, 240);+ markListScrollRestorationEntry();+ await act(async () => {+ await router.navigate("/second");+ await router.navigate(-1);+ });++ expect(main.scrollTop).toBe(240);+ unmount();+ });+test("restores every scroll target after an item click", async () => {const { main, panel, router, unmount } = await renderRouter();recordScroll(main, 240, 30);recordScroll(panel, 120, 10);- markScrollRestorationEntry(router.state.location);+ markListScrollRestorationEntry(router.state.location);await act(async () => {await router.navigate("/second");});@@ -232,7 +295,7 @@ describe("NavigationScrollRestoration", () => {const { main, router, unmount } = await renderRouter();main.scrollTop = 240;- markScrollRestorationEntry(router.state.location);+ markListScrollRestorationEntry(router.state.location);await act(async () => {await router.navigate("/second");});@@ -251,7 +314,7 @@ describe("NavigationScrollRestoration", () => {);main.scrollTop = 640;- markScrollRestorationEntry(router.state.location);+ markListScrollRestorationEntry(router.state.location);await act(async () => {await router.navigate("/second");});@@ -270,7 +333,7 @@ describe("NavigationScrollRestoration", () => {recordScroll(main, 240);for (let i = 0; i < 3; i++) {- markScrollRestorationEntry(router.state.location);+ markListScrollRestorationEntry(router.state.location);await act(async () => {await router.navigate("/second");});@@ -295,7 +358,7 @@ describe("NavigationScrollRestoration", () => {});expect(main.scrollTop).toBe(240);- markScrollRestorationEntry(router.state.location);+ markListScrollRestorationEntry(router.state.location);await act(async () => {await router.navigate("/second");});@@ -311,7 +374,7 @@ describe("NavigationScrollRestoration", () => {test("asks paged content to grow until the saved position is reachable", async () => {const onLoadMore = vi.fn();const PagedPage = () => {- useScrollRestorationLoadMore({+ useListScrollRestorationLoadMore({hasMore: true,isFetchingMore: false,isLoading: false,@@ -323,7 +386,7 @@ describe("NavigationScrollRestoration", () => {const { main, router, unmount } = await renderRouter(<PagedPage />);recordScroll(main, 700);- markScrollRestorationEntry(router.state.location);+ markListScrollRestorationEntry(router.state.location);await act(async () => {await router.navigate("/second");});@@ -346,7 +409,7 @@ describe("NavigationScrollRestoration", () => {const PagedPage = () => {const [dataList, setDataList] = useState<unknown[]>([]);appendItem = () => setDataList((list) => [...list, {}]);- useScrollRestorationLoadMore({+ useListScrollRestorationLoadMore({hasMore: true,isFetchingMore: false,isLoading: false,@@ -358,7 +421,7 @@ describe("NavigationScrollRestoration", () => {const { main, router, unmount } = await renderRouter(<PagedPage />);recordScroll(main, 700);- markScrollRestorationEntry(router.state.location);+ markListScrollRestorationEntry(router.state.location);await act(async () => {await router.navigate("/second");});@@ -391,7 +454,7 @@ describe("NavigationScrollRestoration", () => {setDataList((list) => [...list, {}]);setIsFetchingMore(false);};- useScrollRestorationLoadMore({+ useListScrollRestorationLoadMore({hasMore: true,isFetchingMore,isLoading: false,@@ -406,7 +469,7 @@ describe("NavigationScrollRestoration", () => {const { main, router, unmount } = await renderRouter(<PagedPage />);recordScroll(main, 700);- markScrollRestorationEntry(router.state.location);+ markListScrollRestorationEntry(router.state.location);await act(async () => {await router.navigate("/second");});@@ -437,7 +500,7 @@ describe("NavigationScrollRestoration", () => {);recordScroll(main, 380);- markScrollRestorationEntry(router.state.location);+ markListScrollRestorationEntry(router.state.location);await act(async () => {await router.navigate("/second");});@@ -464,7 +527,7 @@ describe("NavigationScrollRestoration", () => {);recordScroll(main, 600);- markScrollRestorationEntry(router.state.location);+ markListScrollRestorationEntry(router.state.location);await act(async () => {await router.navigate("/second");});@@ -483,7 +546,7 @@ describe("NavigationScrollRestoration", () => {const onLoadMore = vi.fn();let showAnchor = true;const PagedAnchorPage = () => {- useScrollRestorationLoadMore({+ useListScrollRestorationLoadMore({hasMore: true,isFetchingMore: false,isLoading: false,@@ -503,7 +566,7 @@ describe("NavigationScrollRestoration", () => {);recordScroll(main, 300);- markScrollRestorationEntry(router.state.location);+ markListScrollRestorationEntry(router.state.location);await act(async () => {await router.navigate("/second");});@@ -543,7 +606,7 @@ describe("NavigationScrollRestoration", () => {});recordScroll(main, 300);- markScrollRestorationEntry(router.state.location);+ markListScrollRestorationEntry(router.state.location);await act(async () => {await router.navigate("/second");});@@ -582,7 +645,7 @@ describe("NavigationScrollRestoration", () => {setHasMore(false);setIsFetchingMore(false);};- useScrollRestorationLoadMore({+ useListScrollRestorationLoadMore({hasMore,isFetchingMore,isLoading: false,@@ -615,7 +678,7 @@ describe("NavigationScrollRestoration", () => {});recordScroll(main, 300);- markScrollRestorationEntry(router.state.location);+ markListScrollRestorationEntry(router.state.location);await act(async () => {await router.navigate("/second");});@@ -647,7 +710,7 @@ describe("NavigationScrollRestoration", () => {let anchorTop = 320;let scrollHeight = 1000;const PagedAnchorPage = () => {- useScrollRestorationLoadMore({+ useListScrollRestorationLoadMore({hasMore: false,isFetchingMore: false,isLoading: false,@@ -677,7 +740,7 @@ describe("NavigationScrollRestoration", () => {});recordScroll(main, 300);- markScrollRestorationEntry(router.state.location);+ markListScrollRestorationEntry(router.state.location);await act(async () => {await router.navigate("/second");});@@ -692,7 +755,7 @@ describe("NavigationScrollRestoration", () => {expect(vi.getTimerCount()).toBe(0);recordScroll(main, 200);- markScrollRestorationEntry(router.state.location);+ markListScrollRestorationEntry(router.state.location);await act(async () => {await router.navigate("/second");await router.navigate(-1);diff --git a/frontend/src/app/router/NavigationScrollRestoration.tsx b/frontend/src/app/router/NavigationScrollRestoration.tsxindex 3e3fe2af9a..83c8800813 100644--- a/frontend/src/app/router/NavigationScrollRestoration.tsx+++ b/frontend/src/app/router/NavigationScrollRestoration.tsx@@ -33,7 +33,7 @@ const SCROLL_KEYS = new Set(["PageUp"," ",]);-const restorableLocationKeys = new Set<string>();+const listScrollRestorationKeys = new Set<string>();type ScrollAnchor = {key: string;@@ -48,6 +48,11 @@ type ScrollPosition = {type SavedPositions = Record<string, Record<string, ScrollPosition>>;type ScrollTarget = Window | HTMLElement;+type ScrollRestorationLocation = Pick<+ Location,+ "hash" | "pathname" | "search"+> &+ Partial<Pick<Location, "key">>;type ActiveRestoration = {locationKey: string;@@ -78,23 +83,27 @@ function isWindowTarget(target: ScrollTarget): target is Window {return target === window;}-function locationStorageKey(location: Location): string {- if (location.key !== "default") {+function locationStorageKey(location: ScrollRestorationLocation): string {+ if (location.key && location.key !== "default") {return location.key;}return `default:${location.pathname}${location.search}${location.hash}`;}-export function markScrollRestorationEntry(location: Location): void {- restorableLocationKeys.add(locationStorageKey(location));+export function markListScrollRestorationEntry(+ location: ScrollRestorationLocation | undefined = getAppRouterState()+ ?.location+): void {+ if (!location) return;+ listScrollRestorationKeys.add(locationStorageKey(location));}-export function useScrollRestorationKey(): string | undefined {+export function useListScrollRestorationKey(): string | undefined {const location = useLocation();const navigationType = useNavigationType();return useMemo(() => {const key = locationStorageKey(location);- return navigationType === "POP" && restorableLocationKeys.has(key)+ return navigationType === "POP" && listScrollRestorationKeys.has(key)? key: undefined;}, [location, navigationType]);@@ -133,18 +142,6 @@ function savePosition(savedPositions[locationKey][targetId] = position;}-function copyPositions(- savedPositions: SavedPositions,- fromLocationKey: string,- toLocationKey: string-): void {- const positions = savedPositions[fromLocationKey];- if (!positions || fromLocationKey === toLocationKey) return;- for (const [id, position] of Object.entries(positions)) {- savePosition(savedPositions, toLocationKey, id, { ...position });- }-}-function customTargetId(value: string): string {return `${CUSTOM_TARGET_PREFIX}${value}`;}@@ -436,7 +433,7 @@ type NavigationScrollRestorationProps = {children: ReactNode;};-export function useScrollRestorationLoadMore(+export function useListScrollRestorationLoadMore(paged: Pick<PagedDataResult<unknown>,"hasMore" | "isFetchingMore" | "isLoading" | "dataList" | "loadMore"@@ -481,21 +478,23 @@ export function useScrollRestorationLoadMore(}/**- * Restores registered scroll containers by browser history entry.+ * Restores registered scroll containers for explicitly marked list entries.* Nested containers opt in with `data-scroll-restoration-id="stable-id"`* (the main layout pane registers as `MAIN_SCROLL_RESTORATION_ID`).+ * List pages opt in to Back restoration with+ * `markListScrollRestorationEntry`.** Hand-rolled instead of react-router's `<ScrollRestoration>`, which only* handles window scroll: this app scrolls in nested containers and needs the- * `useScrollRestorationLoadMore` growth protocol for paged lists. Never mount- * the built-in alongside — both manage `history.scrollRestoration` and would- * fight over the window position.+ * `useListScrollRestorationLoadMore` growth protocol for paged lists. Never+ * mount the built-in alongside — both manage `history.scrollRestoration` and+ * would fight over the window position.*/export function NavigationScrollRestoration({children,}: NavigationScrollRestorationProps) {const location = useLocation();- const navigationType = useNavigationType();+ const listRestorationKey = useListScrollRestorationKey();// Lazy state, not `useRef(loadSavedPositions())`: a ref initializer argument// is evaluated (storage read + JSON parse) on every render.const [savedPositions] = useState(loadSavedPositions);@@ -539,12 +538,14 @@ export function NavigationScrollRestoration({(target: EventTarget | null) => {const id = targetId(target);if (!id || pendingRestores.has(id)) return;+ const key = currentLocationKeyRef.current;+ if (!listScrollRestorationKeys.has(key)) return;// Scroll events fire at frame rate: read the scrolled element directly// instead of re-querying the DOM for it, and defer persistence to// pagehide/unmount (SPA restores read the in-memory map).savePosition(savedPositions,- currentLocationKeyRef.current,+ key,id,readPosition(target === document ? window : (target as HTMLElement)));@@ -555,6 +556,7 @@ export function NavigationScrollRestoration({const recordAllTargets = useCallback((locationKey?: string) => {const key = locationKey ?? currentLocationKeyRef.current;+ if (!listScrollRestorationKeys.has(key)) return;for (const [id, target] of collectTargets()) {if (pendingRestores.has(id)) continue;const position = readPosition(target, true);@@ -618,22 +620,15 @@ export function NavigationScrollRestoration({}, [flushToStorage]);useLayoutEffect(() => {- const previousLocationKey = currentLocationKeyRef.current;cancelPendingRestores();currentLocationKeyRef.current = locationKey;- const savedForLocation = savedPositions[locationKey];+ const savedForLocation = listRestorationKey+ ? savedPositions[listRestorationKey]+ : undefined;const preventScrollReset = getAppRouterState()?.preventScrollReset === true;- if (preventScrollReset) {- copyPositions(savedPositions, previousLocationKey, locationKey);- }-- if (- navigationType === "POP" &&- savedForLocation &&- restorableLocationKeys.has(locationKey)- ) {- restorableLocationKeys.delete(locationKey);+ if (listRestorationKey && savedForLocation) {+ listScrollRestorationKeys.delete(listRestorationKey);const currentTargets = collectTargets();const targetIds = new Set([...currentTargets.keys(),@@ -641,7 +636,10 @@ export function NavigationScrollRestoration({]);const generation = restorationGenerationRef.current;let remaining = targetIds.size;- setActiveRestoration({ locationKey, positions: savedForLocation });+ setActiveRestoration({+ locationKey: listRestorationKey,+ positions: savedForLocation,+ });for (const id of targetIds) {const position = savedForLocation[id] ?? { x: 0, y: 0 };@@ -677,7 +675,7 @@ export function NavigationScrollRestoration({cancelPendingRestores,location,locationKey,- navigationType,+ listRestorationKey,pendingRestores,savedPositions,]);diff --git a/frontend/src/app/router/canonicalRedirect.test.ts b/frontend/src/app/router/canonicalRedirect.test.tsnew file mode 100644index 0000000000..6f105ad6a0--- /dev/null+++ b/frontend/src/app/router/canonicalRedirect.test.ts@@ -0,0 +1,65 @@+import { createMemoryRouter } from "react-router";+import { afterEach, describe, expect, test } from "vitest";+import { canonicalRedirect } from "./canonicalRedirect";+import { setAppRouter } from "./navigation";++const createRouter = (initialEntries: string[], initialIndex: number) => {+ const router = createMemoryRouter(+ [+ { path: "/before" },+ {+ path: "/legacy",+ loader: () => canonicalRedirect("/canonical"),+ },+ { path: "/canonical" },+ { path: "/after" },+ ],+ { initialEntries, initialIndex }+ );+ setAppRouter(router);+ return router;+};++let router: ReturnType<typeof createMemoryRouter> | undefined;++afterEach(() => {+ router?.dispose();+ router = undefined;+});++describe("canonicalRedirect", () => {+ test("replaces a legacy entry reached by POP so Back can continue", async () => {+ router = createRouter(["/before", "/legacy", "/after"], 2);++ await router.navigate(-1);++ expect(router.state.location.pathname).toBe("/canonical");+ expect(router.state.historyAction).toBe("REPLACE");++ await router.navigate(-1);++ expect(router.state.location.pathname).toBe("/before");+ });++ test("pushes an in-app redirect destination and preserves its referrer", async () => {+ router = createRouter(["/before"], 0);++ await router.navigate("/legacy");++ expect(router.state.location.pathname).toBe("/canonical");+ expect(router.state.historyAction).toBe("PUSH");++ await router.navigate(-1);++ expect(router.state.location.pathname).toBe("/before");+ });++ test("keeps an in-app REPLACE navigation as a replacement", async () => {+ router = createRouter(["/before"], 0);++ await router.navigate("/legacy", { replace: true });++ expect(router.state.location.pathname).toBe("/canonical");+ expect(router.state.historyAction).toBe("REPLACE");+ });+});diff --git a/frontend/src/app/router/canonicalRedirect.ts b/frontend/src/app/router/canonicalRedirect.tsnew file mode 100644index 0000000000..032e8226bb--- /dev/null+++ b/frontend/src/app/router/canonicalRedirect.ts@@ -0,0 +1,13 @@+import { redirect, replace } from "react-router";+import { getAppRouterState } from "./navigation";++// A direct or POP/REPLACE legacy URL must replace itself or Back loops through+// the redirect. Only a genuine in-app PUSH should preserve the referring entry;+// React Router commits the redirect destination without committing the alias.+export const canonicalRedirect = (location: string): Response => {+ const state = getAppRouterState();+ return state?.initialized === true &&+ state.navigation?.historyAction === "PUSH"+ ? redirect(location)+ : replace(location);+};diff --git a/frontend/src/app/router/handles.ts b/frontend/src/app/router/handles.tsindex 711f9e7325..19c54e36d9 100644--- a/frontend/src/app/router/handles.ts+++ b/frontend/src/app/router/handles.ts@@ -104,8 +104,7 @@ export const PROJECT_V1_ROUTE_WORKLOAD_IDENTITIES = `${PROJECT_V1_ROUTE_DASHBOARexport const PROJECT_V1_ROUTE_SETTINGS = `${PROJECT_V1_ROUTE_DASHBOARD}.settings`;export const PROJECT_V1_ROUTE_RELEASES = `${PROJECT_V1_ROUTE_DASHBOARD}.release`;export const PROJECT_V1_ROUTE_RELEASE_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.release.detail`;-export const PROJECT_V1_ROUTE_ROLLOUTS = `${PROJECT_V1_ROUTE_DASHBOARD}.rollouts`;-export const PROJECT_V1_ROUTE_PLAN_ROLLOUT = `${PROJECT_V1_ROUTE_ROLLOUTS}.rollout`;+export const PROJECT_V1_ROUTE_PLAN_ROLLOUT = `${PROJECT_V1_ROUTE_PLAN_DETAIL}.rollout`;export const PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE = `${PROJECT_V1_ROUTE_PLAN_ROLLOUT}.stage`;export const PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK = `${PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE}.task`;export const PROJECT_V1_ROUTE_GITOPS = `${PROJECT_V1_ROUTE_DASHBOARD}.gitops`;@@ -115,6 +114,28 @@ export const PLAN_DETAIL_PHASE_CHANGES = "changes";export const PLAN_DETAIL_PHASE_REVIEW = "review";export const PLAN_DETAIL_PHASE_DEPLOY = "deploy";+// A route whose path (not its query) owns the plan-detail selection. Kept in+// lockstep with the canonicalization and selection hooks that must agree on+// what a URL means.+export const isPlanDetailResourceRoute = (+ routeName: string | undefined+): boolean =>+ routeName === PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS ||+ routeName === PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL ||+ routeName === PROJECT_V1_ROUTE_PLAN_ROLLOUT ||+ routeName === PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE ||+ routeName === PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK;++export const isPlanDetailPhase = (+ value: unknown+): value is+ | typeof PLAN_DETAIL_PHASE_CHANGES+ | typeof PLAN_DETAIL_PHASE_REVIEW+ | typeof PLAN_DETAIL_PHASE_DEPLOY =>+ value === PLAN_DETAIL_PHASE_CHANGES ||+ value === PLAN_DETAIL_PHASE_REVIEW ||+ value === PLAN_DETAIL_PHASE_DEPLOY;+// Normalize a query value (string | string[] | undefined) to a single string.// Ported vue-free from projectV1RouteHelpers.getRouteQueryString.export function getRouteQueryString(diff --git a/frontend/src/app/router/issueDetailRedirect.test.ts b/frontend/src/app/router/issueDetailRedirect.test.tsindex 31df1797fd..76c000c035 100644--- a/frontend/src/app/router/issueDetailRedirect.test.ts+++ b/frontend/src/app/router/issueDetailRedirect.test.ts@@ -15,6 +15,7 @@ import type { Issue } from "@/types/proto-es/v1/issue_service_pb";import { Issue_Type } from "@/types/proto-es/v1/issue_service_pb";import type { Plan } from "@/types/proto-es/v1/plan_service_pb";import { issueDetailRedirectLoader } from "./issueDetailRedirect";+import { setAppRouter } from "./navigation";const PLAN_NAME = "projects/p1/plans/456";@@ -43,10 +44,22 @@ const run = (beforeEach(() => {mocks.getIssue.mockReset();mocks.getPlan.mockReset();+ setAppRouter({+ navigate: vi.fn(),+ state: {+ initialized: false,+ location: {+ pathname: "/projects/p1/issues/123",+ search: "",+ hash: "",+ },+ matches: [],+ },+ });});describe("issueDetailRedirectLoader", () => {- test("redirects a schema/data change issue to Plan Detail", async () => {+ test("redirects a schema/data change issue to the Plan Detail root", async () => {mocks.getIssue.mockResolvedValue(makeIssue(Issue_Type.DATABASE_CHANGE, PLAN_NAME));@@ -57,9 +70,35 @@ describe("issueDetailRedirectLoader", () => {expect(res).toBeInstanceOf(Response);expect(res?.status).toBe(302);expect(res?.headers.get("Location")).toBe("/projects/p1/plans/456");+ expect(res?.headers.get("X-Remix-Replace")).toBe("true");expect(mocks.getPlan).toHaveBeenCalledOnce();});+ test("preserves the referring entry for an in-app issue navigation", async () => {+ setAppRouter({+ navigate: vi.fn(),+ state: {+ initialized: true,+ location: {+ pathname: "/projects/p1/issues",+ search: "",+ hash: "",+ },+ matches: [],+ navigation: { historyAction: "PUSH" },+ },+ });+ mocks.getIssue.mockResolvedValue(+ makeIssue(Issue_Type.DATABASE_CHANGE, PLAN_NAME)+ );+ mocks.getPlan.mockResolvedValue(makePlan(["changeDatabaseConfig"]));++ const res = await run({ projectId: "p1", issueId: "123" });++ expect(res?.headers.get("Location")).toBe("/projects/p1/plans/456");+ expect(res?.headers.get("X-Remix-Replace")).toBeNull();+ });+test("redirects a Draft Review Issue URL to its Plan", async () => {mocks.getIssue.mockResolvedValue(makeIssue(Issue_Type.DATABASE_EXPORT, PLAN_NAME, true)@@ -72,7 +111,26 @@ describe("issueDetailRedirectLoader", () => {expect(mocks.getPlan).not.toHaveBeenCalled();});- test("preserves the query string on redirect", async () => {+ test.each(["changes", "review", "deploy"])(+ "preserves an explicit %s phase intent",+ async (phase) => {+ mocks.getIssue.mockResolvedValue(+ makeIssue(Issue_Type.DATABASE_CHANGE, PLAN_NAME)+ );+ mocks.getPlan.mockResolvedValue(makePlan(["changeDatabaseConfig"]));++ const res = await run(+ { projectId: "p1", issueId: "123" },+ `http://localhost/projects/p1/issues/123?phase=${phase}`+ );++ expect(res?.headers.get("Location")).toBe(+ `/projects/p1/plans/456?phase=${phase}`+ );+ }+ );++ test("drops an invalid phase intent", async () => {mocks.getIssue.mockResolvedValue(makeIssue(Issue_Type.DATABASE_CHANGE, PLAN_NAME));@@ -80,12 +138,24 @@ describe("issueDetailRedirectLoader", () => {const res = await run({ projectId: "p1", issueId: "123" },- "http://localhost/projects/p1/issues/123?stageId=7&foo=bar"+ "http://localhost/projects/p1/issues/123?phase=unknown");- expect(res?.headers.get("Location")).toBe(- "/projects/p1/plans/456?stageId=7&foo=bar"+ expect(res?.headers.get("Location")).toBe("/projects/p1/plans/456");+ });++ test("preserves neutral query state but drops incompatible selectors", async () => {+ mocks.getIssue.mockResolvedValue(+ makeIssue(Issue_Type.DATABASE_CHANGE, PLAN_NAME)+ );+ mocks.getPlan.mockResolvedValue(makePlan(["changeDatabaseConfig"]));++ const res = await run(+ { projectId: "p1", issueId: "123" },+ "http://localhost/projects/p1/issues/123?stageId=7&foo=bar");++ expect(res?.headers.get("Location")).toBe("/projects/p1/plans/456?foo=bar");});test("keeps a create-database issue on Issue Detail", async () => {diff --git a/frontend/src/app/router/issueDetailRedirect.ts b/frontend/src/app/router/issueDetailRedirect.tsindex 8be70cae2b..5aa4c54a05 100644--- a/frontend/src/app/router/issueDetailRedirect.ts+++ b/frontend/src/app/router/issueDetailRedirect.ts@@ -1,6 +1,8 @@import { create } from "@bufbuild/protobuf";-import { type LoaderFunctionArgs, redirect } from "react-router";+import type { LoaderFunctionArgs } from "react-router";import { issueServiceClientConnect, planServiceClientConnect } from "@/api";+import { canonicalRedirect } from "@/app/router/canonicalRedirect";+import { buildPlanDetailLegacySearch } from "@/app/router/planDetailRouteQuery";import { shouldStayOnPlanDetailPage } from "@/lib/plan/workflow";import { issueNamePrefix, projectNamePrefix } from "@/stores/modules/v1/common";import {@@ -10,6 +12,17 @@ import {import { GetPlanRequestSchema } from "@/types/proto-es/v1/plan_service_pb";import { extractPlanUID } from "@/utils/v1/issue/plan";+const planDetailRedirect = (+ projectId: string,+ planId: string,+ requestUrl: string+): Response => {+ const query = buildPlanDetailLegacySearch(requestUrl);+ return canonicalRedirect(+ `/projects/${projectId}/plans/${planId}${query ? `?${query}` : ""}`+ );+};+// Plan Detail is the canonical review surface for Draft Review Issues and// schema/data change plans. Drafts redirect directly from their linked plan;// submitted create-database, export, and grant issues stay on Issue Detail.@@ -18,9 +31,9 @@ import { extractPlanUID } from "@/utils/v1/issue/plan";// changes from create-database plans. Drafts do not need that fetch: their// lifecycle and metadata always belong on the linked Plan Detail surface.//-// Every issue-detail entry point navigates to this route by name, so this single-// guard covers deep links, inbox/notifications, and review CTAs without patching-// call sites. Old issue-detail URLs resolve via this redirect rather than 404.+// A valid legacy phase remains authoritative. A generic issue URL redirects to+// the plan root so Plan Detail can derive the current lifecycle phase from its+// snapshot without a second navigation.export async function issueDetailRedirectLoader({params,request,@@ -44,8 +57,7 @@ export async function issueDetailRedirectLoader({if (issue.draft) {const planId = extractPlanUID(issue.plan);if (!planId) return null;- const { search } = new URL(request.url);- return redirect(`/projects/${projectId}/plans/${planId}${search}`);+ return planDetailRedirect(projectId, planId, request.url);}// Submitted export and grant issues stay on Issue Detail; skip the plan// fetch for them. DATABASE_CHANGE remains ambiguous until the plan loads.@@ -65,8 +77,7 @@ export async function issueDetailRedirectLoader({if (!planId) {return null;}- const { search } = new URL(request.url);- return redirect(`/projects/${projectId}/plans/${planId}${search}`);+ return planDetailRedirect(projectId, planId, request.url);} catch {// 404/403/network → fall through to Issue Detail, which has its own// not-found / permission-denied handling. Avoids turning a transient errordiff --git a/frontend/src/app/router/lazyPage.test.tsx b/frontend/src/app/router/lazyPage.test.tsxnew file mode 100644index 0000000000..fcea92a1bb--- /dev/null+++ b/frontend/src/app/router/lazyPage.test.tsx@@ -0,0 +1,102 @@+import { render, screen, waitFor } from "@testing-library/react";+import { useRef } from "react";+import { createMemoryRouter, RouterProvider } from "react-router";+import { describe, expect, test } from "vitest";+import { lazyPage } from "./lazyPage";++describe("lazyPage persistent parent routes", () => {+ test("forwards leaf params without remounting the parent page", async () => {+ let mountCount = 0;+ const Page = (props: Record<string, unknown>) => {+ const mountId = useRef<number | undefined>(undefined);+ if (mountId.current === undefined) {+ mountCount += 1;+ mountId.current = mountCount;+ }+ return (+ <div>+ <span data-testid="mount-id">{mountId.current}</span>+ <span data-testid="route-name">{String(props.routeName)}</span>+ <span data-testid="route-hash">{String(props.routeHash)}</span>+ <span data-testid="spec-id">{String(props.specId ?? "")}</span>+ <span data-testid="stage-id">{String(props.stageId ?? "")}</span>+ <span data-testid="task-id">{String(props.taskId ?? "")}</span>+ </div>+ );+ };+ const router = createMemoryRouter(+ [+ {+ path: "/projects/:projectId/plans/:planId",+ lazy: lazyPage(+ async () => ({ Page }),+ (module) => module.Page+ ),+ children: [+ { index: true, handle: { name: "plan" } },+ { path: "specs/:specId", handle: { name: "plan.spec" } },+ {+ path: "rollout/stages/:stageId",+ handle: { name: "plan.rollout.stage" },+ },+ {+ path: "rollout/stages/:stageId/tasks/:taskId",+ handle: { name: "plan.rollout.stage.task" },+ },+ ],+ },+ ],+ { initialEntries: ["/projects/p/plans/1"] }+ );++ render(<RouterProvider router={router} />);+ await screen.findByText("plan");+ expect(screen.getByTestId("mount-id")).toHaveTextContent("1");++ await router.navigate("/projects/p/plans/1/specs/spec-2#result-7");+ await waitFor(() =>+ expect(screen.getByTestId("route-name")).toHaveTextContent("plan.spec")+ );+ expect(screen.getByTestId("spec-id")).toHaveTextContent("spec-2");+ expect(screen.getByTestId("route-hash")).toHaveTextContent("#result-7");+ expect(screen.getByTestId("mount-id")).toHaveTextContent("1");++ await router.navigate("/projects/p/plans/1/rollout/stages/prod");+ await waitFor(() =>+ expect(screen.getByTestId("route-name")).toHaveTextContent(+ "plan.rollout.stage"+ )+ );+ expect(screen.getByTestId("stage-id")).toHaveTextContent("prod");+ expect(screen.getByTestId("mount-id")).toHaveTextContent("1");++ await router.navigate(+ "/projects/p/plans/1/rollout/stages/prod/tasks/42?taskRunId=7#log"+ );+ await waitFor(() =>+ expect(screen.getByTestId("route-name")).toHaveTextContent(+ "plan.rollout.stage.task"+ )+ );+ expect(screen.getByTestId("stage-id")).toHaveTextContent("prod");+ expect(screen.getByTestId("task-id")).toHaveTextContent("42");+ expect(screen.getByTestId("route-hash")).toHaveTextContent("#log");+ expect(screen.getByTestId("mount-id")).toHaveTextContent("1");++ await router.navigate(-1);+ await waitFor(() =>+ expect(screen.getByTestId("route-name")).toHaveTextContent(+ "plan.rollout.stage"+ )+ );+ expect(screen.getByTestId("task-id")).toHaveTextContent("");+ expect(screen.getByTestId("mount-id")).toHaveTextContent("1");++ await router.navigate(1);+ await waitFor(() =>+ expect(screen.getByTestId("task-id")).toHaveTextContent("42")+ );+ expect(screen.getByTestId("mount-id")).toHaveTextContent("1");+ expect(mountCount).toBe(1);+ });+});diff --git a/frontend/src/app/router/lazyPage.ts b/frontend/src/app/router/lazyPage.tsindex 76850f33bd..29d5d16123 100644--- a/frontend/src/app/router/lazyPage.ts+++ b/frontend/src/app/router/lazyPage.ts@@ -12,7 +12,8 @@ import { useLocation, useMatches, useParams } from "react-router";// - `routeName` → the matched leaf route's `handle.name`, and `routeQuery` →// the parsed query string. Pages like the plan detail decide which phase /// stage / task / spec to show from these (mirroring the Vue `route.name` /-// `route.query`); without injection that selection silently never fires.+// `route.query`); `routeHash` preserves secondary anchors during canonical+// redirects. Without injection that selection silently never fires.// Pages that don't declare these props simply ignore the extras.export const lazyPage =<T extends Record<string, unknown>>(@@ -23,9 +24,14 @@ export const lazyPage =const m = await loader();const Page = pick(m) as ComponentType<Record<string, unknown>>;const WithRouteProps = () => {- const params = useParams();+ const ownParams = useParams();const matches = useMatches();- const { search } = useLocation();+ // A page can be owned by a persistent parent route while a nested leaf+ // contributes selection params (for example Plan Detail's spec/stage/task+ // routes). useParams() in the parent element only sees the parent's+ // match, while the leaf match contains the fully merged param bag.+ const params = matches.at(-1)?.params ?? ownParams;+ const { hash, search } = useLocation();const routeName = (matches.at(-1)?.handle as { name?: string } | undefined)?.name;@@ -36,7 +42,12 @@ export const lazyPage =() => Object.fromEntries(new URLSearchParams(search)),[search]);- return createElement(Page, { ...params, routeName, routeQuery });+ return createElement(Page, {+ ...params,+ routeHash: hash,+ routeName,+ routeQuery,+ });};return { Component: WithRouteProps };};diff --git a/frontend/src/app/router/navigation.ts b/frontend/src/app/router/navigation.tsindex 9c43adb4e8..1cc244bd03 100644--- a/frontend/src/app/router/navigation.ts+++ b/frontend/src/app/router/navigation.ts@@ -9,6 +9,9 @@ export type RouterState = {location: RouterLocation;matches: RouterMatch[];initialized: boolean;+ navigation?: {+ historyAction?: "POP" | "PUSH" | "REPLACE";+ };preventScrollReset?: boolean;};export type NavigationOptions = {diff --git a/frontend/src/app/router/planDetailRouteQuery.test.ts b/frontend/src/app/router/planDetailRouteQuery.test.tsnew file mode 100644index 0000000000..ea1aa9e744--- /dev/null+++ b/frontend/src/app/router/planDetailRouteQuery.test.ts@@ -0,0 +1,32 @@+import { describe, expect, test } from "vitest";+import {+ buildPlanDetailLegacySearch,+ stripPlanDetailSelectionQuery,+} from "./planDetailRouteQuery";++describe("plan detail route query", () => {+ test("preserves a valid legacy phase without accepting a new phase", () => {+ expect(+ buildPlanDetailLegacySearch(+ "http://localhost/issues/1?phase=review&stageId=s1&foo=a&foo=b"+ )+ ).toBe("phase=review&foo=a&foo=b");+ expect(+ buildPlanDetailLegacySearch(+ "http://localhost/issues/1?phase=unknown&foo=a"+ )+ ).toBe("foo=a");+ });++ test("strips selection keys from object queries", () => {+ expect(+ stripPlanDetailSelectionQuery({+ phase: "deploy",+ specId: "spec-1",+ stageId: "s1",+ taskId: "t1",+ line: "42",+ })+ ).toEqual({ line: "42" });+ });+});diff --git a/frontend/src/app/router/planDetailRouteQuery.ts b/frontend/src/app/router/planDetailRouteQuery.tsnew file mode 100644index 0000000000..852ba9af74--- /dev/null+++ b/frontend/src/app/router/planDetailRouteQuery.ts@@ -0,0 +1,35 @@+import { isPlanDetailPhase } from "./handles";++export const PLAN_DETAIL_SELECTION_QUERY_KEYS: ReadonlySet<string> = new Set([+ "phase",+ "specId",+ "stageId",+ "taskId",+]);++export const stripPlanDetailSelectionQuery = (+ query: Record<string, unknown>+): Record<string, unknown> =>+ Object.fromEntries(+ Object.entries(query).filter(+ ([key]) => !PLAN_DETAIL_SELECTION_QUERY_KEYS.has(key)+ )+ );++// `phase` is a read-only compatibility input. Preserve a valid value already+// present on an old URL, but expose no phase argument that could create a new+// phase query.+export const buildPlanDetailLegacySearch = (requestUrl: string): string => {+ const source = new URL(requestUrl);+ const query = new URLSearchParams();+ const phase = source.searchParams.get("phase");+ if (isPlanDetailPhase(phase)) {+ query.set("phase", phase);+ }+ for (const [key, value] of source.searchParams) {+ if (!PLAN_DETAIL_SELECTION_QUERY_KEYS.has(key)) {+ query.append(key, value);+ }+ }+ return query.toString();+};diff --git a/frontend/src/app/router/routeHelpers.test.ts b/frontend/src/app/router/routeHelpers.test.tsnew file mode 100644index 0000000000..af48246832--- /dev/null+++ b/frontend/src/app/router/routeHelpers.test.ts@@ -0,0 +1,90 @@+import { describe, expect, test } from "vitest";+import {+ PROJECT_V1_ROUTE_PLAN_DETAIL,+ PROJECT_V1_ROUTE_PLAN_ROLLOUT,+ PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE,+ PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+} from "./handles";+import { resolvePath, setRouteNameIndex } from "./navigation";+import {+ buildPlanCreateRoute,+ buildPlanDeployRouteFromRolloutName,+ buildPlanRolloutRouteFromPlanName,+ buildStageRoute,+ buildTaskDetailRoute,+} from "./routeHelpers";+import { buildRouteNameIndex } from "./routes";++describe("plan detail resource route helpers", () => {+ test("builds plan creation on the plan root without a placeholder spec", () => {+ const query = {+ databaseList: "projects/p/databases/db",+ };++ expect(buildPlanCreateRoute("p", query)).toEqual({+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,+ params: { projectId: "p", planId: "create" },+ query,+ });+ });++ test("maps rollout, stage, and task resource names to resource paths", () => {+ const rollout = "projects/p/plans/1/rollout";+ const stage = `${rollout}/stages/prod`;+ const task = `${stage}/tasks/42`;++ expect(buildPlanDeployRouteFromRolloutName(rollout)).toEqual({+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT,+ params: { projectId: "p", planId: "1" },+ });+ expect(buildPlanRolloutRouteFromPlanName("projects/p/plans/1")).toEqual({+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT,+ params: { projectId: "p", planId: "1" },+ });+ expect(buildStageRoute(stage)).toEqual({+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE,+ params: { projectId: "p", planId: "1", stageId: "prod" },+ });+ expect(buildTaskDetailRoute(task)).toEqual({+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ params: {+ projectId: "p",+ planId: "1",+ stageId: "prod",+ taskId: "42",+ },+ });+ });++ test("resolves the canonical resource URL hierarchy", () => {+ setRouteNameIndex(buildRouteNameIndex());+ const params = {+ projectId: "p",+ planId: "1",+ stageId: "prod",+ taskId: "42",+ };++ expect(resolvePath(PROJECT_V1_ROUTE_PLAN_ROLLOUT, { params })).toBe(+ "/projects/p/plans/1/rollout"+ );+ expect(resolvePath(PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE, { params })).toBe(+ "/projects/p/plans/1/rollout/stages/prod"+ );+ expect(resolvePath(PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK, { params })).toBe(+ "/projects/p/plans/1/rollout/stages/prod/tasks/42"+ );+ });++ test("keeps rollout resources in the plan route-name family", () => {+ expect(PROJECT_V1_ROUTE_PLAN_ROLLOUT).toBe(+ `${PROJECT_V1_ROUTE_PLAN_DETAIL}.rollout`+ );+ expect(PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE).toBe(+ `${PROJECT_V1_ROUTE_PLAN_DETAIL}.rollout.stage`+ );+ expect(PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK).toBe(+ `${PROJECT_V1_ROUTE_PLAN_DETAIL}.rollout.stage.task`+ );+ });+});diff --git a/frontend/src/app/router/routeHelpers.ts b/frontend/src/app/router/routeHelpers.tsindex db8a90638f..0ccfdba9b6 100644--- a/frontend/src/app/router/routeHelpers.ts+++ b/frontend/src/app/router/routeHelpers.ts@@ -1,8 +1,10 @@import type { RouteTarget } from "@/app/router";import {- PLAN_DETAIL_PHASE_DEPLOY,PROJECT_V1_ROUTE_PLAN_DETAIL,PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,+ PROJECT_V1_ROUTE_PLAN_ROLLOUT,+ PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE,+ PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,} from "@/app/router/handles";import { extractPlanUID } from "@/utils/v1/issue/plan";import {@@ -16,26 +18,46 @@ import { extractProjectResourceName } from "@/utils/v1/project";// Route-target builders return the structural `RouteTarget` consumed by the// application router's push, replace, and resolve methods.-type BuildPlanDeployRouteParams = {+type BuildPlanDeployRouteSelection = { stageId: string; taskId?: string };++type BuildPlanDeployRouteParams = BuildPlanDeployRouteSelection & {projectId: string;planId: string;- stageId?: string;- taskId?: string;};+export const buildPlanCreateRoute = (+ projectId: string,+ query: Record<string, string>+): RouteTarget => ({+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,+ params: { projectId, planId: "create" },+ query,+});+export const buildPlanDeployRoute = ({projectId,planId,stageId,taskId,-}: BuildPlanDeployRouteParams): RouteTarget => ({- name: PROJECT_V1_ROUTE_PLAN_DETAIL,+}: BuildPlanDeployRouteParams): RouteTarget => {+ if (taskId) {+ return {+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ params: { projectId, planId, stageId, taskId },+ };+ }+ return {+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE,+ params: { projectId, planId, stageId },+ };+};++export const buildPlanRolloutRoute = (+ projectId: string,+ planId: string+): RouteTarget => ({+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT,params: { projectId, planId },- query: {- phase: PLAN_DETAIL_PHASE_DEPLOY,- ...(stageId ? { stageId } : {}),- ...(taskId ? { taskId } : {}),- },});export const buildSpecDetailRouteForCurrentPage = (@@ -55,28 +77,27 @@ export const buildSpecDetailRouteForCurrentPage = () as Record<string, string>),specId,},- query: (currentRoute.query || {}) as Record<string, string | undefined>,});-export const buildPlanDeployRouteFromPlanName = (- planName: string,- options?: Omit<BuildPlanDeployRouteParams, "projectId" | "planId">+export const buildPlanRolloutRouteFromPlanName = (+ planName: string): RouteTarget =>- buildPlanDeployRoute({- projectId: extractProjectResourceName(planName),- planId: extractPlanUID(planName) || "_",- ...options,- });+ buildPlanRolloutRoute(+ extractProjectResourceName(planName),+ extractPlanUID(planName) || "_"+ );export const buildPlanDeployRouteFromRolloutName = (rolloutName: string,- options?: Omit<BuildPlanDeployRouteParams, "projectId" | "planId">-): RouteTarget =>- buildPlanDeployRoute({- projectId: extractProjectResourceName(rolloutName),- planId: extractPlanUIDFromRolloutName(rolloutName) || "_",- ...options,- });+ options?: BuildPlanDeployRouteSelection+): RouteTarget => {+ const projectId = extractProjectResourceName(rolloutName);+ const planId = extractPlanUIDFromRolloutName(rolloutName) || "_";+ if (!options?.stageId) {+ return buildPlanRolloutRoute(projectId, planId);+ }+ return buildPlanDeployRoute({ projectId, planId, ...options });+};export const buildTaskDetailRoute = (taskName: string): RouteTarget => {const stageName = extractStageNameFromTaskName(taskName);diff --git a/frontend/src/app/router/routes.test.tsx b/frontend/src/app/router/routes.test.tsxindex 474c9f8525..4b76cab033 100644--- a/frontend/src/app/router/routes.test.tsx+++ b/frontend/src/app/router/routes.test.tsx@@ -1,6 +1,9 @@import { matchRoutes, type RouteObject } from "react-router";import { describe, expect, it } from "vitest";-import { WORKSPACE_ROUTE_404 } from "@/app/router/handles";+import {+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,+ WORKSPACE_ROUTE_404,+} from "@/app/router/handles";import { routes } from "./routes";// Guardrail for the "blank body" route bug class. During the Vue→React router@@ -104,4 +107,14 @@ describe("react route table reachability", () => {expect(leafHandle?.name).toBe(WORKSPACE_ROUTE_404);expect(leafRoute?.loader).toBeTypeOf("function");});++ it("keeps the specs collection as a selection-only plan-detail route", () => {+ const path = "/projects/p/plans/1/specs";+ const matched = matchRoutes(routes, path);+ const leaf = matched?.at(-1);+ expect((leaf?.route.handle as { name?: string })?.name).toBe(+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS+ );+ expect(leaf?.route.loader).toBeUndefined();+ });});diff --git a/frontend/src/app/router/routes/dashboard.tsx b/frontend/src/app/router/routes/dashboard.tsxindex a90a913a53..5d3fcc8396 100644--- a/frontend/src/app/router/routes/dashboard.tsx+++ b/frontend/src/app/router/routes/dashboard.tsx@@ -882,41 +882,13 @@ const projectV1Routes: RouteObject[] = [(m) => m.ProjectGitOpsPage),},- // Plan detail — three routes share ProjectPlanDetailPage.+ // Plan Detail owns one persistent shell per plan. Nested resource routes+ // only update the leaf selection passed to that shell; they must not+ // mount another page/provider or restart the plan snapshot and polling.{path: "plans/:planId",handle: {- name: PROJECT_V1_ROUTE_PLAN_DETAIL,- requiredPermissionList: (): Permission[] => [- "bb.plans.get",- "bb.planCheckRuns.get",- "bb.taskRuns.list",- ],- },- lazy: lazyPage(- () => import("@/routes/project/plan-detail/ProjectPlanDetailPage"),- (m) => m.ProjectPlanDetailPage- ),- },- {- path: "plans/:planId/specs",- handle: {- name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,- requiredPermissionList: (): Permission[] => [- "bb.plans.get",- "bb.planCheckRuns.get",- "bb.taskRuns.list",- ],- },- lazy: lazyPage(- () => import("@/routes/project/plan-detail/ProjectPlanDetailPage"),- (m) => m.ProjectPlanDetailPage- ),- },- {- path: "plans/:planId/specs/:specId",- handle: {- name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,+ layoutAsPage: true,requiredPermissionList: (): Permission[] => ["bb.plans.get","bb.planCheckRuns.get",@@ -927,6 +899,32 @@ const projectV1Routes: RouteObject[] = [() => import("@/routes/project/plan-detail/ProjectPlanDetailPage"),(m) => m.ProjectPlanDetailPage),+ children: [+ {+ index: true,+ handle: { name: PROJECT_V1_ROUTE_PLAN_DETAIL },+ },+ {+ path: "specs",+ handle: { name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS },+ },+ {+ path: "specs/:specId",+ handle: { name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL },+ },+ {+ path: "rollout",+ handle: { name: PROJECT_V1_ROUTE_PLAN_ROLLOUT },+ },+ {+ path: "rollout/stages/:stageId",+ handle: { name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE },+ },+ {+ path: "rollout/stages/:stageId/tasks/:taskId",+ handle: { name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK },+ },+ ],},// Issue detail. Schema/data change issues redirect to Plan Detail — the// canonical review surface (BYT-9721); create-database, export, and grant@@ -944,34 +942,6 @@ const projectV1Routes: RouteObject[] = [(m) => m.ProjectIssueDetailPage),},- // Legacy rollout paths. The plan detail page now hosts the rollout: it- // shows the deploy phase when the plan has a rollout and selects a- // stage/task from the `?stageId=`/`?taskId=` query (see- // usePlanDetailPage). So these path-based deep links redirect to the plan- // detail page, converting the path stage/task into that query form so the- // selection is preserved. The route names are kept so bookmarks resolve.- {- path: "plans/:planId/rollout",- handle: { name: PROJECT_V1_ROUTE_PLAN_ROLLOUT },- loader: ({ params }) =>- redirect(`/projects/${params.projectId}/plans/${params.planId}`),- },- {- path: "plans/:planId/rollout/stages/:stageId",- handle: { name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE },- loader: ({ params }) =>- redirect(- `/projects/${params.projectId}/plans/${params.planId}?stageId=${params.stageId}`- ),- },- {- path: "plans/:planId/rollout/stages/:stageId/tasks/:taskId",- handle: { name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK },- loader: ({ params }) =>- redirect(- `/projects/${params.projectId}/plans/${params.planId}?stageId=${params.stageId}&taskId=${params.taskId}`- ),- },],},];diff --git a/frontend/src/components/database/DatabaseTable.test.tsx b/frontend/src/components/database/DatabaseTable.test.tsxindex 9185460dfc..91318b3b78 100644--- a/frontend/src/components/database/DatabaseTable.test.tsx+++ b/frontend/src/components/database/DatabaseTable.test.tsx@@ -11,6 +11,7 @@ import { DatabaseTable } from "./DatabaseTable";const mocks = vi.hoisted(() => ({fetchDatabases: vi.fn(),+ routerPush: vi.fn(),}));vi.mock("@/stores/app", () => {@@ -26,7 +27,7 @@ vi.mock("@/stores/app", () => {vi.mock("@/app/router", () => ({router: {resolve: () => ({ fullPath: "/database" }),- push: vi.fn(),+ push: mocks.routerPush,},}));@@ -75,6 +76,9 @@ vi.mock("./DatabaseTableView", () => ({data-has-row-click={Boolean(onRowClick)}data-select-on-row-click={Boolean(selectOnRowClick)}data-selection-column-intro-target={selectionColumnIntroTarget ?? ""}+ onClick={(event) => {+ if (databases[0]) onRowClick?.(databases[0], event);+ }}>{databases.map((database) => database.name).join(",")}{emptyPlaceholder && (@@ -120,6 +124,7 @@ describe("DatabaseTable", () => {container = undefined;document.body.innerHTML = "";mocks.fetchDatabases.mockReset();+ mocks.routerPush.mockReset();});test("keeps appended rows when the parent rerenders with an equivalent filter", async () => {@@ -244,6 +249,41 @@ describe("DatabaseTable", () => {expect(view?.getAttribute("data-select-on-row-click")).toBe("true");});+ test("marks the list entry before opening a database", async () => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ const onOpenDatabase = vi.fn();++ mocks.fetchDatabases.mockResolvedValueOnce({+ databases: [db1],+ nextPageToken: "",+ });++ await act(async () => {+ root!.render(+ <DatabaseTable+ filter={{}}+ parent="instances/i"+ onOpenDatabase={onOpenDatabase}+ />+ );+ await Promise.resolve();+ });++ act(() => {+ container!+ .querySelector<HTMLElement>("[data-testid='database-names']")+ ?.click();+ });++ expect(onOpenDatabase).toHaveBeenCalledOnce();+ expect(mocks.routerPush).toHaveBeenCalledWith("/database");+ expect(onOpenDatabase.mock.invocationCallOrder[0]).toBeLessThan(+ mocks.routerPush.mock.invocationCallOrder[0]+ );+ });+test("forwards selection column intro target to the table view", async () => {container = document.createElement("div");document.body.appendChild(container);diff --git a/frontend/src/components/database/DatabaseTable.tsx b/frontend/src/components/database/DatabaseTable.tsxindex 6282abc061..4d661281f9 100644--- a/frontend/src/components/database/DatabaseTable.tsx+++ b/frontend/src/components/database/DatabaseTable.tsx@@ -1,6 +1,6 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { router } from "@/app/router";-import { useScrollRestorationLoadMore } from "@/app/router/NavigationScrollRestoration";+import { useListScrollRestorationLoadMore } from "@/app/router/NavigationScrollRestoration";import { PagedTableFooter } from "@/hooks/usePagedData";import {getPageSizeOptions,@@ -24,6 +24,7 @@ export interface DatabaseTableProps {mode?: DatabaseTableMode;/** Row click selects instead of navigating to the database page. */selectOnRowClick?: boolean;+ onOpenDatabase?: () => void;selectedNames?: Set<string>;onSelectedNamesChange?: (names: Set<string>) => void;/**@@ -71,6 +72,7 @@ export function DatabaseTable({parent,mode = "ALL",selectOnRowClick = false,+ onOpenDatabase,selectedNames,onSelectedNamesChange,onDatabasesChange,@@ -166,7 +168,7 @@ export function DatabaseTable({fetchDatabases(false);}}, [isFetchingMore, fetchDatabases]);- useScrollRestorationLoadMore({+ useListScrollRestorationLoadMore({dataList: databases,hasMore: !selectOnRowClick && hasMore,isFetchingMore,@@ -182,14 +184,18 @@ export function DatabaseTable({onLoadingChange?.(loading);}, [loading, onLoadingChange]);- const handleRowClick = useCallback((db: Database, e: React.MouseEvent) => {- const url = router.resolve(autoDatabaseRoute(db)).fullPath;- if (e.ctrlKey || e.metaKey) {- window.open(url, "_blank");- } else {- router.push(url);- }- }, []);+ const handleRowClick = useCallback(+ (db: Database, e: React.MouseEvent) => {+ const url = router.resolve(autoDatabaseRoute(db)).fullPath;+ if (e.ctrlKey || e.metaKey) {+ window.open(url, "_blank");+ } else {+ onOpenDatabase?.();+ router.push(url);+ }+ },+ [onOpenDatabase]+ );const pageSizeOptions = getPageSizeOptions();diff --git a/frontend/src/components/issue-activity/IssueCommentActivity.tsx b/frontend/src/components/issue-activity/IssueCommentActivity.tsxindex 263fc76fd6..3214f67a18 100644--- a/frontend/src/components/issue-activity/IssueCommentActivity.tsx+++ b/frontend/src/components/issue-activity/IssueCommentActivity.tsx@@ -6,7 +6,7 @@ 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 { buildPlanDeployRouteFromPlanName } from "@/app/router/routeHelpers";+import { buildPlanRolloutRouteFromPlanName } from "@/app/router/routeHelpers";import { HumanizeTs } from "@/components/HumanizeTs";import {type ActivityIconSpec,@@ -478,7 +478,7 @@ function IssueCommentActionSentence({const planRoute =linkless || !plan? undefined- : buildPlanDeployRouteFromPlanName(plan.name);+ : buildPlanRolloutRouteFromPlanName(plan.name);const sentence =issue?.approvalStatus === ApprovalStatus.APPROVED? planUIDdiff --git a/frontend/src/lib/plan/issue.ts b/frontend/src/lib/plan/issue.tsindex da92a258c3..92843250a0 100644--- a/frontend/src/lib/plan/issue.ts+++ b/frontend/src/lib/plan/issue.ts@@ -1,5 +1,5 @@import { router } from "@/app/router";-import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/app/router/handles";+import { buildPlanCreateRoute } from "@/app/router/routeHelpers";import { useAppStore } from "@/stores/app";import { isValidDatabaseGroupName, isValidDatabaseName } from "@/types";import {@@ -11,8 +11,6 @@ import {import { applyPlanTitleToQuery } from "./title";export const preCreateIssue = async (project: string, targets: string[]) => {- const type = "bb.plan.change-database";-const databaseNames: string[] = [];for (const target of targets) {if (isValidDatabaseGroupName(target)) {@@ -34,33 +32,22 @@ export const preCreateIssue = async (project: string, targets: string[]) => {.getOrFetchProjectByName(project);// Navigate to plan detail page- const query: Record<string, string> = {- template: type,- };+ const query: Record<string, string> = {};if (isDatabaseGroup) {const databaseGroupName = targets[0];query.databaseGroupName = databaseGroupName;applyPlanTitleToQuery(query, projectEntity, () =>- generatePlanTitle(type, [extractDatabaseGroupName(databaseGroupName)])+ generatePlanTitle([extractDatabaseGroupName(databaseGroupName)]));} else {query.databaseList = targets.join(",");applyPlanTitleToQuery(query, projectEntity, () =>generatePlanTitle(- type,targets.map((db) => extractDatabaseResourceName(db).databaseName)));}- router.push({- name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,- params: {- projectId: extractProjectResourceName(project),- planId: "create",- specId: "placeholder",- },- query,- });+ router.push(buildPlanCreateRoute(extractProjectResourceName(project), query));};diff --git a/frontend/src/lib/plan/title.test.ts b/frontend/src/lib/plan/title.test.tsindex cab61594cc..9f6b2be0a9 100644--- a/frontend/src/lib/plan/title.test.ts+++ b/frontend/src/lib/plan/title.test.ts@@ -33,15 +33,13 @@ describe("planQueryNameForProject", () => {describe("applyPlanTitleToQuery", () => {it("does not set query.name when the project enforces manual title", () => {- const query: Record<string, string> = {- template: "bb.plan.change-database",- };+ const query: Record<string, string> = {};applyPlanTitleToQuery(query,{ enforceIssueTitle: true },() => "Auto Title");- expect(query).toEqual({ template: "bb.plan.change-database" });+ expect(query).toEqual({});expect(query.name).toBeUndefined();});@@ -64,7 +62,6 @@ describe("applyPlanTitleToQuery", () => {it("preserves pre-existing keys on the query", () => {const query: Record<string, string> = {- template: "bb.plan.change-database",databaseList: "db1,db2",};applyPlanTitleToQuery(@@ -73,7 +70,6 @@ describe("applyPlanTitleToQuery", () => {() => "Auto Title");expect(query).toEqual({- template: "bb.plan.change-database",databaseList: "db1,db2",name: "Auto Title",});@@ -81,11 +77,11 @@ describe("applyPlanTitleToQuery", () => {it("clears a pre-existing query.name when enforceIssueTitle is true", () => {const query: Record<string, string> = {- template: "bb.plan.change-database",+ databaseList: "db1",name: "stale auto title",};applyPlanTitleToQuery(query, { enforceIssueTitle: true }, () => "fresh");expect(query.name).toBeUndefined();- expect(query.template).toBe("bb.plan.change-database"); // untouched+ expect(query.databaseList).toBe("db1");});});diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 960e9ca35c..f9702e9998 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -2106,7 +2106,6 @@}},"rollout": {- "no-stages": "No stages available","no-tasks-created": "No tasks created yet","pending-tasks-preview": {"action": "Preview",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 2d01d71da2..a98a7ee2fa 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -2106,7 +2106,6 @@}},"rollout": {- "no-stages": "No hay etapas disponibles","no-tasks-created": "Aún no se han creado tareas","pending-tasks-preview": {"action": "Vista previa",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 163607cff8..f4fdd76fab 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -2106,7 +2106,6 @@}},"rollout": {- "no-stages": "利用可能なステージはありません","no-tasks-created": "まだタスクが作成されていません","pending-tasks-preview": {"action": "プレビュー",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex bb01a4de4e..612a68c43f 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -2106,7 +2106,6 @@}},"rollout": {- "no-stages": "Không có giai đoạn nào","no-tasks-created": "Chưa có tác vụ nào được tạo","pending-tasks-preview": {"action": "Xem trước",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex b2cc981712..a9bca5d91e 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -2106,7 +2106,6 @@}},"rollout": {- "no-stages": "暂无阶段","no-tasks-created": "尚未创建任务","pending-tasks-preview": {"action": "预览",diff --git a/frontend/src/modules/sql-editor/components/ExecuteHint.tsx b/frontend/src/modules/sql-editor/components/ExecuteHint.tsxindex 7bc875fbe3..1f3bee9e96 100644--- a/frontend/src/modules/sql-editor/components/ExecuteHint.tsx+++ b/frontend/src/modules/sql-editor/components/ExecuteHint.tsx@@ -1,7 +1,7 @@import { Trans, useTranslation } from "react-i18next";import { v4 as uuidv4 } from "uuid";import { router } from "@/app/router";-import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/app/router/handles";+import { buildPlanCreateRoute } from "@/app/router/routeHelpers";import { Alert } from "@/components/ui/alert";import { Button } from "@/components/ui/button";import { applyPlanTitleToQuery } from "@/lib/plan/title";@@ -66,7 +66,6 @@ export function ExecuteHint({ database, onClose }: Props) {const { databaseName } = extractDatabaseResourceName(db.name);const query: Record<string, string> = {- template: "bb.plan.change-database",databaseList: db.name,sqlStorageKey,};@@ -76,15 +75,9 @@ export function ExecuteHint({ database, onClose }: Props) {() => `[${databaseName}] ${t("issue.title.change-from-sql-editor")}`);- const route = router.resolve({- name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,- params: {- projectId: extractProjectResourceName(db.project),- planId: "create",- specId: "placeholder",- },- query,- });+ const route = router.resolve(+ buildPlanCreateRoute(extractProjectResourceName(db.project), query)+ );window.open(route.fullPath, "_blank");};diff --git a/frontend/src/modules/sql-editor/components/SQLEditorHomePage.tsx b/frontend/src/modules/sql-editor/components/SQLEditorHomePage.tsxindex 3a4ad4f31d..8037e5c08d 100644--- a/frontend/src/modules/sql-editor/components/SQLEditorHomePage.tsx+++ b/frontend/src/modules/sql-editor/components/SQLEditorHomePage.tsx@@ -8,7 +8,7 @@ import {Separator as PanelResizeHandle,} from "react-resizable-panels";import { useNavigate } from "@/app/router";-import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/app/router/handles";+import { buildPlanCreateRoute } from "@/app/router/routeHelpers";import { IAMRemindDialog } from "@/components/IAMRemindDialog";import { Quickstart } from "@/components/Quickstart";import {@@ -118,7 +118,6 @@ export function SQLEditorHomePage() {database.name);const query: Record<string, string> = {- template: "bb.plan.change-database",databaseList: database.name,sql: exampleSQL.join(" "),};@@ -127,15 +126,12 @@ export function SQLEditorHomePage() {project,() => `[${dbName}] ${t("issue.title.edit-schema")}`);- const route = navigate.resolve({- name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,- params: {- projectId: extractProjectResourceName(database.project),- planId: "create",- specId: "placeholder",- },- query,- });+ const route = navigate.resolve(+ buildPlanCreateRoute(+ extractProjectResourceName(database.project),+ query+ )+ );window.open(route.fullPath, "_blank");});diff --git a/frontend/src/routes/project/ProjectDatabasesPage.tsx b/frontend/src/routes/project/ProjectDatabasesPage.tsxindex bc921b425d..a97e2f10af 100644--- a/frontend/src/routes/project/ProjectDatabasesPage.tsx+++ b/frontend/src/routes/project/ProjectDatabasesPage.tsx@@ -8,6 +8,7 @@ import {INSTANCE_ROUTE_CREATE,SQL_EDITOR_DATABASE_MODULE,} from "@/app/router/handles";+import { markListScrollRestorationEntry } from "@/app/router/NavigationScrollRestoration";import {AdvancedSearch,getValueFromScopes,@@ -680,6 +681,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {filter={filter}parent={projectName}mode="PROJECT"+ onOpenDatabase={markListScrollRestorationEntry}selectedNames={selectedNames}onSelectedNamesChange={setSelectedNames}onDatabasesChange={setVisibleDatabases}diff --git a/frontend/src/routes/project/ProjectIssueDashboardPage.tsx b/frontend/src/routes/project/ProjectIssueDashboardPage.tsxindex 59bc9e3231..5b5ca2a502 100644--- a/frontend/src/routes/project/ProjectIssueDashboardPage.tsx+++ b/frontend/src/routes/project/ProjectIssueDashboardPage.tsx@@ -1,10 +1,9 @@import { useCallback, useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";-import { useLocation } from "react-router";import {- markScrollRestorationEntry,- useScrollRestorationKey,- useScrollRestorationLoadMore,+ markListScrollRestorationEntry,+ useListScrollRestorationKey,+ useListScrollRestorationLoadMore,} from "@/app/router/NavigationScrollRestoration";import type { SearchParams } from "@/components/AdvancedSearch";import {@@ -50,8 +49,7 @@ export function ProjectIssueDashboardPage({projectId: string;}) {const { t } = useTranslation();- const location = useLocation();- const scrollRestorationKey = useScrollRestorationKey();+ const listScrollRestorationKey = useListScrollRestorationKey();const batchGetOrFetchUsers = useAppStore((state) => state.batchGetOrFetchUsers);@@ -141,10 +139,10 @@ export function ProjectIssueDashboardPage({sessionKey: "bb.issue-table.project-issues",cacheKey: viewCacheKey,cacheScope: projectIssuesPagedDataCacheScope(projectId),- cacheRestoreToken: scrollRestorationKey,+ cacheRestoreToken: listScrollRestorationKey,fetchList: fetchIssueList,});- useScrollRestorationLoadMore(paged);+ useListScrollRestorationLoadMore(paged);useEffect(() => {if (paged.dataList.length === 0) {@@ -183,11 +181,6 @@ export function ProjectIssueDashboardPage({return next;});}, []);- const handleOpenIssue = useCallback(- () => markScrollRestorationEntry(location),- [location]- );-const toggleSelectAll = useCallback(() => {setSelectedNames((prev) => {const allSelected =@@ -231,7 +224,7 @@ export function ProjectIssueDashboardPage({issues={paged.dataList}selectedNames={selectedNames}onToggleSelection={toggleSelection}- onOpenIssue={handleOpenIssue}+ onOpenIssue={markListScrollRestorationEntry}/>{paged.dataList.length > 0 && (<ProjectPageFooter className="px-2">diff --git a/frontend/src/routes/project/ProjectPlanDashboardPage.test.tsx b/frontend/src/routes/project/ProjectPlanDashboardPage.test.tsxindex 6e844d7324..875e4f981d 100644--- a/frontend/src/routes/project/ProjectPlanDashboardPage.test.tsx+++ b/frontend/src/routes/project/ProjectPlanDashboardPage.test.tsx@@ -24,9 +24,9 @@ const plan = {const mocks = vi.hoisted(() => ({batchGetOrFetchUsers: vi.fn(async () => []),listUsers: vi.fn(async () => ({ users: [] })),- markScrollRestorationEntry: vi.fn(),+ listScrollRestorationKey: undefined as string | undefined,+ markListScrollRestorationEntry: vi.fn(),routerPush: vi.fn(),- scrollRestorationKey: undefined as string | undefined,usePagedData: vi.fn(),}));@@ -151,9 +151,9 @@ vi.mock("@/app/router", () => ({}));vi.mock("@/app/router/NavigationScrollRestoration", () => ({- markScrollRestorationEntry: mocks.markScrollRestorationEntry,- useScrollRestorationKey: () => mocks.scrollRestorationKey,- useScrollRestorationLoadMore: () => undefined,+ markListScrollRestorationEntry: mocks.markListScrollRestorationEntry,+ useListScrollRestorationKey: () => mocks.listScrollRestorationKey,+ useListScrollRestorationLoadMore: () => undefined,}));vi.mock("@/stores/app", () => {@@ -185,7 +185,7 @@ describe("ProjectPlanDashboardPage scroll restoration", () => {document.body.appendChild(container);root = createRoot(container);mocks.usePagedData.mockReset();- mocks.scrollRestorationKey = undefined;+ mocks.listScrollRestorationKey = undefined;mocks.usePagedData.mockReturnValue({dataList: [plan],hasMore: true,@@ -233,7 +233,7 @@ describe("ProjectPlanDashboardPage scroll restoration", () => {});test("uses the item-click restoration key for paged data", () => {- mocks.scrollRestorationKey = "plans-entry";+ mocks.listScrollRestorationKey = "plans-entry";act(() => {root.render(<MemoryRouter>@@ -263,10 +263,10 @@ describe("ProjectPlanDashboardPage scroll restoration", () => {expect(row).not.toBeNull();act(() => row?.click());- expect(mocks.markScrollRestorationEntry).toHaveBeenCalledOnce();+ expect(mocks.markListScrollRestorationEntry).toHaveBeenCalledOnce();expect(mocks.routerPush).toHaveBeenCalledWith("/projects/foo/plans/1");expect(- mocks.markScrollRestorationEntry.mock.invocationCallOrder[0]+ mocks.markListScrollRestorationEntry.mock.invocationCallOrder[0]).toBeLessThan(mocks.routerPush.mock.invocationCallOrder[0]);});diff --git a/frontend/src/routes/project/ProjectPlanDashboardPage.tsx b/frontend/src/routes/project/ProjectPlanDashboardPage.tsxindex 58c67c691e..cd5ffa848d 100644--- a/frontend/src/routes/project/ProjectPlanDashboardPage.tsx+++ b/frontend/src/routes/project/ProjectPlanDashboardPage.tsx@@ -7,18 +7,15 @@ import {} from "lucide-react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";-import { useLocation } from "react-router";import { v4 as uuidv4 } from "uuid";import { router } from "@/app/router";+import { PROJECT_V1_ROUTE_PLAN_DETAIL } from "@/app/router/handles";import {- PROJECT_V1_ROUTE_PLAN_DETAIL,- PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,-} from "@/app/router/handles";-import {- markScrollRestorationEntry,- useScrollRestorationKey,- useScrollRestorationLoadMore,+ markListScrollRestorationEntry,+ useListScrollRestorationKey,+ useListScrollRestorationLoadMore,} from "@/app/router/NavigationScrollRestoration";+import { buildPlanCreateRoute } from "@/app/router/routeHelpers";import {AdvancedSearch,type ScopeOption,@@ -116,12 +113,7 @@ const parsePlanSearchParams = createAdvancedSearchParser(["state", "creator"]);export function ProjectPlanDashboardPage({ projectId }: { projectId: string }) {const { t } = useTranslation();- const location = useLocation();- const scrollRestorationKey = useScrollRestorationKey();- const handleOpenPlan = useCallback(- () => markScrollRestorationEntry(location),- [location]- );+ const listScrollRestorationKey = useListScrollRestorationKey();const projectsByName = useAppStore((s) => s.projectsByName);const listUsers = useAppStore((state) => state.listUsers);const batchGetOrFetchUsers = useAppStore(@@ -243,10 +235,10 @@ export function ProjectPlanDashboardPage({ projectId }: { projectId: string }) {sessionKey: `bb.${projectName}.plan-table`,cacheKey: viewCacheKey,cacheScope: projectPlansPagedDataCacheScope(projectId),- cacheRestoreToken: scrollRestorationKey,+ cacheRestoreToken: listScrollRestorationKey,fetchList: fetchPlanList,});- useScrollRestorationLoadMore(paged);+ useListScrollRestorationLoadMore(paged);useEffect(() => {if (paged.dataList.length === 0) {@@ -260,7 +252,6 @@ export function ProjectPlanDashboardPage({ projectId }: { projectId: string }) {async (spec: Plan_Spec) => {if (!project) return;- const template = "bb.plan.change-database";const targets =spec.config?.case === "changeDatabaseConfig"? [...(spec.config.value.targets ?? [])]@@ -268,7 +259,7 @@ export function ProjectPlanDashboardPage({ projectId }: { projectId: string }) {const isDatabaseGroup = targets.every((target) =>isValidDatabaseGroupName(target));- const query: Record<string, string> = { template };+ const query: Record<string, string> = {};// Check if the spec has a sheet with contentif (@@ -284,15 +275,12 @@ export function ProjectPlanDashboardPage({ projectId }: { projectId: string }) {if (!databaseGroupName) return;query.databaseGroupName = databaseGroupName;applyPlanTitleToQuery(query, project, () =>- generatePlanTitle(template, [- extractDatabaseGroupName(databaseGroupName),- ])+ generatePlanTitle([extractDatabaseGroupName(databaseGroupName)]));} else {query.databaseList = targets.join(",");applyPlanTitleToQuery(query, project, () =>generatePlanTitle(- template,targets.map((db) => {const { databaseName } = extractDatabaseResourceName(db);return databaseName;@@ -301,15 +289,7 @@ export function ProjectPlanDashboardPage({ projectId }: { projectId: string }) {);}- await router.push({- name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,- params: {- projectId,- planId: "create",- specId: "placeholder",- },- query,- });+ await router.push(buildPlanCreateRoute(projectId, query));},[project, projectId]);@@ -355,7 +335,7 @@ export function ProjectPlanDashboardPage({ projectId }: { projectId: string }) {<PlanTableplans={paged.dataList}projectId={projectId}- onOpenPlan={handleOpenPlan}+ onOpenPlan={markListScrollRestorationEntry}/>)}diff --git a/frontend/src/routes/project/ProjectReleaseDashboardPage.tsx b/frontend/src/routes/project/ProjectReleaseDashboardPage.tsxindex 41d479c3a6..ad0b155275 100644--- a/frontend/src/routes/project/ProjectReleaseDashboardPage.tsx+++ b/frontend/src/routes/project/ProjectReleaseDashboardPage.tsx@@ -4,7 +4,10 @@ import { useCallback, useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import { releaseServiceClientConnect } from "@/api";import { router } from "@/app/router";-import { useScrollRestorationLoadMore } from "@/app/router/NavigationScrollRestoration";+import {+ markListScrollRestorationEntry,+ useListScrollRestorationLoadMore,+} from "@/app/router/NavigationScrollRestoration";import { HumanizeTs } from "@/components/HumanizeTs";import { LearnMoreLink } from "@/components/LearnMoreLink";import {@@ -87,7 +90,7 @@ export function ProjectReleaseDashboardPage({sessionKey: `project-${projectName}-releases`,fetchList: fetchReleaseList,});- useScrollRestorationLoadMore(paged);+ useListScrollRestorationLoadMore(paged);return (<ProjectPageLayout>@@ -239,6 +242,7 @@ function ReleaseRow({ release }: { release: Release }) {if (e.ctrlKey || e.metaKey) {window.open(url, "_blank");} else {+ markListScrollRestorationEntry();router.push(url);}},diff --git a/frontend/src/routes/project/ProjectSyncSchemaPage.tsx b/frontend/src/routes/project/ProjectSyncSchemaPage.tsxindex 06515896bb..7367f6a75d 100644--- a/frontend/src/routes/project/ProjectSyncSchemaPage.tsx+++ b/frontend/src/routes/project/ProjectSyncSchemaPage.tsx@@ -13,7 +13,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { v4 as uuidv4 } from "uuid";import { router } from "@/app/router";-import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/app/router/handles";+import { buildPlanCreateRoute } from "@/app/router/routeHelpers";import { DatabaseSelect } from "@/components/DatabaseSelect";import { EngineIcon } from "@/components/EngineIcon";import { EnvironmentSelect } from "@/components/EnvironmentSelect";@@ -391,7 +391,6 @@ export function ProjectSyncSchemaPage({ projectId }: { projectId: string }) {useAppStore.getState().getDatabaseByName(name));const query: Record<string, string> = {- template: "bb.plan.change-database",mode: "normal",};const sqlMap: Record<string, string> = {};@@ -408,22 +407,15 @@ export function ProjectSyncSchemaPage({ projectId }: { projectId: string }) {if (!project) return; // defensive: should not happen if the page renderedapplyPlanTitleToQuery(query, project, () =>generatePlanTitle(- "bb.plan.change-database",targetDatabases.map((db) => extractDatabaseResourceName(db.name).databaseName)));- router.push({- name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,- params: {- projectId: extractProjectResourceName(project.name),- planId: "create",- specId: "placeholder",- },- query,- });+ router.push(+ buildPlanCreateRoute(extractProjectResourceName(project.name), query)+ );}, [selectedDatabaseNameList, schemaDiffCache, project]);if (!project) return null;diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailActionBar.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailActionBar.tsxindex b782f8a9ed..fa1b9a1f1f 100644--- a/frontend/src/routes/project/issue-detail/components/IssueDetailActionBar.tsx+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailActionBar.tsx@@ -27,8 +27,8 @@ import {PROJECT_V1_ROUTE_PLAN_DETAIL,} from "@/app/router/handles";import {- buildPlanDeployRouteFromPlanName,buildPlanDeployRouteFromRolloutName,+ buildPlanRolloutRouteFromPlanName,} from "@/app/router/routeHelpers";import { MarkdownEditor } from "@/components/MarkdownEditor";import { RouterLink } from "@/components/RouterLink";@@ -199,7 +199,7 @@ export function IssueDetailActionBar() {return undefined;}if (page.plan.hasRollout) {- return buildPlanDeployRouteFromPlanName(page.plan.name);+ return buildPlanRolloutRouteFromPlanName(page.plan.name);}return {name: PROJECT_V1_ROUTE_PLAN_DETAIL,@@ -783,7 +783,7 @@ function IssueDetailReviewPopover({) &&page.plan.hasRollout) {- void router.push(buildPlanDeployRouteFromPlanName(page.plan.name));+ void router.push(buildPlanRolloutRouteFromPlanName(page.plan.name));} else if (selectedAction !== "COMMENT" && issue) {void router.push({name: PROJECT_V1_ROUTE_ISSUE_DETAIL,diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailDatabaseChangeView.test.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailDatabaseChangeView.test.tsxindex ff7f644c74..9900da4ff6 100644--- a/frontend/src/routes/project/issue-detail/components/IssueDetailDatabaseChangeView.test.tsx+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailDatabaseChangeView.test.tsx@@ -136,7 +136,7 @@ const mocks = vi.hoisted(() => {extractInstanceResourceName: vi.fn(() => "inst1"),extractPlanUID: vi.fn(() => "123"),extractProjectResourceName: vi.fn(() => "db333"),- buildPlanDeployRouteFromPlanName: vi.fn(() => ({+ buildPlanRolloutRouteFromPlanName: vi.fn(() => ({name: "plan.detail",params: {},})),@@ -213,7 +213,7 @@ vi.mock("@/app/router", async (importOriginal) => ({vi.mock("@/app/router/routeHelpers", async (importOriginal) => ({...(await importOriginal<typeof import("@/app/router/routeHelpers")>()),- buildPlanDeployRouteFromPlanName: mocks.buildPlanDeployRouteFromPlanName,+ buildPlanRolloutRouteFromPlanName: mocks.buildPlanRolloutRouteFromPlanName,}));vi.mock("@/stores", () => ({diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailDatabaseChangeView.tsxindex 1f36643e2e..4d23531e07 100644--- a/frontend/src/routes/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx@@ -8,7 +8,7 @@ import {PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,} from "@/app/router/handles";-import { buildPlanDeployRouteFromPlanName } from "@/app/router/routeHelpers";+import { buildPlanRolloutRouteFromPlanName } from "@/app/router/routeHelpers";import { EngineIcon } from "@/components/EngineIcon";import { RouterLink } from "@/components/RouterLink";import { SearchInput } from "@/components/ui/search-input";@@ -90,7 +90,7 @@ export function IssueDetailDatabaseChangeView({return "";}const route = page.plan.hasRollout- ? buildPlanDeployRouteFromPlanName(page.plan.name)+ ? buildPlanRolloutRouteFromPlanName(page.plan.name): {name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,params: {diff --git a/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.test.tsx b/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.test.tsxindex 1ac1cf2be2..912a004a5b 100644--- a/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.test.tsx+++ b/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.test.tsx@@ -1,5 +1,5 @@import type { ReactNode } from "react";-import { act } from "react";+import { act, useRef } from "react";import { createRoot } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { MAIN_SCROLL_RESTORATION_ID } from "@/app/router/NavigationScrollRestoration";@@ -17,6 +17,9 @@ const mocks = vi.hoisted(() => ({removeItem: vi.fn(),setItem: vi.fn(),},+ branchMountCount: { value: 0 },+ routerPush: vi.fn(),+ selectedSpecRender: vi.fn(),usePlanDetailPage: vi.fn(),}));@@ -27,6 +30,12 @@ vi.mock("react-i18next", () => ({useTranslation: () => ({ t: (key: string) => key }),}));+vi.mock("@/app/router", () => ({+ router: {+ push: mocks.routerPush,+ },+}));+vi.mock("@/components/ui/alert-dialog", () => ({AlertDialog: ({ children }: { children: ReactNode }) => <>{children}</>,AlertDialogContent: ({ children }: { children: ReactNode }) => (@@ -74,14 +83,23 @@ vi.mock("./components/PlanDetailChangesBranch", () => ({}: {onSelectedSpecIdChange: (specId: string) => void;selectedSpecId: string;- }) => (- <div>- <div data-testid="selected-spec-id">{selectedSpecId}</div>- <button onClick={() => onSelectedSpecIdChange("spec-2")}>- select second spec- </button>- </div>- ),+ }) => {+ const mountId = useRef(0);+ if (mountId.current === 0) {+ mocks.branchMountCount.value += 1;+ mountId.current = mocks.branchMountCount.value;+ }+ mocks.selectedSpecRender(selectedSpecId);+ return (+ <div>+ <div data-testid="changes-mount-id">{mountId.current}</div>+ <div data-testid="selected-spec-id">{selectedSpecId}</div>+ <button onClick={() => onSelectedSpecIdChange("spec-2")}>+ select second spec+ </button>+ </div>+ );+ },}));vi.mock("./components/PlanDetailDeployFuture", () => ({@@ -115,6 +133,7 @@ let root: ReturnType<typeof createRoot>;beforeEach(() => {vi.clearAllMocks();+ mocks.branchMountCount.value = 0;container = document.createElement("div");document.body.appendChild(container);root = createRoot(container);@@ -168,8 +187,58 @@ const buildPage = (): PlanDetailPageState =>const selectedSpecIdText = () =>container.querySelector('[data-testid="selected-spec-id"]')?.textContent;+const changesMountIdText = () =>+ container.querySelector('[data-testid="changes-mount-id"]')?.textContent;describe("ProjectPlanDetailPage", () => {+ it("only expands phases while creating a plan", async () => {+ const page = buildPage();+ mocks.usePlanDetailPage.mockReturnValue(page);++ await act(async () => {+ root.render(+ <ProjectPlanDetailPage+ planId="create"+ projectId="foo"+ routeQuery={{}}+ />+ );+ await Promise.resolve();+ });++ const phaseRow = container.querySelector("#plan-phase-changes");+ const phaseDot = phaseRow?.firstElementChild+ ?.firstElementChild as HTMLElement | null;+ if (!phaseDot) throw new Error("Missing Changes phase selector");+ act(() => phaseDot.click());++ expect(page.expandPhase).toHaveBeenCalledWith("changes");+ expect(page.bypassLeaveGuardOnce).not.toHaveBeenCalled();+ expect(mocks.routerPush).not.toHaveBeenCalled();+ });++ it("keeps phase selection local on an existing plan", async () => {+ const page = buildPage();+ page.isCreating = false;+ page.isEditing = true;+ mocks.usePlanDetailPage.mockReturnValue(page);++ await act(async () => {+ root.render(<ProjectPlanDetailPage planId="1" projectId="foo" />);+ await Promise.resolve();+ });++ const phaseRow = container.querySelector("#plan-phase-review");+ const phaseDot = phaseRow?.firstElementChild+ ?.firstElementChild as HTMLElement | null;+ if (!phaseDot) throw new Error("Missing Review phase selector");+ act(() => phaseDot.click());++ expect(page.expandPhase).toHaveBeenCalledWith("review");+ expect(page.bypassLeaveGuardOnce).not.toHaveBeenCalled();+ expect(mocks.routerPush).not.toHaveBeenCalled();+ });+it("uses the dashboard main pane as its vertical scroll owner", async () => {mocks.usePlanDetailPage.mockReturnValue(buildPage());@@ -238,6 +307,59 @@ describe("ProjectPlanDetailPage", () => {expect(selectedSpecIdText()).toBe("spec-2");});+ it("selects the first client-local spec on the first create-route render", async () => {+ mocks.usePlanDetailPage.mockReturnValue(buildPage());++ await act(async () => {+ root.render(+ <ProjectPlanDetailPage planId="create" projectId="foo" routeQuery={{}} />+ );+ });++ expect(+ mocks.selectedSpecRender.mock.calls.every(([id]) => id === "spec-1")+ ).toBe(true);+ expect(selectedSpecIdText()).toBe("spec-1");+ });++ it("renders a route-selected spec without an intermediate stale spec", async () => {+ const page = buildPage();+ page.isCreating = false;+ page.pageKey = "foo/plan-1";+ page.planId = "plan-1";+ mocks.usePlanDetailPage.mockReturnValue(page);++ await act(async () => {+ root.render(+ <ProjectPlanDetailPage+ planId="plan-1"+ projectId="foo"+ specId="spec-1"+ />+ );+ await Promise.resolve();+ });+ expect(selectedSpecIdText()).toBe("spec-1");+ expect(changesMountIdText()).toBe("1");++ mocks.selectedSpecRender.mockClear();+ await act(async () => {+ root.render(+ <ProjectPlanDetailPage+ planId="plan-1"+ projectId="foo"+ specId="spec-2"+ />+ );+ });++ expect(mocks.selectedSpecRender.mock.calls.map(([id]) => id)).toEqual([+ "spec-2",+ ]);+ expect(selectedSpecIdText()).toBe("spec-2");+ expect(changesMountIdText()).toBe("1");+ });+it("resets spec selection when navigating to another plan", async () => {const firstPage = buildPage();firstPage.isCreating = false;@@ -280,6 +402,7 @@ describe("ProjectPlanDetailPage", () => {});expect(selectedSpecIdText()).toBe("new-spec");+ expect(changesMountIdText()).toBe("2");});it("renders the review phase for sheet-backed plans with an issue", async () => {diff --git a/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx b/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsxindex 445a565dfd..e4fb794b8e 100644--- a/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx+++ b/frontend/src/routes/project/plan-detail/ProjectPlanDetailPage.tsx@@ -11,6 +11,7 @@ import {} from "@/components/ui/alert-dialog";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";+import { useOnKeyChange } from "@/hooks/useOnKeyChange";import { cn } from "@/lib/utils";import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";@@ -44,12 +45,15 @@ function phaseLineClass(from: PhaseStatus, to: PhaseStatus): string {export function ProjectPlanDetailPage(props: {projectId: string;planId: string;+ routeHash?: string;routeName?: string;routeQuery?: Record<string, unknown>;specId?: string;+ stageId?: string;+ taskId?: string;}) {return (- <PlanDetailStoreProvider>+ <PlanDetailStoreProvider key={`${props.projectId}/${props.planId}`}><ProjectPlanDetailPageInner {...props} /></PlanDetailStoreProvider>);@@ -58,15 +62,21 @@ export function ProjectPlanDetailPage(props: {function ProjectPlanDetailPageInner({projectId,planId,+ routeHash,routeName,routeQuery,specId,+ stageId,+ taskId,}: {projectId: string;planId: string;+ routeHash?: string;routeName?: string;routeQuery?: Record<string, unknown>;specId?: string;+ stageId?: string;+ taskId?: string;}) {const { t } = useTranslation();const [pageHost, setPageHost] = useState<HTMLDivElement | null>(null);@@ -89,9 +99,12 @@ function ProjectPlanDetailPageInner({const page = usePlanDetailPage({projectId,planId,+ routeHash,routeName,routeQuery,specId,+ stageId,+ taskId,});const isGitOpsPlan = useMemo(() => isReleaseBackedPlan(page.plan.specs),@@ -101,6 +114,7 @@ function ProjectPlanDetailPageInner({// before an issue exists it shows as an upcoming step. Only GitOps// release-backed plans, which bypass review entirely, hide it.const reviewVisible = !isGitOpsPlan;+ const selectPhase = page.expandPhase;const phaseConfigs = useMemo(() => {const hasIssue = !!page.issue;@@ -219,26 +233,20 @@ function ProjectPlanDetailPageInner({};}, [page.isCreating, page.issue, page.rollout, reviewVisible, t]);- useEffect(() => {- setSelectedSpecId(specId ?? "");- }, [page.pageKey]);-- // Mirror the URL specId into local state. We deliberately don't include- // selectedSpecId in the deps — children (e.g. PlanDetailChangesBranch) may- // set selectedSpecId to a draft spec that has no URL yet, and snapping it- // back to specId here would defeat the selection.- useEffect(() => {+ // Route-driven spec changes reset during render, so the first paint after a+ // Back/Forward or tab navigation already shows the destination spec. The+ // keyed provider remounts this subtree when the plan itself changes.+ useOnKeyChange(`${page.pageKey}:${specId ?? ""}`, () => {if (!page.isCreating && specId) {setSelectedSpecId(specId);}- }, [page.isCreating, specId]);+ });- // Default to the first spec when nothing is selected.- useEffect(() => {- if (!selectedSpecId && page.plan.specs.length > 0) {- setSelectedSpecId(page.plan.specs[0].id);- }- }, [page.plan.specs, selectedSpecId]);+ // A create route has no persisted spec resource in its URL. Derive the+ // initial selection during render so the first ready paint already shows the+ // first client-local spec, without a placeholder route or a follow-up effect.+ const effectiveSelectedSpecId =+ selectedSpecId || page.plan.specs[0]?.id || "";return (<PlanDetailProvider value={page}>@@ -279,14 +287,14 @@ function ProjectPlanDetailPageInner({icon={<Code2 className="size-3 md:size-4" />}lineClass={phaseConfigs.changes.lineClass}label={t("plan.navigator.changes")}- onSelect={() => page.expandPhase("changes")}+ onSelect={() => selectPhase("changes")}status={phaseConfigs.changes.status}onToggle={() => page.togglePhase("changes")}summary={buildChangesSummary(page.plan, t)}><PlanDetailChangesBranchonSelectedSpecIdChange={setSelectedSpecId}- selectedSpecId={selectedSpecId}+ selectedSpecId={effectiveSelectedSpecId}/></PhaseSection>@@ -298,7 +306,7 @@ function ProjectPlanDetailPageInner({icon={<MessageSquareMore className="size-3 md:size-4" />}lineClass={phaseConfigs.review.lineClass}label={t("plan.navigator.review")}- onSelect={() => page.expandPhase("review")}+ onSelect={() => selectPhase("review")}status={phaseConfigs.review.status}onToggle={() => page.togglePhase("review")}summary={buildReviewSummary(page.issue, t)}@@ -320,7 +328,7 @@ function ProjectPlanDetailPageInner({isLastlabel={t("plan.navigator.deploy")}status={phaseConfigs.deploy.status}- onSelect={() => page.expandPhase("deploy")}+ onSelect={() => selectPhase("deploy")}onToggle={() => page.togglePhase("deploy")}summary={buildDeploySummary(page.issue?.draft ? undefined : page.rollout,diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.test.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.test.tsxindex 096e053b2c..899ceda646 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.test.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.test.tsx@@ -625,7 +625,11 @@ function TestHarness({ rerenderToken }: { rerenderToken: number }) {);}-function StatefulSpecHarness() {+function StatefulSpecHarness({+ targets = [[], []],+}: {+ targets?: [string[], string[]];+}) {const [selectedSpecId, setSelectedSpecId] = useState("spec-1");const page = buildPageState();page.plan.specs = [@@ -634,7 +638,7 @@ function StatefulSpecHarness() {config: {case: "changeDatabaseConfig",value: {- targets: [],+ targets: targets[0],},},},@@ -643,7 +647,7 @@ function StatefulSpecHarness() {config: {case: "changeDatabaseConfig",value: {- targets: [],+ targets: targets[1],},},},@@ -1075,6 +1079,50 @@ describe("PlanDetailChangesBranch", () => {expect(container.textContent).not.toContain("spec-2:check-run-for-spec-1");});+ it("does not show target loading when switching between cached changes", () => {+ mocks.databaseStore.getOrFetchDatabaseByName.mockImplementation(+ () => new Promise(() => {})+ );++ act(() => {+ root.render(+ <StatefulSpecHarness targets={[[DB_WIDGETS], [DB_COGS]]} />+ );+ });++ expect(+ container.querySelector('[data-testid="targets-loading"]')+ ).toBeNull();++ const specTabs = [...container.querySelectorAll("button")].filter(+ (button) => button.textContent?.includes("plan.spec.type.database-change")+ );+ expect(specTabs.length).toBe(2);++ act(() => {+ specTabs[1]?.click();+ });++ expect(+ container.querySelector('[data-testid="targets-loading"]')+ ).toBeNull();+ });++ it("shows target loading while a change target is not cached", () => {+ mocks.databaseStore.getDatabaseByName.mockReturnValue({ name: "" });+ mocks.databaseStore.getOrFetchDatabaseByName.mockImplementation(+ () => new Promise(() => {})+ );++ act(() => {+ root.render(<StatefulSpecHarness targets={[[DB_WIDGETS], []]} />);+ });++ expect(+ container.querySelector('[data-testid="targets-loading"]')+ ).not.toBeNull();+ });+it("keeps hook order stable when the selected spec appears after an empty render", async () => {const consoleError = vi.spyOn(console, "error")diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsxindex 0f8663c5d0..44432b8e57 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailChangesBranch.tsx@@ -68,6 +68,7 @@ import {import { Switch } from "@/components/ui/switch";import { Tooltip } from "@/components/ui/tooltip";import { useCurrentUser } from "@/hooks/useAppState";+import { useOnKeyChange } from "@/hooks/useOnKeyChange";import { useProjectByName } from "@/hooks/useProjectByName";import { useSessionPageSize } from "@/hooks/useSessionPageSize";import { seedSheetStatement } from "@/hooks/useSheetStatement";@@ -163,10 +164,13 @@ const pushSpecDetailRoute = (planId: string,specId: string) =>- router.push({- name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,- params: { planId, projectId, specId },- });+ router.push(+ {+ name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,+ params: { planId, projectId, specId },+ },+ { preventScrollReset: true }+ );type IsolationLevel =| "READ_UNCOMMITTED"@@ -1314,16 +1318,25 @@ function TargetsSection({}, [selectedSpec]);const [showAllTargetsDialog, setShowAllTargetsDialog] = useState(false);const [searchText, setSearchText] = useState("");- // Start loading when there are targets to resolve, so the first paint shows- // the spinner instead of blank (unknownDatabase) chips.- const [isLoadingTargets, setIsLoadingTargets] = useState(- () => targets.length > 0- );- const [isLoadingAllTargets, setIsLoadingAllTargets] = useState(false);const visibleTargets = useMemo(() => targets.slice(0, Math.min(DEFAULT_VISIBLE_TARGETS, targets.length)),[targets]);+ const visibleTargetsKey = useMemo(+ () => visibleTargets.join("\0"),+ [visibleTargets]+ );+ const visibleTargetsCached = useMemo(+ () => areTargetsCached(visibleTargets, databasesByName),+ [databasesByName, visibleTargets]+ );+ const [isLoadingTargets, setIsLoadingTargets] = useState(+ () => visibleTargets.length > 0 && !visibleTargetsCached+ );+ const [isLoadingAllTargets, setIsLoadingAllTargets] = useState(false);+ useOnKeyChange(visibleTargetsKey, () => {+ setIsLoadingTargets(visibleTargets.length > 0 && !visibleTargetsCached);+ });const nonEnvDatabaseNames = useMemo(() => {if (isLoadingTargets) return [];return targets@@ -1366,7 +1379,7 @@ function TargetsSection({useEffect(() => {let canceled = false;const load = async () => {- if (targets.length === 0) {+ if (visibleTargets.length === 0 || visibleTargetsCached) {setIsLoadingTargets(false);return;}@@ -1381,7 +1394,7 @@ function TargetsSection({return () => {canceled = true;};- }, [targets, visibleTargets]);+ }, [visibleTargets, visibleTargetsCached]);useEffect(() => {if (!showAllTargetsDialog) return;@@ -1445,7 +1458,10 @@ function TargetsSection({/>)}{isLoadingTargets ? (- <div className="flex items-center justify-center py-2">+ <div+ className="flex items-center justify-center py-2"+ data-testid="targets-loading"+ ><div className="h-5 w-5 animate-spin rounded-full border-2 border-control-border border-t-accent" /></div>) : targets.length > 0 ? (@@ -2177,3 +2193,25 @@ async function fetchTargets(targets: string[]) {}));}++function areTargetsCached(+ targets: string[],+ databasesByName: Record<string, Database>+): boolean {+ const store = useAppStore.getState();+ return targets.every((target) => {+ if (isValidDatabaseName(target)) {+ return isValidDatabaseName(databasesByName[target]?.name ?? "");+ }+ if (!isValidDatabaseGroupName(target)) {+ return true;+ }+ const group = store.getDBGroupByName(target, DatabaseGroupView.FULL);+ return (+ isValidDatabaseGroupName(group.name) &&+ (group.matchedDatabases ?? []).every((database) =>+ isValidDatabaseName(databasesByName[database.name]?.name ?? "")+ )+ );+ });+}diff --git a/frontend/src/routes/project/plan-detail/components/deploy/DeployBranch.test.tsx b/frontend/src/routes/project/plan-detail/components/deploy/DeployBranch.test.tsxindex 54ee0888e1..17252939b2 100644--- a/frontend/src/routes/project/plan-detail/components/deploy/DeployBranch.test.tsx+++ b/frontend/src/routes/project/plan-detail/components/deploy/DeployBranch.test.tsx@@ -19,11 +19,14 @@ vi.mock("./DeployStageCard", () => ({DeployStageList: ({onSelectStage,rollout,+ selectedStageId,}: {onSelectStage: (stage: Stage) => void;rollout: Rollout;+ selectedStageId: string;}) => (<div>+ <span data-testid="selected-stage-id">{selectedStageId}</span>{rollout.stages.map((stage) => (<buttonkey={stage.name}@@ -47,7 +50,7 @@ vi.mock("../../utils/rolloutPreview", () => ({generateRolloutPreview: () => Promise.resolve({ stages: [] }),}));-const ROLLOUT = "projects/p/rollouts/r";+const ROLLOUT = "projects/p/plans/1/rollout";const stage = (id: string): Stage =>({name: `${ROLLOUT}/stages/${id}`,@@ -70,6 +73,18 @@ const makePage = (routeStageId: string): PlanDetailPageState =>}) as unknown as PlanDetailPageState;describe("DeployBranch stage selection", () => {+ test("uses the rollout frontier while a stale stage route canonicalizes", () => {+ render(+ <PlanDetailProvider value={makePage("missing")}>+ <DeployBranch />+ </PlanDetailProvider>+ );++ expect(screen.getByTestId("selected-stage-id")).toHaveTextContent(+ `${ROLLOUT}/stages/a`+ );+ });+test("a quick click back to the route stage supersedes a pending optimistic switch", () => {routerMocks.push.mockClear();render(@@ -81,16 +96,24 @@ describe("DeployBranch stage selection", () => {// Switch to b optimistically. routeStageId still reads "a" (its URL// re-render is pending), but the view now shows b.fireEvent.click(screen.getByTestId("select-b"));- expect(routerMocks.push).toHaveBeenLastCalledWith({- query: { phase: "deploy", stageId: "b" },- });+ expect(routerMocks.push).toHaveBeenLastCalledWith(+ {+ name: "workspace.project.plan.detail.rollout.stage",+ params: { projectId: "p", planId: "1", stageId: "b" },+ },+ { preventScrollReset: true }+ );// Immediately click back to a. This must NOT be dropped as a no-op just// because routeStageId still reads "a" — the on-screen stage is b, so the// click has to push a and win over the pending b navigation.fireEvent.click(screen.getByTestId("select-a"));- expect(routerMocks.push).toHaveBeenLastCalledWith({- query: { phase: "deploy", stageId: "a" },- });+ expect(routerMocks.push).toHaveBeenLastCalledWith(+ {+ name: "workspace.project.plan.detail.rollout.stage",+ params: { projectId: "p", planId: "1", stageId: "a" },+ },+ { preventScrollReset: true }+ );});});diff --git a/frontend/src/routes/project/plan-detail/components/deploy/DeployBranch.tsx b/frontend/src/routes/project/plan-detail/components/deploy/DeployBranch.tsxindex a1d9151074..89a53612c2 100644--- a/frontend/src/routes/project/plan-detail/components/deploy/DeployBranch.tsx+++ b/frontend/src/routes/project/plan-detail/components/deploy/DeployBranch.tsx@@ -1,6 +1,7 @@import { useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import { router } from "@/app/router";+import { buildStageRoute } from "@/app/router/routeHelpers";import { Button } from "@/components/ui/button";import type { Plan } from "@/types/proto-es/v1/plan_service_pb";import type { Rollout, Task } from "@/types/proto-es/v1/rollout_service_pb";@@ -44,7 +45,7 @@ async function loadPendingGroups(export function DeployBranch() {const { t } = useTranslation();const page = usePlanDetailContext();- // Full task resource name resolved from the ?taskId= deep link.+ // Full task resource name resolved from the task route.const selectedTaskName = page.selectedTaskName;const projectName = `projects/${page.projectId}`;const [pendingOpen, setPendingOpen] = useState(false);@@ -106,12 +107,16 @@ export function DeployBranch() {}}if (page.routeStageId) {- return page.rollout.stages.find((stage) =>+ const routeStage = page.rollout.stages.find((stage) =>stage.name.endsWith(`/${page.routeStageId}`));+ if (routeStage) {+ return routeStage;+ }}- // Default to the frontier (first non-complete) stage, falling back to the- // first stage once every stage is complete.+ // A missing route stage canonicalizes to the rollout route. Render that+ // route's frontier synchronously too, so a stale URL cannot flash the+ // misleading empty-stage state before the replace settles.return getFrontierStage(page.rollout) ?? page.rollout.stages[0];}, [page.rollout, page.routeStageId, selectedTaskName, optimisticStageName]);@@ -168,11 +173,7 @@ export function DeployBranch() {}if (!selectedStage) {- return (- <div className="flex items-center justify-center py-12">- <p className="text-control-light">{t("rollout.no-stages")}</p>- </div>- );+ return null;}return (@@ -191,13 +192,12 @@ export function DeployBranch() {if (stage.name === selectedStage.name) {return;}- const stageId = extractStageUID(stage.name);setOptimisticStageName(stage.name);// The URL carries only the stage; each stage's card expansion is its// own local state (kept alive across switches), so there's nothing// per-task to restore through the URL.- const target = { query: { phase: "deploy", stageId } };- // A stage switch is an internal same-path query change and a pure+ const target = buildStageRoute(stage.name);+ // A stage switch is an internal resource selection and a pure// visibility flip — keep-alive preserves every stage's editor state,// so no edit is lost. Bypass the unsaved-edits guard so it doesn't// cancel this push or pop a spurious discard dialog. Arm it ONLY when@@ -213,7 +213,7 @@ export function DeployBranch() {) {page.bypassLeaveGuardOnce();}- void router.push(target);+ void router.push(target, { preventScrollReset: true });}}rollout={page.rollout}selectedStageId={selectedStage.name}diff --git a/frontend/src/routes/project/plan-detail/components/deploy/DeployTaskList.test.tsx b/frontend/src/routes/project/plan-detail/components/deploy/DeployTaskList.test.tsxindex 2e41cd4422..7857855d51 100644--- a/frontend/src/routes/project/plan-detail/components/deploy/DeployTaskList.test.tsx+++ b/frontend/src/routes/project/plan-detail/components/deploy/DeployTaskList.test.tsx@@ -9,17 +9,22 @@ import type { PlanDetailPageState } from "../../shell/hooks/types";import { PlanDetailProvider } from "../../shell/PlanDetailContext";import { DeployTaskList } from "./DeployTaskList";+const componentMocks = vi.hoisted(() => ({+ onToggleExpand: vi.fn(),+}));+vi.mock("react-i18next", () => ({initReactI18next: { type: "3rdParty", init: () => undefined },useTranslation: () => ({ t: (key: string) => key }),}));const routerMocks = vi.hoisted(() => ({+ push: vi.fn(),replace: vi.fn(),}));vi.mock("@/app/router", () => ({- router: { replace: routerMocks.replace },+ router: { push: routerMocks.push, replace: routerMocks.replace },}));vi.mock("./DeployTaskItem", () => ({@@ -33,17 +38,20 @@ vi.mock("./DeployTaskItem", () => ({deepLinked: boolean;isExpanded: boolean;onToggleExpand: (task: Task) => void;- }) => (- // One control per card: clicking the card toggles it open or closed.- <div- data-deeplinked={deepLinked ? "true" : "false"}- data-expanded={isExpanded ? "true" : "false"}- data-testid="task"- onClick={() => onToggleExpand(task)}- >- {task.name}- </div>- ),+ }) => {+ componentMocks.onToggleExpand(onToggleExpand);+ return (+ // One control per card: clicking the card toggles it open or closed.+ <div+ data-deeplinked={deepLinked ? "true" : "false"}+ data-expanded={isExpanded ? "true" : "false"}+ data-testid="task"+ onClick={() => onToggleExpand(task)}+ >+ {task.name}+ </div>+ );+ },}));vi.mock("./DeployTaskToolbar", () => ({ DeployTaskToolbar: () => null }));@@ -107,7 +115,7 @@ describe("DeployTaskList stage switching (BYT-9763)", () => {});describe("DeployTaskList first-actionable auto-expand", () => {- const stageName = "rollouts/r/stages/s";+ const stageName = "projects/p/plans/plan-1/rollout/stages/s";const taskName = (id: string) => `${stageName}/tasks/${id}`;test("expands the first running task over earlier finished ones", () => {@@ -144,14 +152,14 @@ describe("DeployTaskList first-actionable auto-expand", () => {});describe("DeployTaskList deep-linked task", () => {- const stageName = "rollouts/r/stages/s";+ const stageName = "projects/p/plans/plan-1/rollout/stages/s";const taskName = (id: number) => `${stageName}/tasks/t${id}`;const manyTasks = Array.from({ length: 30 }, (_, i) => taskName(i + 1));test("expands only the deep-linked task, not the auto pick", () => {const stage = makeStage(stageName, [taskName(1), taskName(2), taskName(3)]);render(renderList(stage, taskName(3)));- // An explicit ?taskId= selection is the focus — the auto pick (the first+ // An explicit task resource is the focus — the auto pick (the first// task) must NOT also open, or a reloaded deep link shows two cards.expect(expandedOf(taskName(1))).toBe("false");expect(expandedOf(taskName(2))).toBe("false");@@ -177,11 +185,11 @@ describe("DeployTaskList deep-linked task", () => {});describe("DeployTaskList mirrors the focused task into the URL", () => {- const stageName = "rollouts/r/stages/s";+ const stageName = "projects/p/plans/plan-1/rollout/stages/s";const taskName = (id: number) => `${stageName}/tasks/t${id}`;- test("mounting an active stage writes its default task to the URL", () => {- routerMocks.replace.mockClear();+ test("mounting an active stage does not write its automatic default", () => {+ routerMocks.push.mockClear();const stage = makeStage(stageName, [{ name: taskName(1), status: Task_Status.DONE },{ name: taskName(2), status: Task_Status.RUNNING },@@ -192,16 +200,14 @@ describe("DeployTaskList mirrors the focused task into the URL", () => {</PlanDetailProvider>);- // The default focus (first running task) is expanded and mirrored so the- // URL is a shareable link to the stage + task from the start.+ // The first running task expands, but automatic selection must not make a+ // rollout/stage URL more specific or create a history entry.expect(expandedOf(taskName(2))).toBe("true");- expect(routerMocks.replace).toHaveBeenCalledWith({- query: { phase: "deploy", stageId: "s", taskId: "t2" },- });+ expect(routerMocks.push).not.toHaveBeenCalled();});test("opening a card writes that task to the URL", () => {- routerMocks.replace.mockClear();+ routerMocks.push.mockClear();const stage = makeStage(stageName, [taskName(1), taskName(2)]);render(<PlanDetailProvider value={makePage()}>@@ -212,23 +218,61 @@ describe("DeployTaskList mirrors the focused task into the URL", () => {// t1 is the default; opening t2 focuses it and mirrors it into the URL.fireEvent.click(screen.getByText(taskName(2)));expect(expandedOf(taskName(2))).toBe("true");- expect(routerMocks.replace).toHaveBeenLastCalledWith({- query: { phase: "deploy", stageId: "s", taskId: "t2" },- });+ expect(routerMocks.push).toHaveBeenLastCalledWith(+ {+ name: "workspace.project.plan.detail.rollout.stage.task",+ params: {+ projectId: "p",+ planId: "plan-1",+ stageId: "s",+ taskId: "t2",+ },+ },+ { preventScrollReset: true }+ );+ });++ test("keeps card toggle callbacks stable across route and edit changes", () => {+ const stage = makeStage(stageName, [taskName(1)]);+ const { rerender } = render(+ <PlanDetailProvider value={makePage()}>+ <DeployTaskList stage={stage} />+ </PlanDetailProvider>+ );+ const callback = componentMocks.onToggleExpand.mock.calls.at(-1)?.[0];+ componentMocks.onToggleExpand.mockClear();++ rerender(+ <PlanDetailProvider+ value={+ {+ ...makePage(taskName(1)),+ isEditing: true,+ } as PlanDetailPageState+ }+ >+ <DeployTaskList stage={stage} />+ </PlanDetailProvider>+ );++ expect(componentMocks.onToggleExpand).toHaveBeenCalled();+ for (const [nextCallback] of componentMocks.onToggleExpand.mock.calls) {+ expect(nextCallback).toBe(callback);+ }});test("preview (readonly) never writes the URL", () => {- routerMocks.replace.mockClear();+ routerMocks.push.mockClear();const stage = makeStage(stageName, [taskName(1), taskName(2)]);render(renderList(stage));fireEvent.click(screen.getByText(taskName(2)));expect(expandedOf(taskName(2))).toBe("true");- expect(routerMocks.replace).not.toHaveBeenCalled();+ expect(routerMocks.push).not.toHaveBeenCalled();});- test("landing with a ?taskId= honors it without re-writing", () => {- routerMocks.replace.mockClear();+ test("landing on a task resource honors it without re-writing", () => {+ routerMocks.push.mockClear();const stage = makeStage(stageName, [taskName(1), taskName(2)]);render(<PlanDetailProvider value={makePage(taskName(2))}>@@ -236,14 +280,14 @@ describe("DeployTaskList mirrors the focused task into the URL", () => {</PlanDetailProvider>);- // The incoming ?taskId= already matches the focus — no redundant write.+ // The incoming task path already matches the focus — no redundant write.expect(expandedOf(taskName(2))).toBe("true");- expect(routerMocks.replace).not.toHaveBeenCalled();+ expect(routerMocks.push).not.toHaveBeenCalled();});});describe("DeployTaskList keep-alive activation", () => {- const stageName = "rollouts/r/stages/s";+ const stageName = "projects/p/plans/plan-1/rollout/stages/s";const taskName = (id: number) => `${stageName}/tasks/t${id}`;const renderActive = (stage: Stage, active: boolean) => (@@ -253,31 +297,29 @@ describe("DeployTaskList keep-alive activation", () => {);test("a hidden list mounts collapsed and never writes the URL", () => {- routerMocks.replace.mockClear();+ routerMocks.push.mockClear();const stage = makeStage(stageName, [taskName(1), taskName(2)]);render(renderActive(stage, false));// No default expansion (that would mount Monaco + fetch logs offscreen)- // and no ?taskId= mirror from a stage the user isn't looking at.+ // and no task-route write from a stage the user isn't looking at.expect(expandedOf(taskName(1))).toBe("false");expect(expandedOf(taskName(2))).toBe("false");- expect(routerMocks.replace).not.toHaveBeenCalled();+ expect(routerMocks.push).not.toHaveBeenCalled();});- test("first activation expands the default task and mirrors it", () => {- routerMocks.replace.mockClear();+ test("first activation expands the default task without changing the URL", () => {+ routerMocks.push.mockClear();const stage = makeStage(stageName, [taskName(1), taskName(2)]);const { rerender } = render(renderActive(stage, false));rerender(renderActive(stage, true));expect(expandedOf(taskName(1))).toBe("true");- expect(routerMocks.replace).toHaveBeenCalledWith({- query: { phase: "deploy", stageId: "s", taskId: "t1" },- });+ expect(routerMocks.push).not.toHaveBeenCalled();});test("first activation reseeds focus to a task that went active while hidden", () => {- routerMocks.replace.mockClear();+ routerMocks.push.mockClear();// Mount hidden with everything not-started — the captured default focus is// the first task.const hidden = makeStage(stageName, [@@ -294,17 +336,15 @@ describe("DeployTaskList keep-alive activation", () => {]);rerender(renderActive(running, false));- // On first activation the default-open card AND the URL mirror must reflect- // the current statuses (t2), not the stale mount-time default (t1).+ // On first activation the default-open card reflects current status, but+ // the automatic choice does not write a task URL.rerender(renderActive(running, true));expect(expandedOf(taskName(2))).toBe("true");- expect(routerMocks.replace).toHaveBeenLastCalledWith({- query: { phase: "deploy", stageId: "s", taskId: "t2" },- });+ expect(routerMocks.push).not.toHaveBeenCalled();});test("bypasses the leave guard for the internal URL sync while editing", () => {- routerMocks.replace.mockClear();+ routerMocks.push.mockClear();const bypass = vi.fn();const stage = makeStage(stageName, [{ name: taskName(1), status: Task_Status.DONE },@@ -320,19 +360,19 @@ describe("DeployTaskList keep-alive activation", () => {<DeployTaskList stage={stage} /></PlanDetailProvider>);- // The internal same-path mirror still writes the URL, and bypasses the- // unsaved-edits guard so no discard dialog interrupts it mid-edit.- expect(routerMocks.replace).toHaveBeenCalledWith({- query: { phase: "deploy", stageId: "s", taskId: "t2" },- });+ fireEvent.click(screen.getByText(taskName(1)));+ // Explicit task navigation bypasses the page-level guard because task-card+ // state is kept alive within the same persistent plan shell.+ expect(routerMocks.push).toHaveBeenCalled();expect(bypass).toHaveBeenCalled();});test("does not touch the leave guard when not editing", () => {- routerMocks.replace.mockClear();+ routerMocks.push.mockClear();const bypass = vi.fn();const stage = makeStage(stageName, [{ name: taskName(1), status: Task_Status.RUNNING },+ { name: taskName(2), status: Task_Status.NOT_STARTED },]);const page = {...makePage(),@@ -344,7 +384,8 @@ describe("DeployTaskList keep-alive activation", () => {<DeployTaskList stage={stage} /></PlanDetailProvider>);- expect(routerMocks.replace).toHaveBeenCalled();+ fireEvent.click(screen.getByText(taskName(2)));+ expect(routerMocks.push).toHaveBeenCalled();expect(bypass).not.toHaveBeenCalled();});@@ -364,10 +405,10 @@ describe("DeployTaskList keep-alive activation", () => {});describe("DeployTaskList arrival scroll (BYT-9765 offset jump)", () => {- const stageName = "rollouts/r/stages/s";+ const stageName = "projects/p/plans/plan-1/rollout/stages/s";const taskName = (id: number) => `${stageName}/tasks/t${id}`;- test("a genuine ?taskId= arrival deep-links its card", () => {+ test("a genuine task-route arrival deep-links its card", () => {const stage = makeStage(stageName, [taskName(1), taskName(2)]);// Arrived via a shared link to t2 (nothing self-written yet).render(@@ -401,6 +442,25 @@ describe("DeployTaskList arrival scroll (BYT-9765 offset jump)", () => {expect(deepLinkedOf(taskName(2))).toBe("false");});+ test("Back to the stage route does not restore the previous task URL", () => {+ const stage = makeStage(stageName, [taskName(1), taskName(2)]);+ const at = (selected?: string) => (+ <PlanDetailProvider value={makePage(selected)}>+ <DeployTaskList stage={stage} />+ </PlanDetailProvider>+ );+ const { rerender } = render(at());++ fireEvent.click(screen.getByText(taskName(2)));+ rerender(at(taskName(2)));+ routerMocks.push.mockClear();++ // Browser Back removes the task selection while preserving the kept-alive+ // card state. The old local focus must not push the task path again.+ rerender(at());+ expect(routerMocks.push).not.toHaveBeenCalled();+ });+test("forward-navigation to a self-opened task still deep-links (scrolls)", () => {const stage = makeStage(stageName, [taskName(1), taskName(2)]);const at = (selected?: string) => (diff --git a/frontend/src/routes/project/plan-detail/components/deploy/DeployTaskList.tsx b/frontend/src/routes/project/plan-detail/components/deploy/DeployTaskList.tsxindex 401710dc7f..a8a6ebc895 100644--- a/frontend/src/routes/project/plan-detail/components/deploy/DeployTaskList.tsx+++ b/frontend/src/routes/project/plan-detail/components/deploy/DeployTaskList.tsx@@ -1,6 +1,7 @@-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { router } from "@/app/router";+import { buildTaskDetailRoute } from "@/app/router/routeHelpers";import { Button } from "@/components/ui/button";import { useLatestRef } from "@/hooks/useLatestRef";import { useOnKeyChange } from "@/hooks/useOnKeyChange";@@ -10,7 +11,6 @@ import {Task_Status,type TaskRun,} from "@/types/proto-es/v1/rollout_service_pb";-import { extractStageUID, extractTaskUID } from "@/utils/v1/issue/rollout";import { usePlanDetailContext } from "../../shell/PlanDetailContext";import { DeployTaskItem } from "./DeployTaskItem";import { DeployTaskToolbar } from "./DeployTaskToolbar";@@ -30,20 +30,12 @@ const autoExpandTaskName = (tasks: Task[]): string | undefined =>) ?? tasks[0])?.name;-// The shareable ?stageId&taskId= shape for a task.-const deployTaskQuery = (stageName: string, taskName: string) => ({- phase: "deploy",- stageId: extractStageUID(stageName),- taskId: extractTaskUID(taskName),-});-const initialExpandedNames = (tasks: Task[],selectedTaskName?: string): Set<string> => {- // An explicit ?taskId= selection is the user's focus — open only that task.- // (Matches focusedTaskName's selection-wins logic; opening the auto pick too- // would leave two unrelated cards expanded on reload of a deep link.)+ // An explicit task resource selection is the user's focus — open only it;+ // opening the auto pick too would show two unrelated cards on a deep link.if (selectedTaskName &&tasks.some((task) => task.name === selectedTaskName)@@ -81,7 +73,7 @@ export function DeployTaskList({}) {const { t } = useTranslation();const page = usePlanDetailContext();- // Full task resource name resolved from the ?taskId= deep link.+ // Full task resource name resolved from the task resource route.const selectedTaskName = page.selectedTaskName;const filteredTasks = stage.tasks;// The stage object is rebuilt every poll tick, so passing it to the memoized@@ -103,19 +95,9 @@ export function DeployTaskList({const [selectedTaskNames, setSelectedTaskNames] = useState<Set<string>>(new Set());- // The focused task of this stage — the last card the user opened, defaulting- // to the auto-expand pick or an incoming deep link. It is mirrored into- // ?stageId&taskId= while this stage is active (the effect below), so the- // address bar is a shareable link to this stage + task, and switching back to- // a visited stage restores it.- const [focusedTaskName, setFocusedTaskName] = useState<string | undefined>(- () =>- (isTaskInStage(selectedTaskName) ? selectedTaskName : undefined) ??- autoExpandTaskName(filteredTasks)- );// A card scrolls into view only for an EXTERNAL arrival (a shared link or- // back/forward), never for a ?taskId= this list wrote itself. The mirror- // effect records the value it writes here, and the route-settle handler below+ // back/forward), never for a task route this list wrote itself. The explicit+ // card-open handler records the value here, and the route-settle handler below// CONSUMES it (one-shot). A persistent marker would misread a later external// navigation back to a previously self-opened task as a self-write and fail// to scroll (BYT-9765).@@ -143,14 +125,6 @@ export function DeployTaskList({initialDisplayedCount(filteredTasks, selectedTaskName));setExpandedTaskNames(initialExpandedNames(filteredTasks, selectedTaskName));- // Reseed the focused task too: a task may have become RUNNING/FAILED while- // this stage was mounted-but-hidden, so the default-open card — and the URL- // mirror that follows it — must reflect the current statuses, not the ones- // captured at the hidden mount (which would write a stale ?taskId=).- setFocusedTaskName(- (isTaskInStage(selectedTaskName) ? selectedTaskName : undefined) ??- autoExpandTaskName(filteredTasks)- );}// When the visible task set changes (a plan edit, a filter change), re-derive@@ -175,14 +149,10 @@ export function DeployTaskList({);return remaining.length === prev.size ? prev : new Set(remaining);});- // Keep focus valid: fall back to the default if the focused task is gone.- setFocusedTaskName((prev) =>- isTaskInStage(prev) ? prev : autoExpandTaskName(filteredTasks)- );});- // When ?taskId= settles to a task in this stage, focus + reveal it. Scroll- // only when it is an external arrival (not a ?taskId= we just wrote) — decided+ // When a task route settles in this stage, focus + reveal it. Scroll only+ // when it is an external arrival (not a route we just wrote) — decided// here, once the route has settled, so the transient render during our own// write can't be mistaken for an arrival.useOnKeyChange(selectedTaskName ?? "", () => {@@ -198,48 +168,20 @@ export function DeployTaskList({prev.has(selectedTaskName) ? prev : new Set(prev).add(selectedTaskName));setDisplayedTaskCount((count) => Math.max(count, index + 1));- setFocusedTaskName(selectedTaskName);setArrivalTaskName(wasSelfWrite ? undefined : selectedTaskName);} else {setArrivalTaskName(undefined);}});- // Mirror the focused task into ?stageId&taskId= while this stage is active,- // so the URL is a shareable link. Only the active stage writes (a hidden- // keep-alive list must not hijack the address bar); recording the write in- // pendingSelfWriteRef keeps its own route echo from scrolling the card.const { isEditing, bypassLeaveGuardOnce } = page;- useEffect(() => {- if (- readonly ||- !active ||- !focusedTaskName ||- selectedTaskName === focusedTaskName- ) {- return;- }- pendingSelfWriteRef.current = focusedTaskName;- // This is an internal, same-path query sync (a shareable ?taskId=), not a- // page leave — bypass the unsaved-edits guard so it doesn't cancel the write- // (which would strand pendingSelfWriteRef and desync focus from the URL) or- // pop a spurious discard dialog mid-edit. Only while editing, so the one-shot- // bypass is consumed by this navigation instead of lingering to a real leave.- if (isEditing) {- bypassLeaveGuardOnce();- }- void router.replace({- query: deployTaskQuery(stage.name, focusedTaskName),- });- }, [+ const taskNavigationRef = useLatestRef({active,+ bypassLeaveGuardOnce,+ isEditing,readonly,- focusedTaskName,selectedTaskName,- stage.name,- isEditing,- bypassLeaveGuardOnce,- ]);+ });const visibleTasks = filteredTasks.slice(0, displayedTaskCount);const hasMoreTasks = filteredTasks.length > displayedTaskCount;@@ -250,21 +192,39 @@ export function DeployTaskList({);// One control per card: toggle it open or closed (local state; keep-alive- // preserves it across stage switches). Opening focuses the task, which the- // effect above mirrors into the URL. Stable identities so the memoized cards- // don't re-render when the list does.- const toggleTask = useCallback((task: Task) => {- const willExpand = !expandedTaskNamesRef.current.has(task.name);- setExpandedTaskNames((prev) => {- const next = new Set(prev);- if (next.has(task.name)) next.delete(task.name);- else next.add(task.name);- return next;- });- if (willExpand) {- setFocusedTaskName(task.name);- }- }, []);+ // preserves it across stage switches). Explicitly opening a task also pushes+ // its resource route. Stable identities so the memoized cards don't re-render+ // when the list does.+ const toggleTask = useCallback(+ (task: Task) => {+ const willExpand = !expandedTaskNamesRef.current.has(task.name);+ setExpandedTaskNames((prev) => {+ const next = new Set(prev);+ if (next.has(task.name)) next.delete(task.name);+ else next.add(task.name);+ return next;+ });+ const navigation = taskNavigationRef.current;+ if (+ willExpand &&+ navigation.active &&+ !navigation.readonly &&+ navigation.selectedTaskName !== task.name+ ) {+ // Only this explicit card-open writes a task route. Expansion state+ // survives keep-alive switches, but cannot rewrite Back/Forward or an+ // explicit stage/phase selection.+ pendingSelfWriteRef.current = task.name;+ if (navigation.isEditing) {+ navigation.bypassLeaveGuardOnce();+ }+ void router.push(buildTaskDetailRoute(task.name), {+ preventScrollReset: true,+ });+ }+ },+ [taskNavigationRef]+ );const toggleSelect = useCallback((task: Task) => {setSelectedTaskNames((prev) => {const next = new Set(prev);diff --git a/frontend/src/routes/project/plan-detail/components/lifecycle/DeployStageActions.test.tsx b/frontend/src/routes/project/plan-detail/components/lifecycle/DeployStageActions.test.tsxnew file mode 100644index 0000000000..5f360f0070--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/lifecycle/DeployStageActions.test.tsx@@ -0,0 +1,119 @@+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, test, vi } from "vitest";+import type { Stage } from "@/types/proto-es/v1/rollout_service_pb";+import type { PlanDetailPageState } from "../../shell/hooks/types";+import { PlanDetailProvider } from "../../shell/PlanDetailContext";+import { RunStageAction } from "./DeployStageActions";++const mocks = vi.hoisted(() => ({+ bypassLeaveGuardOnce: vi.fn(),+ expandPhase: vi.fn(),+ push: vi.fn(),+ refreshState: vi.fn(async () => {}),+ resolve: vi.fn(() => ({ fullPath: "/projects/p/plans/1/rollout/stages/a" })),+}));++vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => undefined },+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("@/app/router", () => ({+ router: {+ currentRoute: {+ value: { fullPath: "/projects/p/plans/1/rollout/stages/b" },+ },+ push: mocks.push,+ resolve: mocks.resolve,+ },+}));++vi.mock("../../../issue-detail/utils/rollout", () => ({+ RUNNABLE_TASK_STATUSES: [],+ canRolloutTasks: () => true,+ preloadRolloutPermissionContext: () => Promise.resolve(),+}));++vi.mock("../../shell/focusPhase", () => ({+ focusPlanPhase: (+ phase: "deploy",+ expandPhase: (phase: "deploy") => void+ ) => expandPhase(phase),+}));++vi.mock("../PlanDetailTaskRolloutActionPanel", () => ({+ PlanDetailTaskRolloutActionPanel: ({+ onConfirm,+ open,+ }: {+ onConfirm?: () => Promise<void> | void;+ open: boolean;+ }) =>+ open ? (+ <button onClick={() => void onConfirm?.()} type="button">+ confirm-run+ </button>+ ) : null,+}));++vi.mock("./useStageTitle", () => ({+ useStageTitle: () => "Stage A",+}));++const stage = {+ name: "projects/p/plans/1/rollout/stages/a",+ environment: "environments/test",+ tasks: [],+} as unknown as Stage;++const makePage = (routeStageId: string): PlanDetailPageState =>+ ({+ bypassLeaveGuardOnce: mocks.bypassLeaveGuardOnce,+ currentUser: { name: "users/[email protected]" },+ expandPhase: mocks.expandPhase,+ isEditing: true,+ project: { name: "projects/p" },+ refreshState: mocks.refreshState,+ routeStageId,+ }) as unknown as PlanDetailPageState;++const confirmRun = async (routeStageId: string) => {+ render(+ <PlanDetailProvider value={makePage(routeStageId)}>+ <RunStageAction stage={stage} />+ </PlanDetailProvider>+ );++ fireEvent.click(await screen.findByRole("button"));+ fireEvent.click(screen.getByRole("button", { name: "confirm-run" }));+ await waitFor(() => expect(mocks.refreshState).toHaveBeenCalledTimes(1));+};++describe("RunStageAction", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ test("bypasses the leave guard before switching an edited page to the run stage", async () => {+ await confirmRun("b");++ expect(mocks.bypassLeaveGuardOnce).toHaveBeenCalledTimes(1);+ expect(mocks.push).toHaveBeenCalledWith(+ {+ name: "workspace.project.plan.detail.rollout.stage",+ params: { projectId: "p", planId: "1", stageId: "a" },+ },+ { preventScrollReset: true }+ );+ expect(mocks.bypassLeaveGuardOnce.mock.invocationCallOrder[0]).toBeLessThan(+ mocks.push.mock.invocationCallOrder[0]+ );+ });++ test("does not arm the leave-guard bypass when the run stage is already selected", async () => {+ await confirmRun("a");++ expect(mocks.bypassLeaveGuardOnce).not.toHaveBeenCalled();+ expect(mocks.push).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/routes/project/plan-detail/components/lifecycle/DeployStageActions.tsx b/frontend/src/routes/project/plan-detail/components/lifecycle/DeployStageActions.tsxindex 217c14b569..3560696ed4 100644--- a/frontend/src/routes/project/plan-detail/components/lifecycle/DeployStageActions.tsx+++ b/frontend/src/routes/project/plan-detail/components/lifecycle/DeployStageActions.tsx@@ -9,6 +9,7 @@ import { Play } from "lucide-react";import { useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import { router } from "@/app/router";+import { buildStageRoute } from "@/app/router/routeHelpers";import { TaskStatusIcon } from "@/components/TaskStatusIcon";import { Button } from "@/components/ui/button";import {@@ -124,7 +125,17 @@ export function RunStageAction({ stage }: { stage: Stage }) {// another stage is currently selected, then bring the phase into view.const stageId = stage.name.split("/").pop();if (stageId && page.routeStageId && page.routeStageId !== stageId) {- void router.push({ query: { phase: "deploy", stageId } });+ const target = buildStageRoute(stage.name);+ if (+ page.isEditing &&+ router.resolve(target).fullPath !==+ router.currentRoute.value.fullPath+ ) {+ page.bypassLeaveGuardOnce();+ }+ void router.push(target, {+ preventScrollReset: true,+ });}focusPlanPhase("deploy", page.expandPhase);}}diff --git a/frontend/src/routes/project/plan-detail/shell/hooks/useCanonicalPlanDetailRoute.test.tsx b/frontend/src/routes/project/plan-detail/shell/hooks/useCanonicalPlanDetailRoute.test.tsxnew file mode 100644index 0000000000..3a780ddd75--- /dev/null+++ b/frontend/src/routes/project/plan-detail/shell/hooks/useCanonicalPlanDetailRoute.test.tsx@@ -0,0 +1,502 @@+import { renderHook, waitFor } from "@testing-library/react";+import { beforeEach, describe, expect, test, vi } from "vitest";+import {+ PROJECT_V1_ROUTE_PLAN_DETAIL,+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,+ PROJECT_V1_ROUTE_PLAN_ROLLOUT,+ PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE,+ PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+} from "@/app/router/handles";+import type { PlanDetailPageSnapshot } from "./types";++const mocks = vi.hoisted(() => ({ replace: vi.fn() }));++vi.mock("@/app/router", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/app/router")>()),+ router: { replace: mocks.replace },+}));++import { useCanonicalPlanDetailRoute } from "./useCanonicalPlanDetailRoute";++const rolloutName = "projects/p/plans/1/rollout";+const snapshot = (options?: {+ hasRollout?: boolean;+ isCreating?: boolean;+ pageKey?: string;+ ready?: boolean;+ specs?: string[];+ rollout?: boolean;+}): PlanDetailPageSnapshot =>+ ({+ projectId: "p",+ planId: "1",+ pageKey: options?.pageKey ?? "p/1",+ isCreating: options?.isCreating ?? false,+ ready: options?.ready ?? true,+ plan: {+ name: "projects/p/plans/1",+ hasRollout: options?.hasRollout ?? options?.rollout ?? true,+ specs: (options?.specs ?? ["spec-1"]).map((id) => ({ id })),+ planCheckRunStatusCount: {},+ },+ rollout:+ options?.rollout === false+ ? undefined+ : {+ name: rolloutName,+ stages: [+ {+ name: `${rolloutName}/stages/a`,+ tasks: [{ name: `${rolloutName}/stages/a/tasks/t1` }],+ },+ {+ name: `${rolloutName}/stages/b`,+ tasks: [{ name: `${rolloutName}/stages/b/tasks/t2` }],+ },+ ],+ },+ }) as unknown as PlanDetailPageSnapshot;++const renderCanonical = (+ overrides: Partial<Parameters<typeof useCanonicalPlanDetailRoute>[0]>+) =>+ renderHook(() =>+ useCanonicalPlanDetailRoute({+ projectId: "p",+ planId: "1",+ routeName: PROJECT_V1_ROUTE_PLAN_DETAIL,+ routeQuery: {},+ snapshot: snapshot(),+ isEditing: false,+ bypassLeaveGuardOnce: vi.fn(),+ ...overrides,+ })+ );++beforeEach(() => {+ mocks.replace.mockReset();+});++describe("useCanonicalPlanDetailRoute", () => {+ test("does not canonicalize a plan-creation resource URL", async () => {+ renderCanonical({+ planId: "create",+ routeName: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,+ routeQuery: {+ template: "bb.plan.change-database",+ databaseList: "databases/db1",+ },+ specId: "placeholder",+ snapshot: snapshot({ isCreating: true, pageKey: "p/create" }),+ });++ await waitFor(() => expect(mocks.replace).not.toHaveBeenCalled());+ });++ test("does not validate a new plan route against the previous plan snapshot", async () => {+ renderCanonical({+ planId: "2",+ routeName: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ stageId: "a",+ taskId: "t1",+ snapshot: snapshot(),+ });++ await waitFor(() => expect(mocks.replace).not.toHaveBeenCalled());+ });++ test("removes contradictory selection queries from a spec resource", async () => {+ renderCanonical({+ routeName: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,+ routeQuery: { phase: "deploy", stageId: "a", line: "42" },+ routeHash: "#result-7",+ specId: "spec-1",+ });++ await waitFor(() =>+ expect(mocks.replace).toHaveBeenCalledWith(+ {+ name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,+ params: { projectId: "p", planId: "1", specId: "spec-1" },+ query: { line: "42" },+ hash: "#result-7",+ },+ { preventScrollReset: true }+ )+ );+ });++ test("removes phase queries from the specs collection resource", async () => {+ renderCanonical({+ routeName: PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,+ routeQuery: { phase: "review", foo: "bar" },+ });++ await waitFor(() =>+ expect(mocks.replace).toHaveBeenCalledWith(+ {+ name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,+ params: { projectId: "p", planId: "1" },+ query: { foo: "bar" },+ },+ { preventScrollReset: true }+ )+ );+ });++ test("removes selectors from a task resource without losing task-run state", async () => {+ renderCanonical({+ routeName: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ routeQuery: {+ phase: "review",+ specId: "spec-1",+ stageId: "stale",+ taskId: "stale",+ taskRunId: "run-7",+ },+ routeHash: "#log",+ stageId: "b",+ taskId: "t2",+ });++ await waitFor(() =>+ expect(mocks.replace).toHaveBeenCalledWith(+ {+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ params: {+ projectId: "p",+ planId: "1",+ stageId: "b",+ taskId: "t2",+ },+ query: { taskRunId: "run-7" },+ hash: "#log",+ },+ { preventScrollReset: true }+ )+ );+ });++ test("accepts a valid legacy phase on the plan root", async () => {+ renderCanonical({+ routeQuery: { phase: "review" },+ });++ await waitFor(() => expect(mocks.replace).not.toHaveBeenCalled());+ });++ test("upgrades legacy stage and task queries to a task resource", async () => {+ renderCanonical({+ routeQuery: { phase: "deploy", stageId: "a", taskId: "t1" },+ });++ await waitFor(() =>+ expect(mocks.replace).toHaveBeenCalledWith(+ {+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ params: {+ projectId: "p",+ planId: "1",+ stageId: "a",+ taskId: "t1",+ },+ query: {},+ },+ { preventScrollReset: true }+ )+ );+ });++ test("waits for validation and canonicalizes a legacy task once", async () => {+ const { rerender } = renderHook(+ ({ currentSnapshot }: { currentSnapshot: PlanDetailPageSnapshot }) =>+ useCanonicalPlanDetailRoute({+ projectId: "p",+ planId: "1",+ routeName: PROJECT_V1_ROUTE_PLAN_DETAIL,+ routeQuery: { stageId: "a", taskId: "t2" },+ snapshot: currentSnapshot,+ isEditing: false,+ bypassLeaveGuardOnce: vi.fn(),+ }),+ { initialProps: { currentSnapshot: snapshot({ ready: false }) } }+ );++ expect(mocks.replace).not.toHaveBeenCalled();++ rerender({ currentSnapshot: snapshot() });++ await waitFor(() => expect(mocks.replace).toHaveBeenCalledTimes(1));+ expect(mocks.replace).toHaveBeenCalledWith(+ {+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ params: {+ projectId: "p",+ planId: "1",+ stageId: "b",+ taskId: "t2",+ },+ query: {},+ },+ { preventScrollReset: true }+ );+ });++ test("upgrades a legacy spec query to a spec resource", async () => {+ renderCanonical({+ routeQuery: { phase: "changes", specId: "spec-1", line: "8" },+ });++ await waitFor(() =>+ expect(mocks.replace).toHaveBeenCalledWith(+ {+ name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,+ params: { projectId: "p", planId: "1", specId: "spec-1" },+ query: { line: "8" },+ },+ { preventScrollReset: true }+ )+ );+ });++ test("gives a legacy spec selector precedence over stage and task", async () => {+ renderCanonical({+ routeQuery: {+ specId: "spec-1",+ stageId: "a",+ taskId: "t1",+ line: "8",+ },+ });++ await waitFor(() =>+ expect(mocks.replace).toHaveBeenCalledWith(+ {+ name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,+ params: { projectId: "p", planId: "1", specId: "spec-1" },+ query: { line: "8" },+ },+ { preventScrollReset: true }+ )+ );+ });++ test("uses a task's actual owner when a legacy task has no stage", async () => {+ renderCanonical({+ routeQuery: { taskId: "t2", taskRunId: "run-7" },+ });++ await waitFor(() =>+ expect(mocks.replace).toHaveBeenCalledWith(+ {+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ params: {+ projectId: "p",+ planId: "1",+ stageId: "b",+ taskId: "t2",+ },+ query: { taskRunId: "run-7" },+ },+ { preventScrollReset: true }+ )+ );+ });++ test("falls back from an unknown legacy task to its valid stage", async () => {+ renderCanonical({+ routeQuery: { stageId: "a", taskId: "missing" },+ });++ await waitFor(() =>+ expect(mocks.replace).toHaveBeenCalledWith(+ {+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE,+ params: { projectId: "p", planId: "1", stageId: "a" },+ query: {},+ },+ { preventScrollReset: true }+ )+ );+ });++ test("keeps a committed rollout URL while rollout data is still pending", async () => {+ renderCanonical({+ routeName: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ stageId: "a",+ taskId: "t1",+ snapshot: snapshot({ hasRollout: true, rollout: false }),+ });++ await waitFor(() => expect(mocks.replace).not.toHaveBeenCalled());+ });++ test("keeps legacy rollout selectors until an expected rollout is visible", async () => {+ renderCanonical({+ routeQuery: { stageId: "a", taskId: "t1" },+ snapshot: snapshot({ hasRollout: true, rollout: false }),+ });++ await waitFor(() => expect(mocks.replace).not.toHaveBeenCalled());+ });++ test("corrects a task path whose task belongs to another stage", async () => {+ renderCanonical({+ routeName: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ routeHash: "#log",+ routeQuery: { taskRunId: "run-7" },+ stageId: "a",+ taskId: "t2",+ });++ await waitFor(() =>+ expect(mocks.replace).toHaveBeenCalledWith(+ {+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ params: {+ projectId: "p",+ planId: "1",+ stageId: "b",+ taskId: "t2",+ },+ query: { taskRunId: "run-7" },+ hash: "#log",+ },+ { preventScrollReset: true }+ )+ );+ });++ test("falls back from an unknown task and stage to the rollout", async () => {+ renderCanonical({+ routeName: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ stageId: "missing",+ taskId: "missing",+ });++ await waitFor(() =>+ expect(mocks.replace).toHaveBeenCalledWith(+ {+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT,+ params: { projectId: "p", planId: "1" },+ },+ { preventScrollReset: true }+ )+ );+ });++ test("falls back from an unknown task to its valid stage", async () => {+ renderCanonical({+ routeName: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ stageId: "a",+ taskId: "missing",+ });++ await waitFor(() =>+ expect(mocks.replace).toHaveBeenCalledWith(+ {+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE,+ params: { projectId: "p", planId: "1", stageId: "a" },+ },+ { preventScrollReset: true }+ )+ );+ });++ test("falls back from an unknown stage to the rollout", async () => {+ renderCanonical({+ routeName: PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE,+ stageId: "missing",+ });++ await waitFor(() =>+ expect(mocks.replace).toHaveBeenCalledWith(+ {+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT,+ params: { projectId: "p", planId: "1" },+ },+ { preventScrollReset: true }+ )+ );+ });++ test("falls back from resources that do not exist yet to the plan root", async () => {+ renderCanonical({+ routeName: PROJECT_V1_ROUTE_PLAN_ROLLOUT,+ snapshot: snapshot({ rollout: false }),+ });++ await waitFor(() =>+ expect(mocks.replace).toHaveBeenCalledWith(+ {+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,+ params: { projectId: "p", planId: "1" },+ query: {},+ },+ { preventScrollReset: true }+ )+ );+ });++ test("falls back from an unknown spec to the plan root", async () => {+ renderCanonical({+ routeName: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,+ specId: "missing",+ snapshot: snapshot({ specs: ["spec-1"] }),+ });++ await waitFor(() =>+ expect(mocks.replace).toHaveBeenCalledWith(+ {+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,+ params: { projectId: "p", planId: "1" },+ query: {},+ },+ { preventScrollReset: true }+ )+ );+ });++ test("waits for the snapshot before rejecting an unknown spec path", async () => {+ const { rerender } = renderHook(+ ({ currentSnapshot }: { currentSnapshot: PlanDetailPageSnapshot }) =>+ useCanonicalPlanDetailRoute({+ projectId: "p",+ planId: "1",+ routeName: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,+ routeQuery: {},+ specId: "missing",+ snapshot: currentSnapshot,+ isEditing: false,+ bypassLeaveGuardOnce: vi.fn(),+ }),+ { initialProps: { currentSnapshot: snapshot({ ready: false }) } }+ );++ expect(mocks.replace).not.toHaveBeenCalled();++ rerender({+ currentSnapshot: snapshot({ ready: true, specs: ["spec-1"] }),+ });++ await waitFor(() => expect(mocks.replace).toHaveBeenCalledTimes(1));+ });++ test("bypasses the leave guard exactly once for a canonical replacement", async () => {+ const bypassLeaveGuardOnce = vi.fn();+ renderCanonical({+ isEditing: true,+ bypassLeaveGuardOnce,+ routeName: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,+ routeQuery: { phase: "deploy" },+ specId: "spec-1",+ });++ await waitFor(() => expect(mocks.replace).toHaveBeenCalledTimes(1));+ expect(bypassLeaveGuardOnce).toHaveBeenCalledTimes(1);+ expect(bypassLeaveGuardOnce.mock.invocationCallOrder[0]).toBeLessThan(+ mocks.replace.mock.invocationCallOrder[0]+ );+ });+});diff --git a/frontend/src/routes/project/plan-detail/shell/hooks/useCanonicalPlanDetailRoute.ts b/frontend/src/routes/project/plan-detail/shell/hooks/useCanonicalPlanDetailRoute.tsnew file mode 100644index 0000000000..64ac6ee524--- /dev/null+++ b/frontend/src/routes/project/plan-detail/shell/hooks/useCanonicalPlanDetailRoute.ts@@ -0,0 +1,293 @@+import { useEffect } from "react";+import { type RouteTarget, router } from "@/app/router";+import {+ getRouteQueryString,+ isPlanDetailPhase,+ isPlanDetailResourceRoute,+ PROJECT_V1_ROUTE_PLAN_DETAIL,+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,+ PROJECT_V1_ROUTE_PLAN_ROLLOUT,+ PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE,+ PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+} from "@/app/router/handles";+import {+ PLAN_DETAIL_SELECTION_QUERY_KEYS,+ stripPlanDetailSelectionQuery,+} from "@/app/router/planDetailRouteQuery";+import {+ buildPlanDeployRoute,+ buildPlanRolloutRoute,+} from "@/app/router/routeHelpers";+import { extractStageUID, extractTaskUID } from "@/utils/v1/issue/rollout";+import { isRolloutExpected } from "../../utils/phaseSummary";+import type { PlanDetailPageSnapshot } from "./types";++export function useCanonicalPlanDetailRoute(params: {+ projectId: string;+ planId: string;+ routeHash?: string;+ routeName?: string;+ routeQuery: Record<string, unknown>;+ specId?: string;+ stageId?: string;+ taskId?: string;+ snapshot: PlanDetailPageSnapshot;+ isEditing: boolean;+ bypassLeaveGuardOnce: () => void;+}) {+ useEffect(() => {+ const pageKey = `${params.projectId}/${params.planId}`;+ if (+ params.snapshot.pageKey !== pageKey ||+ params.snapshot.isCreating ||+ params.planId.toLowerCase() === "create"+ ) {+ return;+ }+ const replace = (target: RouteTarget) => {+ if (params.isEditing) params.bypassLeaveGuardOnce();+ void router.replace(+ typeof target === "string" || !params.routeHash+ ? target+ : { ...target, hash: params.routeHash },+ { preventScrollReset: true }+ );+ };+ const base = { projectId: params.projectId, planId: params.planId };+ const cleanQuery = stripPlanDetailSelectionQuery(params.routeQuery);+ const hasSelectionQuery = Object.keys(params.routeQuery).some((key) =>+ PLAN_DETAIL_SELECTION_QUERY_KEYS.has(key)+ );++ // Resource paths own the selection. Remove contradictory or legacy+ // selection queries without adding a history entry.+ if (isPlanDetailResourceRoute(params.routeName) && hasSelectionQuery) {+ const target: RouteTarget =+ params.routeName === PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS+ ? {+ name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,+ params: base,+ query: cleanQuery,+ }+ : params.routeName === PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL+ ? {+ name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,+ params: { ...base, specId: params.specId },+ query: cleanQuery,+ }+ : params.routeName === PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK+ ? {+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ params: {+ ...base,+ stageId: params.stageId,+ taskId: params.taskId,+ },+ query: cleanQuery,+ }+ : params.routeName === PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE+ ? {+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE,+ params: { ...base, stageId: params.stageId },+ query: cleanQuery,+ }+ : {+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT,+ params: base,+ query: cleanQuery,+ };+ replace(target);+ return;+ }++ // Query-only resource selectors are old bookmarks. Wait for the snapshot,+ // validate once, then replace directly with the final canonical resource.+ // Eagerly trusting a stale stage would produce an intermediate wrong path+ // followed by a second correction after the rollout loads.+ if (params.routeName === PROJECT_V1_ROUTE_PLAN_DETAIL) {+ const querySpecId = getRouteQueryString(+ params.routeQuery.specId as never+ );+ const queryStageId = getRouteQueryString(+ params.routeQuery.stageId as never+ );+ const queryTaskId = getRouteQueryString(+ params.routeQuery.taskId as never+ );+ if (querySpecId || queryStageId || queryTaskId) {+ if (!params.snapshot.ready) return;++ if (querySpecId) {+ const specExists = params.snapshot.plan.specs.some(+ (spec) => spec.id === querySpecId+ );+ replace({+ name: specExists+ ? PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL+ : PROJECT_V1_ROUTE_PLAN_DETAIL,+ params: specExists ? { ...base, specId: querySpecId } : base,+ query: cleanQuery,+ });+ return;+ }++ const rollout = params.snapshot.rollout;+ if (!rollout) {+ if (!isRolloutExpected(params.snapshot)) {+ replace({+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,+ params: base,+ query: cleanQuery,+ });+ }+ return;+ }++ const queryStage = queryStageId+ ? rollout.stages.find(+ (stage) => extractStageUID(stage.name) === queryStageId+ )+ : undefined;+ if (queryTaskId) {+ const taskOwner = rollout.stages.find((stage) =>+ stage.tasks.some(+ (task) => extractTaskUID(task.name) === queryTaskId+ )+ );+ if (taskOwner) {+ replace({+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ params: {+ ...base,+ stageId: extractStageUID(taskOwner.name),+ taskId: queryTaskId,+ },+ query: cleanQuery,+ });+ return;+ }+ }++ if (queryStage) {+ replace({+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE,+ params: { ...base, stageId: queryStageId },+ query: cleanQuery,+ });+ return;+ }++ replace({+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT,+ params: base,+ query: cleanQuery,+ });+ return;+ }+ const phase = params.routeQuery.phase;+ if (phase !== undefined && !isPlanDetailPhase(phase)) {+ replace({+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,+ params: base,+ query: cleanQuery,+ });+ return;+ }+ }++ if (!params.snapshot.ready) return;++ if (+ params.routeName === PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL &&+ params.specId &&+ !params.snapshot.plan.specs.some((spec) => spec.id === params.specId)+ ) {+ replace({+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,+ params: base,+ query: cleanQuery,+ });+ return;+ }++ if (+ (params.routeName === PROJECT_V1_ROUTE_PLAN_ROLLOUT ||+ params.routeName === PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE ||+ params.routeName === PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK) &&+ !params.snapshot.rollout+ ) {+ if (!isRolloutExpected(params.snapshot)) {+ replace({+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,+ params: base,+ query: cleanQuery,+ });+ }+ return;+ }++ const rollout = params.snapshot.rollout;+ if (!rollout) return;+ const stage = params.stageId+ ? rollout.stages.find(+ (item) => extractStageUID(item.name) === params.stageId+ )+ : undefined;++ if (params.routeName === PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE && !stage) {+ replace(buildPlanRolloutRoute(params.projectId, params.planId));+ return;+ }++ if (params.routeName === PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK) {+ const taskOwner = params.taskId+ ? rollout.stages.find((item) =>+ item.tasks.some(+ (task) => extractTaskUID(task.name) === params.taskId+ )+ )+ : undefined;+ if (!taskOwner) {+ replace(+ stage+ ? buildPlanDeployRoute({+ ...base,+ stageId: extractStageUID(stage.name),+ })+ : buildPlanRolloutRoute(params.projectId, params.planId)+ );+ return;+ }+ const canonicalStageId = extractStageUID(taskOwner.name);+ if (canonicalStageId !== params.stageId) {+ replace({+ name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ params: {+ ...base,+ stageId: canonicalStageId,+ taskId: params.taskId,+ },+ query: cleanQuery,+ });+ }+ }+ }, [+ params.bypassLeaveGuardOnce,+ params.isEditing,+ params.planId,+ params.projectId,+ params.routeHash,+ params.routeName,+ params.routeQuery,+ params.snapshot.isCreating,+ params.snapshot.issue,+ params.snapshot.pageKey,+ params.snapshot.plan,+ params.snapshot.ready,+ params.snapshot.rollout,+ params.specId,+ params.stageId,+ params.taskId,+ ]);+}diff --git a/frontend/src/routes/project/plan-detail/shell/hooks/useDerivedPlanState.ts b/frontend/src/routes/project/plan-detail/shell/hooks/useDerivedPlanState.tsindex bcaf417ae5..1d55dff282 100644--- a/frontend/src/routes/project/plan-detail/shell/hooks/useDerivedPlanState.ts+++ b/frontend/src/routes/project/plan-detail/shell/hooks/useDerivedPlanState.ts@@ -52,6 +52,9 @@ export function useDerivedPlanState(params: {if (!routeTaskId || !snapshot.rollout) {return undefined;}+ // Route canonicalization corrects a stale/mismatched stage. Resolve the+ // task globally for this render so selection never flashes to a default+ // while that replace settles.for (const stage of snapshot.rollout.stages) {const task = stage.tasks.find((item) =>item.name.endsWith(`/${routeTaskId}`)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.tsxindex 9a24366842..f830597dd6 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@@ -13,7 +13,7 @@ import {TaskRunSchema,} from "@/types/proto-es/v1/rollout_service_pb";import { UserSchema } from "@/types/proto-es/v1/user_service_pb";-import type { PlanDetailPageSnapshot } from "./types";+import type { PlanDetailPageSnapshot, PlanDetailPhase } from "./types";const mocks = vi.hoisted(() => ({fetchPlanSnapshot: vi.fn(),@@ -84,7 +84,16 @@ const buildSnapshotPatch = ({creator: "users/[email protected]",hasRollout: false,state: State.ACTIVE,- specs: [{ id: "spec-1" }, { id: "spec-2" }],+ specs: [+ {+ id: "spec-1",+ config: { case: "changeDatabaseConfig", value: { targets: [] } },+ },+ {+ id: "spec-2",+ config: { case: "changeDatabaseConfig", value: { targets: [] } },+ },+ ],},issue,rollout,@@ -106,48 +115,52 @@ describe("usePlanDetailPage", () => {vi.restoreAllMocks();});- test("defaults to only the changes phase on the specs route", async () => {+ test("defaults to only the deploy phase on the deploy route query", async () => {const { result } = renderHook(() =>usePlanDetailPage({projectId: "foo",- planId: "create",- routeName: "workspace.project.plan.detail.specs",+ planId: "plan-1",+ routeQuery: { phase: "deploy" },}),{ wrapper });await waitFor(() => expect(result.current.ready).toBe(true));- expect(result.current.activePhases.has("changes")).toBe(true);+ expect(result.current.activePhases.has("changes")).toBe(false);expect(result.current.activePhases.has("review")).toBe(false);- expect(result.current.activePhases.has("deploy")).toBe(false);+ expect(result.current.activePhases.has("deploy")).toBe(true);- act(() => result.current.togglePhase("changes"));+ act(() => result.current.togglePhase("deploy"));await waitFor(() =>- expect(result.current.activePhases.has("changes")).toBe(false)+ expect(result.current.activePhases.has("deploy")).toBe(false));});- test("defaults to only the deploy phase on the deploy route query", async () => {+ test("keeps the specs collection focused on Changes without a phase query", async () => {+ mocks.fetchPlanSnapshot.mockResolvedValue(+ buildSnapshotPatch({+ planId: "plan-1",+ rollout: {+ name: "projects/foo/plans/plan-1/rollout",+ stages: [],+ } as unknown as PlanDetailPageSnapshot["rollout"],+ })+ );const { result } = renderHook(() =>usePlanDetailPage({projectId: "foo",planId: "plan-1",- routeQuery: { phase: "deploy" },+ routeName: "workspace.project.plan.detail.specs",}),{ wrapper });await waitFor(() => expect(result.current.ready).toBe(true));- expect(result.current.activePhases.has("changes")).toBe(false);- expect(result.current.activePhases.has("review")).toBe(false);- expect(result.current.activePhases.has("deploy")).toBe(true);-- act(() => result.current.togglePhase("deploy"));- await waitFor(() =>- expect(result.current.activePhases.has("deploy")).toBe(false)- );+ expect(result.current.activePhases).toEqual(new Set(["changes"]));+ expect(mocks.routerPush).not.toHaveBeenCalled();+ expect(mocks.routerReplace).not.toHaveBeenCalled();});test("resets focused phase when navigating to another plan with the same route phase", async () => {@@ -179,6 +192,45 @@ describe("usePlanDetailPage", () => {expect(result.current.activePhases.has("deploy")).toBe(true);});+ test("derives a new plan's disclosure from its own snapshot", async () => {+ mocks.fetchPlanSnapshot.mockImplementation(+ async (_projectId: string, planId: string) =>+ planId === "plan-1"+ ? buildSnapshotPatch({+ planId,+ rollout: {+ name: `projects/foo/plans/${planId}/rollout`,+ stages: [],+ } as unknown as PlanDetailPageSnapshot["rollout"],+ })+ : buildSnapshotPatch({+ planId,+ issue: {+ name: "projects/foo/issues/2",+ } as PlanDetailPageSnapshot["issue"],+ })+ );+ const { result, rerender } = renderHook(+ ({ planId }: { planId: string }) =>+ usePlanDetailPage({ projectId: "foo", planId }),+ {+ initialProps: { planId: "plan-1" },+ wrapper,+ }+ );++ await waitFor(() => expect(result.current.ready).toBe(true));+ expect(result.current.activePhases).toEqual(new Set(["deploy"]));++ rerender({ planId: "plan-2" });++ 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"])+ );+ });+test("defaults to the changes and review phases after an issue is created", async () => {mocks.fetchPlanSnapshot.mockResolvedValue(buildSnapshotPatch({@@ -204,38 +256,53 @@ describe("usePlanDetailPage", () => {expect(result.current.activePhases.has("deploy")).toBe(false);});- test("keeps the review section visible for reviewed plans on the specs route", async () => {+ test("defaults to deploy while rollout creation is pending", async () => {mocks.fetchPlanSnapshot.mockResolvedValue(buildSnapshotPatch({issue: {name: "projects/foo/issues/1",+ approvalStatus: ApprovalStatus.APPROVED,+ draft: false,+ status: IssueStatus.OPEN,} as PlanDetailPageSnapshot["issue"],planId: "plan-1",}));+ const readyRenders: Set<PlanDetailPhase>[] = [];const { result } = renderHook(- () =>- usePlanDetailPage({+ () => {+ const page = usePlanDetailPage({projectId: "foo",planId: "plan-1",- routeName: "workspace.project.plan.detail.specs",- }),+ });+ if (page.ready) {+ readyRenders.push(new Set(page.activePhases));+ }+ return page;+ },{ wrapper });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).toEqual(new Set(["deploy"]));+ expect(readyRenders[0]).toEqual(new Set(["deploy"]));+ expect(mocks.routerPush).not.toHaveBeenCalled();+ expect(mocks.routerReplace).not.toHaveBeenCalled();});- test("focuses the deploy phase on the specs route for rollout plans", async () => {+ test("keeps an explicit review phase on a reviewed rollout plan", async () => {mocks.fetchPlanSnapshot.mockResolvedValue(buildSnapshotPatch({+ issue: {+ name: "projects/foo/issues/1",+ approvalStatus: ApprovalStatus.APPROVED,+ draft: false,+ status: IssueStatus.DONE,+ } as PlanDetailPageSnapshot["issue"],planId: "plan-1",rollout: {- name: "projects/foo/rollouts/1",+ name: "projects/foo/plans/plan-1/rollout",stages: [],} as unknown as PlanDetailPageSnapshot["rollout"],})@@ -246,18 +313,20 @@ describe("usePlanDetailPage", () => {usePlanDetailPage({projectId: "foo",planId: "plan-1",- routeName: "workspace.project.plan.detail.specs",+ routeQuery: { phase: "review" },}),{ wrapper });await waitFor(() => expect(result.current.ready).toBe(true));- expect(result.current.activePhases.has("changes")).toBe(false);- expect(result.current.activePhases.has("review")).toBe(false);- expect(result.current.activePhases.has("deploy")).toBe(true);+ expect(result.current.activePhases).toEqual(+ new Set(["changes", "review"])+ );+ expect(mocks.routerPush).not.toHaveBeenCalled();+ expect(mocks.routerReplace).not.toHaveBeenCalled();});- test("focuses the deploy phase on the spec-detail route for reviewed rollout plans", async () => {+ test("lets a spec resource override a reviewed rollout plan's default", async () => {mocks.fetchPlanSnapshot.mockResolvedValue(buildSnapshotPatch({issue: {@@ -283,9 +352,9 @@ describe("usePlanDetailPage", () => {);await waitFor(() => expect(result.current.ready).toBe(true));- expect(result.current.activePhases.has("changes")).toBe(false);+ expect(result.current.activePhases.has("changes")).toBe(true);expect(result.current.activePhases.has("review")).toBe(false);- expect(result.current.activePhases.has("deploy")).toBe(true);+ expect(result.current.activePhases.has("deploy")).toBe(false);});test("has review default phases on the first ready render", async () => {@@ -351,7 +420,7 @@ describe("usePlanDetailPage", () => {expect(readyRenders[0].has("deploy")).toBe(true);});- test("does not refetch the page snapshot when only the route spec changes", async () => {+ test("reveals a new spec without refetching the page snapshot", async () => {const { result, rerender } = renderHook(({ specId }: { specId: string }) =>usePlanDetailPage({@@ -371,12 +440,192 @@ describe("usePlanDetailPage", () => {expect(result.current.activePhases.has("changes")).toBe(true);expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);+ act(() => result.current.togglePhase("changes"));+ expect(result.current.activePhases.has("changes")).toBe(false);+rerender({ specId: "spec-2" });+ // The new spec is a distinct resource selection even though its lifecycle+ // phase is unchanged. Layout synchronization reveals it before rerender+ // returns, without waiting for a post-paint effect.+ expect(result.current.activePhases.has("changes")).toBe(true);+ expect(result.current.pageKey).toBe("foo/plan-1");+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);+ });++ test("reveals a rollout resource before paint after a deploy phase route", async () => {+ mocks.fetchPlanSnapshot.mockResolvedValue(+ buildSnapshotPatch({+ planId: "plan-1",+ rollout: {+ name: "projects/foo/plans/plan-1/rollout",+ stages: [],+ } as unknown as PlanDetailPageSnapshot["rollout"],+ })+ );+ const { result, rerender } = renderHook(+ ({+ routeName,+ routeQuery,+ }: {+ routeName: string;+ routeQuery: Record<string, unknown>;+ }) =>+ usePlanDetailPage({+ projectId: "foo",+ planId: "plan-1",+ routeName,+ routeQuery,+ }),+ {+ initialProps: {+ routeName: "workspace.project.plan.detail",+ routeQuery: { phase: "deploy" } as Record<string, unknown>,+ },+ wrapper,+ }+ );++ await waitFor(() => expect(result.current.ready).toBe(true));+ act(() => result.current.togglePhase("deploy"));+ expect(result.current.activePhases.has("deploy")).toBe(false);++ rerender({+ routeName: "workspace.project.plan.detail.rollout",+ routeQuery: {},+ });++ // Both URLs resolve to Deploy, but the rollout is a new resource arrival.+ // It is visible in the same commit and disclosure sync never writes a URL.+ expect(result.current.activePhases.has("deploy")).toBe(true);+ expect(mocks.routerPush).not.toHaveBeenCalled();+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);+ });++ test("ignores secondary query changes when synchronizing disclosure", async () => {+ const { result, rerender } = renderHook(+ ({ line }: { line: string }) =>+ usePlanDetailPage({+ projectId: "foo",+ planId: "plan-1",+ routeName: "workspace.project.plan.detail.spec.detail",+ routeQuery: { line },+ specId: "spec-1",+ }),+ {+ initialProps: { line: "1" },+ wrapper,+ }+ );++ await waitFor(() => expect(result.current.ready).toBe(true));+ act(() => result.current.togglePhase("changes"));+ expect(result.current.activePhases.has("changes")).toBe(false);++ rerender({ line: "2" });++ expect(result.current.activePhases.has("changes")).toBe(false);+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);+ });++ test("keeps disclosure stable while a legacy stage query canonicalizes", async () => {+ mocks.fetchPlanSnapshot.mockResolvedValue(+ buildSnapshotPatch({+ planId: "plan-1",+ rollout: {+ name: "projects/foo/plans/plan-1/rollout",+ stages: [+ {+ name: "projects/foo/plans/plan-1/rollout/stages/s1",+ tasks: [],+ },+ ],+ } as unknown as PlanDetailPageSnapshot["rollout"],+ })+ );+ const { result, rerender } = renderHook(+ ({+ routeName,+ routeQuery,+ stageId,+ }: {+ routeName: string;+ routeQuery: Record<string, unknown>;+ stageId?: string;+ }) =>+ usePlanDetailPage({+ projectId: "foo",+ planId: "plan-1",+ routeName,+ routeQuery,+ stageId,+ }),+ {+ initialProps: {+ routeName: "workspace.project.plan.detail",+ routeQuery: { stageId: "s1" } as Record<string, unknown>,+ stageId: undefined as string | undefined,+ },+ wrapper,+ }+ );++ await waitFor(() => expect(result.current.ready).toBe(true));+ act(() => result.current.togglePhase("deploy"));+ expect(result.current.activePhases.has("deploy")).toBe(false);++ rerender({+ routeName: "workspace.project.plan.detail.rollout.stage",+ routeQuery: {},+ stageId: "s1",+ });++ // The query bookmark and its canonical path represent one selection, so+ // the replace cannot produce an extra collapse/expand transition.+ expect(result.current.activePhases.has("deploy")).toBe(false);+ expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);+ });++ test("reveals a resource phase without collapsing same-plan disclosure", async () => {+ mocks.fetchPlanSnapshot.mockResolvedValue(+ buildSnapshotPatch({+ planId: "plan-1",+ rollout: {+ name: "projects/foo/plans/plan-1/rollout",+ stages: [],+ } as unknown as PlanDetailPageSnapshot["rollout"],+ })+ );+ const { result, rerender } = renderHook(+ ({ routeName, specId }: { routeName: string; specId?: string }) =>+ usePlanDetailPage({+ projectId: "foo",+ planId: "plan-1",+ routeName,+ specId,+ }),+ {+ initialProps: {+ routeName: "workspace.project.plan.detail.rollout",+ specId: "",+ },+ wrapper,+ }+ );++ await waitFor(() => expect(result.current.ready).toBe(true));+ expect(result.current.activePhases.has("deploy")).toBe(true);+ expect(result.current.activePhases.has("changes")).toBe(false);++ rerender({+ routeName: "workspace.project.plan.detail.spec.detail",+ specId: "spec-1",+ });+await waitFor(() =>expect(result.current.activePhases.has("changes")).toBe(true));- expect(result.current.pageKey).toBe("foo/plan-1");+ expect(result.current.activePhases.has("deploy")).toBe(true);expect(mocks.fetchPlanSnapshot).toHaveBeenCalledTimes(1);});@@ -444,6 +693,89 @@ describe("usePlanDetailPage", () => {expect(result.current.activePhases.has("changes")).toBe(true);});+ test("reveals a rollout once when it materializes on an open plan", async () => {+ const reviewIssue = {+ name: "projects/foo/issues/1",+ status: IssueStatus.OPEN,+ approvalStatus: ApprovalStatus.CHECKING,+ } as PlanDetailPageSnapshot["issue"];+ const reviewPatch = buildSnapshotPatch({+ issue: reviewIssue,+ planId: "plan-1",+ });+ const rolloutPatch = {+ ...reviewPatch,+ issue: {+ ...reviewIssue,+ approvalStatus: ApprovalStatus.APPROVED,+ status: IssueStatus.DONE,+ } as PlanDetailPageSnapshot["issue"],+ plan: { ...reviewPatch.plan, hasRollout: true },+ rollout: {+ name: "projects/foo/plans/plan-1/rollout",+ stages: [],+ } as unknown as PlanDetailPageSnapshot["rollout"],+ };+ mocks.fetchPlanSnapshot+ .mockResolvedValueOnce(reviewPatch)+ .mockResolvedValue(rolloutPatch);++ const readyRenders: {+ activePhases: Set<PlanDetailPhase>;+ hasRollout: boolean;+ }[] = [];+ const { result } = renderHook(+ () => {+ const page = usePlanDetailPage({+ projectId: "foo",+ planId: "plan-1",+ });+ if (page.ready) {+ readyRenders.push({+ activePhases: new Set(page.activePhases),+ hasRollout: !!page.rollout,+ });+ }+ return page;+ },+ { wrapper }+ );++ await waitFor(() => expect(result.current.ready).toBe(true));+ expect(result.current.activePhases).toEqual(+ new Set(["changes", "review"])+ );++ act(() => result.current.togglePhase("review"));+ expect(result.current.activePhases.has("review")).toBe(false);++ await act(async () => {+ await result.current.refreshState();+ });++ expect(result.current.rollout).toBeDefined();+ expect(result.current.activePhases).toEqual(+ new Set(["changes", "deploy"])+ );+ const rolloutRenders = readyRenders.filter((render) => render.hasRollout);+ expect(rolloutRenders.length).toBeGreaterThan(0);+ expect(+ rolloutRenders.every((render) => render.activePhases.has("deploy"))+ ).toBe(true);+ expect(mocks.routerPush).not.toHaveBeenCalled();++ act(() => result.current.togglePhase("deploy"));+ expect(result.current.activePhases.has("deploy")).toBe(false);++ await act(async () => {+ await result.current.refreshState();+ });++ // Later polls must preserve a deliberate collapse after the one-time+ // lifecycle transition has already been consumed.+ expect(result.current.activePhases).toEqual(new Set(["changes"]));+ });+test("a poll returning identical content keeps the page state identity", async () => {// Real proto messages (not cast plain objects): the identity gate only// structurally compares actual messages.diff --git a/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.ts b/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.tsindex 4b3f2e7c21..ad88adb8a4 100644--- a/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.ts+++ b/frontend/src/routes/project/plan-detail/shell/hooks/usePlanDetailPage.ts@@ -8,6 +8,7 @@ import {} from "react";import { useTranslation } from "react-i18next";import {+ isPlanDetailPhase,PLAN_DETAIL_PHASE_CHANGES,PLAN_DETAIL_PHASE_DEPLOY,PLAN_DETAIL_PHASE_REVIEW,@@ -39,9 +40,13 @@ import { isTaskActivelyTransitioning } from "@/utils/v1/issue/rollout";import { invalidateProjectPagedDataCacheIfChanged } from "../../../pagedDataCacheScope";import type { PlanDetailPhase } from "../../shared/stores/types";import { usePlanDetailStoreApi } from "../../shared/stores/usePlanDetailStore";-import { getPlanCheckSummary } from "../../utils/phaseSummary";+import {+ getPlanCheckSummary,+ isRolloutExpected,+} from "../../utils/phaseSummary";import { fetchPlanSnapshot } from "./fetchPlanSnapshot";import type { PlanDetailPageSnapshot, PlanDetailPageState } from "./types";+import { useCanonicalPlanDetailRoute } from "./useCanonicalPlanDetailRoute";import { useDerivedPlanState } from "./useDerivedPlanState";import { useEditingScopes } from "./useEditingScopes";import { useInitialFetch } from "./useInitialFetch";@@ -138,28 +143,21 @@ const getDefaultActivePhases = (phase: PlanDetailPhase): PlanDetailPhase[] => {type PhaseSelection = {routePhase?: PlanDetailPhase;- routeStageId?: string;- routeTaskId?: string;+ routeSelectionKey: string;};-// The phase to focus by default: an explicit URL selection (phase / stage /-// task) wins, otherwise the furthest-progressed phase the plan has reached.+// The phase to focus by default: an explicit URL selection wins — a stage/task+// selection already resolves to an explicit deploy phase in useRouteSelection —+// otherwise the furthest-progressed phase the plan has reached.const getCurrentPhase = (snapshot: PlanDetailPageSnapshot,selection: PhaseSelection): PlanDetailPhase => {- const { routePhase, routeStageId, routeTaskId } = selection;- if (- routePhase === PLAN_DETAIL_PHASE_CHANGES ||- routePhase === PLAN_DETAIL_PHASE_REVIEW ||- routePhase === PLAN_DETAIL_PHASE_DEPLOY- ) {+ const { routePhase } = selection;+ if (isPlanDetailPhase(routePhase)) {return routePhase;}- if (routeStageId || routeTaskId) {- return PLAN_DETAIL_PHASE_DEPLOY;- }- if (snapshot.rollout) {+ if (snapshot.rollout || isRolloutExpected(snapshot)) {return PLAN_DETAIL_PHASE_DEPLOY;}if (snapshot.issue) {@@ -171,15 +169,21 @@ const getCurrentPhase = (export const usePlanDetailPage = ({projectId,planId,+ routeHash,routeName,routeQuery = {},specId,+ stageId,+ taskId,}: {projectId: string;planId: string;+ routeHash?: string;routeName?: string;routeQuery?: Record<string, unknown>;specId?: string;+ stageId?: string;+ taskId?: string;}): PlanDetailPageState => {const { t } = useTranslation();const [snapshot, setSnapshot] = useState<PlanDetailPageSnapshot>(() =>@@ -197,51 +201,66 @@ export const usePlanDetailPage = ({// routeQuery is a fresh object on every router navigation. Stash the latest// value in a ref and depend only on the individual keys we actually consume,// so the init/refresh/poll effects don't churn (and reset isInitializing)- // every time an unrelated query param like ?taskId changes.+ // every time unrelated secondary query state changes.const routeQueryRef = useRef(routeQuery);routeQueryRef.current = routeQuery;- const route = useRouteSelection({ routeQuery, specId });+ const route = useRouteSelection({+ routeName,+ routeQuery,+ specId,+ stageId,+ taskId,+ });const routePhase = route.phase;+ const routeSelectionKey = route.selectionKey;const routeStageId = route.stageId;const routeTaskId = route.taskId;const setActivePhases = phase.setActivePhases;+ const expandPhase = phase.expandPhase;const pageIdentityKey = `${projectId}/${planId}`;+ const snapshotBelongsToRoute = snapshot.pageKey === pageIdentityKey;useEffect(() => {setCreationIssueLabels([]);}, [pageIdentityKey]);- const phaseSelectionRef = useRef<PhaseSelection>({});+ const phaseSelectionRef = useRef<PhaseSelection>({ routeSelectionKey });phaseSelectionRef.current = {routePhase,- routeStageId,- routeTaskId,+ routeSelectionKey,};const syncedDefaultPhaseRef = useRef<| {pageIdentityKey: string;- phase: PlanDetailPhase;+ selectionKey: string;}| undefined>(undefined);const syncDefaultActivePhases = useCallback((nextSnapshot: PlanDetailPageSnapshot) => {+ if (!nextSnapshot.ready || nextSnapshot.pageKey !== pageIdentityKey) {+ return;+ }const nextPhase = getCurrentPhase(nextSnapshot,phaseSelectionRef.current);+ const explicitPhase = phaseSelectionRef.current.routePhase;+ const selectionKey = phaseSelectionRef.current.routeSelectionKey;const synced = syncedDefaultPhaseRef.current;- if (- synced?.pageIdentityKey === pageIdentityKey &&- synced.phase === nextPhase- ) {+ if (synced?.pageIdentityKey !== pageIdentityKey) {+ setActivePhases(getDefaultActivePhases(nextPhase));+ syncedDefaultPhaseRef.current = { pageIdentityKey, selectionKey };return;}- setActivePhases(getDefaultActivePhases(nextPhase));- syncedDefaultPhaseRef.current = {- pageIdentityKey,- phase: nextPhase,- };+ if (synced.selectionKey === selectionKey) return;+ // Same-plan resource navigation only reveals the destination phase. It+ // never collapses phases the user already opened, so Back/Forward and+ // rapid spec/stage/task selection cannot reset disclosure state.+ if (explicitPhase) {+ expandPhase(explicitPhase);+ }+ syncedDefaultPhaseRef.current = { pageIdentityKey, selectionKey };},- [pageIdentityKey, setActivePhases]+ [expandPhase, pageIdentityKey, setActivePhases]);const patchState = useCallback(@@ -276,6 +295,19 @@ export const usePlanDetailPage = ({}));syncDefaultActivePhases(nextSnapshot);+ // Reveal a rollout that materializes while this plan is already open,+ // regardless of which backend gate completed last. Expanding before the+ // snapshot update keeps the old future state visually unchanged, so the+ // first render with rollout data is already expanded without changing+ // selection, URL, scroll, or the user's other disclosure choices.+ if (+ prevSnapshot.ready &&+ prevSnapshot.pageKey === nextSnapshot.pageKey &&+ !prevSnapshot.rollout &&+ nextSnapshot.rollout+ ) {+ expandPhase(PLAN_DETAIL_PHASE_DEPLOY);+ }if (nextSnapshot === prevSnapshot) {// Content-identical (the common quiet poll tick) — no state update,// so nothing under the provider re-renders.@@ -284,7 +316,7 @@ export const usePlanDetailPage = ({latestSnapshotRef.current = nextSnapshot;setSnapshot(nextSnapshot);},- [syncDefaultActivePhases]+ [expandPhase, syncDefaultActivePhases]);// Monotonic fetch sequence: a fetch already in flight when a newer one started@@ -303,11 +335,9 @@ export const usePlanDetailPage = ({// failure doesn't spam the global toast (the initial load is loud).true);- // The page isn't remounted on plan->plan navigation, so a poll started for- // the previous plan can still be in flight after the switch. The seq guard- // doesn't bump on navigation, so also drop the patch when the page identity- // has changed — otherwise the old plan's data would merge onto the new- // plan's snapshot (wrong data under a correct URL, until the next poll).+ // The keyed page provider remounts for normal plan-to-plan navigation. Keep+ // the page-identity check as a defensive hook-level guard for any caller+ // that reuses the hook instance while a request is still in flight.if (seq !== fetchSeqRef.current ||latestSnapshotRef.current.pageKey !== current.pageKey@@ -326,6 +356,9 @@ export const usePlanDetailPage = ({});useEffect(() => {+ if (!snapshotBelongsToRoute) {+ return;+ }if (snapshot.isCreating) {setDocumentTitle(t("plan.new-plan"), snapshot.projectTitle);return;@@ -338,24 +371,35 @@ export const usePlanDetailPage = ({snapshot.plan.title,snapshot.projectTitle,snapshot.ready,+ snapshotBelongsToRoute,t,]);useRedirects({- ready: snapshot.ready,+ ready: snapshotBelongsToRoute && snapshot.ready,plan: snapshot.plan,issue: snapshot.issue,});+ // Reveal a same-plan route destination before the browser paints. A normal+ // effect would commit the previous collapsed state for one frame first.useLayoutEffect(() => {syncDefaultActivePhases(latestSnapshotRef.current);- }, [- pageIdentityKey,- routePhase,- routeStageId,- routeTaskId,- syncDefaultActivePhases,- ]);+ }, [pageIdentityKey, routeSelectionKey, syncDefaultActivePhases]);++ useCanonicalPlanDetailRoute({+ projectId,+ planId,+ routeHash,+ routeName,+ routeQuery,+ specId,+ stageId,+ taskId,+ snapshot,+ isEditing,+ bypassLeaveGuardOnce: editing.bypassLeaveGuardOnce,+ });const { activePollingKey, isPlanDone, pollingMode } = useMemo((): {activePollingKey: string;@@ -371,31 +415,11 @@ export const usePlanDetailPage = ({const hasActivePlanChecks =checks.running > 0 ||(snapshot.plan.planCheckRunStatusCount?.AVAILABLE ?? 0) > 0;- const hasCanceledPlanChecks =- (snapshot.plan.planCheckRunStatusCount?.CANCELED ?? 0) > 0;- // The backend considers an approval template with zero roles approved,- // although its API approval status can still be PENDING. Treat the- // resolved empty flow as passed so we keep polling through rollout- // creation instead of falling back to the idle cadence in that window.- const hasNoApprovalSteps =- snapshot.issue?.approvalTemplate?.flow?.roles.length === 0;- const approvalPassed =- snapshot.issue?.approvalStatus === ApprovalStatus.APPROVED ||- snapshot.issue?.approvalStatus === ApprovalStatus.SKIPPED ||- hasNoApprovalSteps;const approvalChecking =snapshot.issue?.status === IssueStatus.OPEN &&!snapshot.issue.draft &&snapshot.issue.approvalStatus === ApprovalStatus.CHECKING;- const rolloutExpected =- snapshot.plan.hasRollout ||- snapshot.issue?.status === IssueStatus.DONE ||- (snapshot.issue?.status === IssueStatus.OPEN &&- !snapshot.issue.draft &&- approvalPassed &&- !hasActivePlanChecks &&- !hasCanceledPlanChecks &&- checks.error === 0);+ const rolloutExpected = isRolloutExpected(snapshot);// Once every gate passes, rollout creation is asynchronous. Keep polling// at the active cadence through that gap, as well as when either the plan// or issue already proves the rollout committed but its data is missing.@@ -462,7 +486,11 @@ export const usePlanDetailPage = ({// Independent jitter prevents synchronized clients; hidden tabs pause until// they become visible again.const { restart: restartPolling } = usePlanPolling({- enabled: snapshot.ready && !snapshot.isCreating && !isPlanDone,+ enabled:+ snapshotBelongsToRoute &&+ snapshot.ready &&+ !snapshot.isCreating &&+ !isPlanDone,mode: pollingMode,refreshState: fetchState,resetKey: pollingMode === "active" ? activePollingKey : undefined,diff --git a/frontend/src/routes/project/plan-detail/shell/hooks/useRouteSelection.test.tsx b/frontend/src/routes/project/plan-detail/shell/hooks/useRouteSelection.test.tsxnew file mode 100644index 0000000000..5b5b94802f--- /dev/null+++ b/frontend/src/routes/project/plan-detail/shell/hooks/useRouteSelection.test.tsx@@ -0,0 +1,328 @@+import { renderHook, waitFor } from "@testing-library/react";+import type { ReactNode } from "react";+import { describe, expect, test } from "vitest";+import {+ PROJECT_V1_ROUTE_PLAN_DETAIL,+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,+ PROJECT_V1_ROUTE_PLAN_ROLLOUT,+ PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE,+ PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+} from "@/app/router/handles";+import { PlanDetailStoreProvider } from "../../shared/stores/PlanDetailStoreProvider";+import { usePlanDetailStore } from "../../shared/stores/usePlanDetailStore";+import { useRouteSelection } from "./useRouteSelection";++const wrapper = ({ children }: { children: ReactNode }) => (+ <PlanDetailStoreProvider>{children}</PlanDetailStoreProvider>+);++type RouteSelectionParams = Parameters<typeof useRouteSelection>[0];++const renderSelection = (initialProps: RouteSelectionParams) =>+ renderHook(+ (params: RouteSelectionParams) => {+ const route = useRouteSelection(params);+ const routePhase = usePlanDetailStore((state) => state.routePhase);+ const selectedSpecId = usePlanDetailStore(+ (state) => state.selectedSpecId+ );+ const selectedStageId = usePlanDetailStore(+ (state) => state.selectedStageId+ );+ const selectedTaskName = usePlanDetailStore(+ (state) => state.selectedTaskName+ );+ return {+ route,+ store: {+ routePhase,+ selectedSpecId,+ selectedStageId,+ selectedTaskName,+ },+ };+ },+ { initialProps, wrapper }+ );++describe("useRouteSelection", () => {+ test.each([+ {+ expected: {+ phase: "changes",+ selectionKey: "spec:",+ specId: undefined,+ stageId: undefined,+ taskId: undefined,+ },+ name: "spec collection",+ params: {+ routeName: PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,+ routeQuery: {},+ },+ },+ {+ expected: {+ phase: "changes",+ selectionKey: "spec:spec-2",+ specId: "spec-2",+ stageId: undefined,+ taskId: undefined,+ },+ name: "specific spec",+ params: {+ routeName: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,+ routeQuery: {},+ specId: "spec-2",+ },+ },+ {+ expected: {+ phase: "deploy",+ selectionKey: "rollout",+ specId: undefined,+ stageId: undefined,+ taskId: undefined,+ },+ name: "rollout",+ params: {+ routeName: PROJECT_V1_ROUTE_PLAN_ROLLOUT,+ routeQuery: {},+ },+ },+ {+ expected: {+ phase: "deploy",+ selectionKey: "stage:prod",+ specId: undefined,+ stageId: "prod",+ taskId: undefined,+ },+ name: "specific stage",+ params: {+ routeName: PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE,+ routeQuery: {},+ stageId: "prod",+ },+ },+ {+ expected: {+ phase: "deploy",+ selectionKey: "task:42",+ specId: undefined,+ stageId: "prod",+ taskId: "42",+ },+ name: "specific task",+ params: {+ routeName: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ routeQuery: {},+ stageId: "prod",+ taskId: "42",+ },+ },+ ] as const)(+ "derives the owning phase and identity for $name",+ async ({ expected, params }) => {+ const { result } = renderSelection(params);++ expect(result.current.route).toEqual(expected);+ await waitFor(() =>+ expect(result.current.store).toEqual({+ routePhase: expected.phase,+ selectedSpecId: expected.specId,+ selectedStageId: expected.stageId,+ selectedTaskName: expected.taskId,+ })+ );+ }+ );++ test.each(["changes", "review", "deploy"] as const)(+ "accepts the legacy %s phase only on the plan root",+ async (phase) => {+ const { result } = renderSelection({+ routeName: PROJECT_V1_ROUTE_PLAN_DETAIL,+ routeQuery: { phase },+ });++ expect(result.current.route).toEqual({+ phase,+ selectionKey: `plan:${phase}`,+ specId: undefined,+ stageId: undefined,+ taskId: undefined,+ });+ await waitFor(() =>+ expect(result.current.store.routePhase).toBe(phase)+ );+ }+ );++ test("ignores contradictory legacy selectors on a resource path", async () => {+ const { result } = renderSelection({+ routeName: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,+ routeQuery: {+ phase: "deploy",+ specId: "query-spec",+ stageId: "prod",+ taskId: "42",+ },+ specId: "path-spec",+ stageId: "ignored-stage",+ taskId: "ignored-task",+ });++ expect(result.current.route).toEqual({+ phase: "changes",+ selectionKey: "spec:path-spec",+ specId: "path-spec",+ stageId: undefined,+ taskId: undefined,+ });+ await waitFor(() =>+ expect(result.current.store).toEqual({+ routePhase: "changes",+ selectedSpecId: "path-spec",+ selectedStageId: undefined,+ selectedTaskName: undefined,+ })+ );+ });++ test.each([+ {+ expected: {+ phase: "changes",+ selectionKey: "spec:spec-1",+ specId: "spec-1",+ stageId: undefined,+ taskId: undefined,+ },+ name: "spec wins over rollout selectors",+ routeQuery: {+ phase: "review",+ specId: "spec-1",+ stageId: "prod",+ taskId: "42",+ },+ },+ {+ expected: {+ phase: "deploy",+ selectionKey: "task:42",+ specId: undefined,+ stageId: "prod",+ taskId: "42",+ },+ name: "task wins over stage and phase",+ routeQuery: {+ phase: "review",+ stageId: "prod",+ taskId: "42",+ },+ },+ {+ expected: {+ phase: "deploy",+ selectionKey: "task:42",+ specId: undefined,+ stageId: undefined,+ taskId: "42",+ },+ name: "task remains identifiable without a legacy stage",+ routeQuery: { phase: "review", taskId: "42" },+ },+ {+ expected: {+ phase: "deploy",+ selectionKey: "stage:prod",+ specId: undefined,+ stageId: "prod",+ taskId: undefined,+ },+ name: "stage wins over phase",+ routeQuery: { phase: "review", stageId: "prod" },+ },+ ] as const)(+ "applies legacy selector precedence when $name",+ async ({ expected, routeQuery }) => {+ const { result } = renderSelection({+ routeName: PROJECT_V1_ROUTE_PLAN_DETAIL,+ routeQuery,+ });++ expect(result.current.route).toEqual(expected);+ await waitFor(() =>+ expect(result.current.store).toEqual({+ routePhase: expected.phase,+ selectedSpecId: expected.specId,+ selectedStageId: expected.stageId,+ selectedTaskName: expected.taskId,+ })+ );+ }+ );++ test("uses the task identity while canonicalizing its owning stage", async () => {+ const { result, rerender } = renderSelection({+ routeName: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ routeQuery: {},+ stageId: "stale",+ taskId: "42",+ });++ expect(result.current.route.selectionKey).toBe("task:42");++ rerender({+ routeName: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ routeQuery: {},+ stageId: "prod",+ taskId: "42",+ });++ expect(result.current.route.selectionKey).toBe("task:42");+ await waitFor(() =>+ expect(result.current.store).toEqual({+ routePhase: "deploy",+ selectedSpecId: undefined,+ selectedStageId: "prod",+ selectedTaskName: "42",+ })+ );+ });++ test("clears resource selection when returning to the plain plan root", async () => {+ const { result, rerender } = renderSelection({+ routeName: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+ routeQuery: {},+ stageId: "prod",+ taskId: "42",+ });+ await waitFor(() =>+ expect(result.current.store.selectedTaskName).toBe("42")+ );++ rerender({+ routeName: PROJECT_V1_ROUTE_PLAN_DETAIL,+ routeQuery: { activity: "comment-7" },+ });++ expect(result.current.route).toEqual({+ phase: undefined,+ selectionKey: "plan:",+ specId: undefined,+ stageId: undefined,+ taskId: undefined,+ });+ await waitFor(() =>+ expect(result.current.store).toEqual({+ routePhase: undefined,+ selectedSpecId: undefined,+ selectedStageId: undefined,+ selectedTaskName: undefined,+ })+ );+ });+});diff --git a/frontend/src/routes/project/plan-detail/shell/hooks/useRouteSelection.ts b/frontend/src/routes/project/plan-detail/shell/hooks/useRouteSelection.tsindex 3d6a43f87f..f511a5fd77 100644--- a/frontend/src/routes/project/plan-detail/shell/hooks/useRouteSelection.ts+++ b/frontend/src/routes/project/plan-detail/shell/hooks/useRouteSelection.ts@@ -1,28 +1,117 @@import { useEffect } from "react";-import { getRouteQueryString } from "@/app/router/handles";+import {+ getRouteQueryString,+ isPlanDetailPhase,+ isPlanDetailResourceRoute,+ PLAN_DETAIL_PHASE_CHANGES,+ PLAN_DETAIL_PHASE_DEPLOY,+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,+ PROJECT_V1_ROUTE_PLAN_ROLLOUT,+ PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE,+ PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,+} from "@/app/router/handles";import type { PlanDetailPhase } from "../../shared/stores/types";import { usePlanDetailStore } from "../../shared/stores/usePlanDetailStore";export function useRouteSelection(params: {+ routeName?: string;routeQuery: Record<string, unknown>;specId?: string;+ stageId?: string;+ taskId?: string;}) {const setRouteSelection = usePlanDetailStore((s) => s.setRouteSelection);- const phase = getRouteQueryString(params.routeQuery.phase as never) as- | PlanDetailPhase- | undefined;- const stageId = getRouteQueryString(params.routeQuery.stageId as never);- const taskId = getRouteQueryString(params.routeQuery.taskId as never);+ const rawQueryPhase = getRouteQueryString(params.routeQuery.phase as never);+ const queryPhase: PlanDetailPhase | undefined = isPlanDetailPhase(+ rawQueryPhase+ )+ ? rawQueryPhase+ : undefined;+ const isSpecDetailRoute =+ params.routeName === PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL;+ const isSpecsRoute = params.routeName === PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS;+ const isRolloutRoute = params.routeName === PROJECT_V1_ROUTE_PLAN_ROLLOUT;+ const isStageRoute = params.routeName === PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE;+ const isTaskRoute = params.routeName === PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK;++ // A resource path owns the selection completely. Query selectors are a+ // read-only fallback only on the plan route, until canonicalization replaces+ // the old bookmark with its resource path.+ const isResourceRoute = isPlanDetailResourceRoute(params.routeName);+ const querySpecId = isResourceRoute+ ? undefined+ : getRouteQueryString(params.routeQuery.specId as never);+ const queryStageId = isResourceRoute+ ? undefined+ : getRouteQueryString(params.routeQuery.stageId as never);+ const queryTaskId = isResourceRoute+ ? undefined+ : getRouteQueryString(params.routeQuery.taskId as never);++ // The resource this URL selects, in precedence order. Both `phase` and the+ // disclosure identity below derive from this single discriminant, so the+ // spec → task → stage → rollout → plan ladder is written once.+ const kind =+ isSpecsRoute || isSpecDetailRoute || querySpecId+ ? "spec"+ : isTaskRoute || queryTaskId+ ? "task"+ : isStageRoute || queryStageId+ ? "stage"+ : isRolloutRoute+ ? "rollout"+ : "plan";+ // Apply the same precedence to the concrete selection fields. A legacy URL+ // can contain contradictory selectors; while canonicalization replaces it,+ // the store must still expose one coherent resource rather than a spec plus+ // stale stage/task state for an intermediate render.+ const specId =+ kind === "spec"+ ? isSpecDetailRoute+ ? params.specId+ : querySpecId+ : undefined;+ const stageId =+ kind === "stage" || kind === "task"+ ? isStageRoute || isTaskRoute+ ? params.stageId+ : queryStageId+ : undefined;+ const taskId =+ kind === "task" ? (isTaskRoute ? params.taskId : queryTaskId) : undefined;+ const phase =+ kind === "spec"+ ? PLAN_DETAIL_PHASE_CHANGES+ : kind === "plan"+ ? queryPhase+ : PLAN_DETAIL_PHASE_DEPLOY;++ // This semantic identity drives disclosure synchronization. It deliberately+ // excludes secondary state (line, task run, hash) and normalizes legacy query+ // selectors to the same identity as their canonical resource path. A task is+ // plan-unique, so its owning stage is not part of the task identity; correcting+ // a stale stage path must not create a second disclosure transition.+ const selectionKey =+ kind === "spec"+ ? `spec:${specId ?? ""}`+ : kind === "task"+ ? `task:${taskId ?? ""}`+ : kind === "stage"+ ? `stage:${stageId ?? ""}`+ : kind === "rollout"+ ? "rollout"+ : `plan:${phase ?? ""}`;useEffect(() => {setRouteSelection({phase,stageId,taskName: taskId,- specId: params.specId,+ specId,});- }, [setRouteSelection, phase, stageId, taskId, params.specId]);+ }, [setRouteSelection, phase, specId, stageId, taskId]);- return { phase, stageId, taskId };+ return { phase, selectionKey, specId, stageId, taskId };}diff --git a/frontend/src/routes/project/plan-detail/utils/createPlan.test.ts b/frontend/src/routes/project/plan-detail/utils/createPlan.test.tsnew file mode 100644index 0000000000..3671e93b43--- /dev/null+++ b/frontend/src/routes/project/plan-detail/utils/createPlan.test.ts@@ -0,0 +1,31 @@+import { create } from "@bufbuild/protobuf";+import { describe, expect, test } from "vitest";+import { ProjectSchema } from "@/types/proto-es/v1/project_service_pb";+import { createPlanSkeleton } from "./createPlan";++const project = create(ProjectSchema, { name: "projects/p" });++describe("createPlanSkeleton", () => {+ test("creates a change-database spec without a template query", async () => {+ const plan = await createPlanSkeleton(project, {+ databaseList: "projects/p/databases/db",+ });++ expect(plan.specs).toHaveLength(1);+ expect(plan.specs[0].config).toEqual({+ case: "changeDatabaseConfig",+ value: expect.objectContaining({+ targets: ["projects/p/databases/db"],+ }),+ });+ });++ test("ignores the legacy template query", async () => {+ const plan = await createPlanSkeleton(project, {+ template: "bb.plan.change-database",+ databaseList: "projects/p/databases/db",+ });++ expect(plan.specs[0].config.case).toBe("changeDatabaseConfig");+ });+});diff --git a/frontend/src/routes/project/plan-detail/utils/createPlan.ts b/frontend/src/routes/project/plan-detail/utils/createPlan.tsindex 7aa3506082..8fb93a8428 100644--- a/frontend/src/routes/project/plan-detail/utils/createPlan.ts+++ b/frontend/src/routes/project/plan-detail/utils/createPlan.ts@@ -16,8 +16,6 @@ import {setLocalSheetStatement,} from "./localSheet";-type PlanTemplate = "bb.plan.change-database";-type InitialSQL = {sqlMap?: Record<string, string>;sql?: string;@@ -106,13 +104,6 @@ export const createPlanSkeleton = async (project: Project,query: Record<string, string>) => {- const template = query.template as PlanTemplate | undefined;- if (!template || template !== "bb.plan.change-database") {- throw new Error(- "Only change-database plan creation is supported from the plan detail route."- );- }-const databaseList = query.databaseList ?? "";// Guard the empty case: "".split(",") yields [""], which would create a spec// with a single empty-string target.diff --git a/frontend/src/routes/project/plan-detail/utils/phaseSummary.test.ts b/frontend/src/routes/project/plan-detail/utils/phaseSummary.test.tsindex 948bafb01f..6a35a5234a 100644--- a/frontend/src/routes/project/plan-detail/utils/phaseSummary.test.ts+++ b/frontend/src/routes/project/plan-detail/utils/phaseSummary.test.ts@@ -1,5 +1,6 @@import { describe, expect, test } from "vitest";-import type { Issue } from "@/types/proto-es/v1/issue_service_pb";+import { ApprovalStatus, State } from "@/types/proto-es/v1/common_pb";+import { type Issue, IssueStatus } from "@/types/proto-es/v1/issue_service_pb";import type { Plan } from "@/types/proto-es/v1/plan_service_pb";import type { Rollout } from "@/types/proto-es/v1/rollout_service_pb";import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";@@ -7,6 +8,7 @@ import {buildChangesSummary,buildDeploySummary,buildReviewSummary,+ isRolloutExpected,} from "./phaseSummary";const templates: Record<string, string> = {@@ -98,3 +100,214 @@ describe("plan detail phase summaries", () => {expect(buildDeploySummary(rollout, t)).toBe("2/3 tasks");});});++describe("isRolloutExpected", () => {+ const approvedIssue = {+ approvalStatus: ApprovalStatus.APPROVED,+ draft: false,+ status: IssueStatus.OPEN,+ } as unknown as Issue;+ const planWithSpec = (configCase: string) =>+ ({+ planCheckRunStatusCount: { SUCCESS: 1 },+ specs: [{ config: { case: configCase, value: {} } }],+ state: State.ACTIVE,+ }) as unknown as Plan;++ test("expects automatic rollout for an approved change-database plan", () => {+ expect(+ isRolloutExpected({+ issue: approvedIssue,+ plan: planWithSpec("changeDatabaseConfig"),+ })+ ).toBe(true);+ });++ test.each([+ {+ expected: true,+ issue: {+ ...approvedIssue,+ approvalStatus: ApprovalStatus.SKIPPED,+ },+ name: "skipped approval",+ },+ {+ expected: true,+ issue: {+ ...approvedIssue,+ approvalStatus: ApprovalStatus.PENDING,+ approvalTemplate: { flow: { roles: [] } },+ },+ name: "zero approval roles",+ },+ {+ expected: true,+ issue: {+ ...approvedIssue,+ approvalStatus: ApprovalStatus.PENDING,+ status: IssueStatus.DONE,+ },+ name: "completed issue commitment",+ },+ {+ expected: false,+ issue: {+ ...approvedIssue,+ approvalStatus: ApprovalStatus.CHECKING,+ },+ name: "approval finding",+ },+ {+ expected: false,+ issue: {+ ...approvedIssue,+ approvalStatus: ApprovalStatus.PENDING,+ },+ name: "pending approval",+ },+ {+ expected: false,+ issue: {+ ...approvedIssue,+ draft: true,+ },+ name: "draft issue",+ },+ {+ expected: false,+ issue: {+ ...approvedIssue,+ status: IssueStatus.CANCELED,+ },+ name: "canceled issue",+ },+ ])("returns $expected for $name", ({ expected, issue }) => {+ expect(+ isRolloutExpected({+ issue: issue as unknown as Issue,+ plan: planWithSpec("changeDatabaseConfig"),+ })+ ).toBe(expected);+ });++ test.each([+ { expected: true, name: "no checks", statusCount: {} },+ {+ expected: true,+ name: "successful checks",+ statusCount: { SUCCESS: 2 },+ },+ {+ expected: true,+ name: "warning-only checks",+ statusCount: { WARNING: 1 },+ },+ {+ expected: false,+ name: "queued checks",+ statusCount: { AVAILABLE: 1 },+ },+ {+ expected: false,+ name: "running checks",+ statusCount: { RUNNING: 1 },+ },+ {+ expected: false,+ name: "canceled checks",+ statusCount: { CANCELED: 1 },+ },+ {+ expected: false,+ name: "advice errors",+ statusCount: { ERROR: 1 },+ },+ {+ expected: false,+ name: "failed check runs",+ statusCount: { FAILED: 1 },+ },+ ])("returns $expected with $name", ({ expected, statusCount }) => {+ const plan = {+ ...planWithSpec("changeDatabaseConfig"),+ planCheckRunStatusCount: statusCount,+ } as unknown as Plan;++ expect(isRolloutExpected({ issue: approvedIssue, plan })).toBe(expected);+ });++ test.each(["createDatabaseConfig", "exportDataConfig"])(+ "does not expect automatic rollout for %s",+ (configCase) => {+ expect(+ isRolloutExpected({+ issue: approvedIssue,+ plan: planWithSpec(configCase),+ })+ ).toBe(false);+ }+ );++ test("does not expect rollout when only some specs support it", () => {+ const plan = {+ ...planWithSpec("changeDatabaseConfig"),+ specs: [+ { config: { case: "changeDatabaseConfig", value: {} } },+ { config: { case: "exportDataConfig", value: {} } },+ ],+ } as unknown as Plan;++ expect(isRolloutExpected({ issue: approvedIssue, plan })).toBe(false);+ });++ test("does not expect rollout before an issue exists", () => {+ expect(+ isRolloutExpected({+ plan: planWithSpec("changeDatabaseConfig"),+ })+ ).toBe(false);+ });++ test("does not expect automatic rollout for empty or deleted plans", () => {+ const emptyPlan = {+ specs: [],+ state: State.ACTIVE,+ } as unknown as Plan;+ const deletedPlan = {+ ...planWithSpec("changeDatabaseConfig"),+ state: State.DELETED,+ } as unknown as Plan;++ expect(isRolloutExpected({ issue: approvedIssue, plan: emptyPlan })).toBe(+ false+ );+ expect(isRolloutExpected({ issue: approvedIssue, plan: deletedPlan })).toBe(+ false+ );+ });++ test("does not infer a rollout from a done unsupported issue", () => {+ const doneIssue = {+ ...approvedIssue,+ status: IssueStatus.DONE,+ } as unknown as Issue;++ expect(+ isRolloutExpected({+ issue: doneIssue,+ plan: planWithSpec("exportDataConfig"),+ })+ ).toBe(false);+ });++ test("keeps polling after rollout commitment regardless of eligibility", () => {+ const plan = {+ ...planWithSpec("exportDataConfig"),+ hasRollout: true,+ state: State.DELETED,+ } as unknown as Plan;++ expect(isRolloutExpected({ issue: approvedIssue, plan })).toBe(true);+ });+});diff --git a/frontend/src/routes/project/plan-detail/utils/phaseSummary.ts b/frontend/src/routes/project/plan-detail/utils/phaseSummary.tsindex cbfb241593..76e7e1e629 100644--- a/frontend/src/routes/project/plan-detail/utils/phaseSummary.ts+++ b/frontend/src/routes/project/plan-detail/utils/phaseSummary.ts@@ -1,4 +1,6 @@+import { ApprovalStatus, State } from "@/types/proto-es/v1/common_pb";import type { Issue } from "@/types/proto-es/v1/issue_service_pb";+import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";import type { Plan } from "@/types/proto-es/v1/plan_service_pb";import { PlanCheckRun_Status } from "@/types/proto-es/v1/plan_service_pb";import type { Rollout } from "@/types/proto-es/v1/rollout_service_pb";@@ -18,6 +20,14 @@ export interface PlanCheckSummary {warning: number;}+// Mirrors the eligibility gates that can permanently prevent RolloutCreator+// from materializing a rollout. Transient approval and check gates are handled+// separately below.+const supportsAutomaticRollout = (plan: Plan): boolean =>+ plan.state === State.ACTIVE &&+ plan.specs.length > 0 &&+ plan.specs.every((spec) => spec.config?.case === "changeDatabaseConfig");+export const getPlanCheckSummary = (plan: Plan): PlanCheckSummary => {const statusCount = plan.planCheckRunStatusCount || {};const running =@@ -38,6 +48,38 @@ export const getPlanCheckSummary = (plan: Plan): PlanCheckSummary => {};};+export const isRolloutExpected = ({+ issue,+ plan,+}: {+ issue?: Issue;+ plan: Plan;+}): boolean => {+ if (plan.hasRollout) {+ return true;+ }+ if (!supportsAutomaticRollout(plan)) {+ return false;+ }+ if (issue?.status === IssueStatus.DONE) {+ return true;+ }+ const approvalPassed =+ issue?.approvalStatus === ApprovalStatus.APPROVED ||+ issue?.approvalStatus === ApprovalStatus.SKIPPED ||+ issue?.approvalTemplate?.flow?.roles.length === 0;+ if (issue?.status !== IssueStatus.OPEN || issue.draft || !approvalPassed) {+ return false;+ }+ const checks = getPlanCheckSummary(plan);+ return (+ checks.running === 0 &&+ checks.error === 0 &&+ (plan.planCheckRunStatusCount?.AVAILABLE ?? 0) === 0 &&+ (plan.planCheckRunStatusCount?.CANCELED ?? 0) === 0+ );+};+const targetsForSpec = (spec: Plan["specs"][number]): string[] => {if (spec.config?.case === "changeDatabaseConfig") {return spec.config.value.targets || [];diff --git a/frontend/src/routes/workspace/DatabasesPage.tsx b/frontend/src/routes/workspace/DatabasesPage.tsxindex 24259c0f3e..1796a26ec4 100644--- a/frontend/src/routes/workspace/DatabasesPage.tsx+++ b/frontend/src/routes/workspace/DatabasesPage.tsx@@ -4,6 +4,7 @@ import { Plus } from "lucide-react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { useCurrentRoute } from "@/app/router";+import { markListScrollRestorationEntry } from "@/app/router/NavigationScrollRestoration";import {AdvancedSearch,getValueFromScopes,@@ -521,6 +522,7 @@ export function DatabasesPage() {<DatabaseTablefilter={filter}mode="ALL"+ onOpenDatabase={markListScrollRestorationEntry}selectedNames={selectedNames}onSelectedNamesChange={setSelectedNames}onDatabasesChange={setVisibleDatabases}diff --git a/frontend/src/routes/workspace/InstancesPage.tsx b/frontend/src/routes/workspace/InstancesPage.tsxindex cba008c3bb..c5e7f65332 100644--- a/frontend/src/routes/workspace/InstancesPage.tsx+++ b/frontend/src/routes/workspace/InstancesPage.tsx@@ -13,7 +13,10 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { router, useCurrentRoute } from "@/app/router";import { INSTANCE_ROUTE_CREATE } from "@/app/router/handles";-import { useScrollRestorationLoadMore } from "@/app/router/NavigationScrollRestoration";+import {+ markListScrollRestorationEntry,+ useListScrollRestorationLoadMore,+} from "@/app/router/NavigationScrollRestoration";import {AdvancedSearch,getValueFromScopes,@@ -703,7 +706,7 @@ export function InstancesPage() {fetchInstances(false);}}, [isFetchingMore, fetchInstances]);- useScrollRestorationLoadMore({+ useListScrollRestorationLoadMore({dataList: instances,hasMore,isFetchingMore,@@ -858,6 +861,7 @@ export function InstancesPage() {if (e.ctrlKey || e.metaKey) {window.open(url, "_blank");} else {+ markListScrollRestorationEntry();router.push(url);}},diff --git a/frontend/src/routes/workspace/MyIssuesPage.tsx b/frontend/src/routes/workspace/MyIssuesPage.tsxindex fc7ff7d601..c47bc37fa4 100644--- a/frontend/src/routes/workspace/MyIssuesPage.tsx+++ b/frontend/src/routes/workspace/MyIssuesPage.tsx@@ -1,9 +1,8 @@import { useCallback, useEffect, useMemo, useState } from "react";-import { useLocation } from "react-router";import {- markScrollRestorationEntry,- useScrollRestorationKey,- useScrollRestorationLoadMore,+ markListScrollRestorationEntry,+ useListScrollRestorationKey,+ useListScrollRestorationLoadMore,} from "@/app/router/NavigationScrollRestoration";import type { SearchParams } from "@/components/AdvancedSearch";import {@@ -38,8 +37,7 @@ const serializeSearchParams = (params: SearchParams): string =>buildSearchTextBySearchParams(params);export function MyIssuesPage() {- const location = useLocation();- const scrollRestorationKey = useScrollRestorationKey();+ const listScrollRestorationKey = useListScrollRestorationKey();const batchGetOrFetchUsers = useAppStore((state) => state.batchGetOrFetchUsers);@@ -104,10 +102,10 @@ export function MyIssuesPage() {const paged = usePagedData<Issue>({sessionKey: "bb.issue-table.my-issues",cacheKey: viewCacheKey,- cacheRestoreToken: scrollRestorationKey,+ cacheRestoreToken: listScrollRestorationKey,fetchList: fetchIssueList,});- useScrollRestorationLoadMore(paged);+ useListScrollRestorationLoadMore(paged);useEffect(() => {if (paged.dataList.length === 0) {@@ -146,11 +144,6 @@ export function MyIssuesPage() {return next;});}, []);- const handleOpenIssue = useCallback(- () => markScrollRestorationEntry(location),- [location]- );-const toggleSelectAll = useCallback(() => {setSelectedNames((prev) => {const allSelected =@@ -191,7 +184,7 @@ export function MyIssuesPage() {issues={paged.dataList}selectedNames={selectedNames}onToggleSelection={toggleSelection}- onOpenIssue={handleOpenIssue}+ onOpenIssue={markListScrollRestorationEntry}showProject/>{paged.dataList.length > 0 && (diff --git a/frontend/src/routes/workspace/ProjectsPage.navigation.test.ts b/frontend/src/routes/workspace/ProjectsPage.navigation.test.tsindex 21fa31b009..9ff4659035 100644--- a/frontend/src/routes/workspace/ProjectsPage.navigation.test.ts+++ b/frontend/src/routes/workspace/ProjectsPage.navigation.test.ts@@ -8,6 +8,7 @@ describe("ProjectsPage navigation", () => {expect(source).toContain("projectIssuesRoute(project)");expect(source).toContain("e.ctrlKey || e.metaKey");expect(source).toContain('window.open(route.fullPath, "_blank")');+ expect(source).toContain("markListScrollRestorationEntry();");expect(source).not.toContain("PROJECT_V1_ROUTE_DETAIL");expect(source).not.toContain("router.push({ path: `/${project.name}` })");});diff --git a/frontend/src/routes/workspace/ProjectsPage.tsx b/frontend/src/routes/workspace/ProjectsPage.tsxindex b23e4623ec..9642e5ec80 100644--- a/frontend/src/routes/workspace/ProjectsPage.tsx+++ b/frontend/src/routes/workspace/ProjectsPage.tsx@@ -3,7 +3,10 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { router, useCurrentRoute } from "@/app/router";import { PROJECT_V1_ROUTE_ISSUES } from "@/app/router/handles";-import { useScrollRestorationLoadMore } from "@/app/router/NavigationScrollRestoration";+import {+ markListScrollRestorationEntry,+ useListScrollRestorationLoadMore,+} from "@/app/router/NavigationScrollRestoration";import {AdvancedSearch,getValueFromScopes,@@ -439,7 +442,7 @@ export function ProjectsPage() {fetchProjects(false);}}, [isFetchingMore, fetchProjects]);- useScrollRestorationLoadMore({+ useListScrollRestorationLoadMore({dataList: projects,hasMore,isFetchingMore,@@ -600,6 +603,7 @@ export function ProjectsPage() {if (e.ctrlKey || e.metaKey) {window.open(route.fullPath, "_blank");} else {+ markListScrollRestorationEntry();router.push(projectIssuesRoute(project));}},diff --git a/frontend/src/utils/v1/issue/issue.ts b/frontend/src/utils/v1/issue/issue.tsindex 5ad6315538..22c256491b 100644--- a/frontend/src/utils/v1/issue/issue.ts+++ b/frontend/src/utils/v1/issue/issue.ts@@ -91,10 +91,7 @@ export const formatIssueTitle = (};/** Generates a title for database change plan issues. */-export const generatePlanTitle = (- template: "bb.plan.change-database",- databaseNameList?: string[]-): string => {+export const generatePlanTitle = (databaseNameList?: string[]): string => {return formatIssueTitle(i18n.t("issue.title.change-database"),databaseNameListdiff --git a/frontend/tests/e2e/scroll-restoration/dashboard-scroll-restoration.spec.ts b/frontend/tests/e2e/scroll-restoration/dashboard-scroll-restoration.spec.tsindex b0f99ab829..dffa397582 100644--- a/frontend/tests/e2e/scroll-restoration/dashboard-scroll-restoration.spec.ts+++ b/frontend/tests/e2e/scroll-restoration/dashboard-scroll-restoration.spec.ts@@ -11,12 +11,10 @@ import { loadTestEnv, type TestEnv } from "../framework/env";test.setTimeout(240_000);const ISSUE_COUNT = 18;-const PLAN_COUNT = 55;let env: TestEnv & { api: BytebaseApiClient };let sharedContext: BrowserContext;let page: Page;let issueListUrl: string;-let planListUrl: string;let originalExternalUrl = "";type SavedViewport = {@@ -98,9 +96,6 @@ test.beforeAll(async ({ browser }) => {issueListUrl = `${env.baseURL}/projects/${projectId}/issues?q=${encodeURIComponent(searchToken)}`;- planListUrl = `${env.baseURL}/projects/${projectId}/plans?q=${encodeURIComponent(- searchToken- )}`;const setting = await env.api.getSetting("WORKSPACE_PROFILE");originalExternalUrl =@@ -108,7 +103,7 @@ test.beforeAll(async ({ browser }) => {?.workspaceProfile?.externalUrl ?? "";const sheet = await env.api.createSheet(env.project, "SELECT 1;");- for (let i = 0; i < PLAN_COUNT; i++) {+ for (let i = 0; i < ISSUE_COUNT; i++) {const title = `${searchToken} issue ${i}`;const plan = await env.api.createPlan(env.project, title, [{@@ -121,14 +116,12 @@ test.beforeAll(async ({ browser }) => {{ length: (i % 4) + 1 },() => `${searchToken} variable-height content`).join("\n");- if (i < ISSUE_COUNT) {- await env.api.createIssue(- env.project,- title,- plan.name,- repeatedDescription- );- }+ await env.api.createIssue(+ env.project,+ title,+ plan.name,+ repeatedDescription+ );}sharedContext = await browser.newContext({@@ -161,16 +154,6 @@ test.describe("dashboard scroll restoration", () => {});});- test("restores every loaded page in the paginated Plans view", async () => {- await env.api.setWorkspaceExternalUrl(env.baseURL);- await expectBackRestored({- detailUrlPattern: /\/projects\/[^/]+\/plans\//,- listUrl: planListUrl,- rowTestId: "plan-list-item",- rowCount: PLAN_COUNT,- });- });-test("restores the nested main pane below a wrapped banner", async () => {await env.api.setWorkspaceExternalUrl("");await page.goto(issueListUrl);