Skip to content

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

refactor(plan-detail): foundation + page-hook restructure (#20338)

boojack738b40486093
diff --git a/docs/superpowers/plans/2026-05-13-plan-detail-refactor.md b/docs/superpowers/plans/2026-05-13-plan-detail-refactor.md
new file mode 100644
index 0000000000..e82a5a66c8
--- /dev/null
+++ b/docs/superpowers/plans/2026-05-13-plan-detail-refactor.md
@@ -0,0 +1,2531 @@
+# Plan Detail Refactor Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Refactor `frontend/src/react/pages/project/plan-detail/` for maintainability without changing behavior — split oversized files, restructure the page hook, replace Pinia reads with Zustand slices, run `/simplify` per a bounded checklist.
+
+**Architecture:** Single PR carrying the entire refactor. Internally the work is grouped into six phases (Foundation → Shell → Changes → Review → Deploy → Header/Sidebar/cleanup), but everything lands on one feature branch as a single review surface. No intermediate compatibility shims — every consumer updates in the same diff. The CI guard for Pinia reads inside `plan-detail/` is strict from the first commit.
+
+**Tech Stack:** React 18, TypeScript, Zustand v5 (slice pattern), Vitest + React Testing Library, Playwright (e2e), Tailwind v4, Vue 3 Pinia (existing, kept in coexistence for other pages), Connect-RPC service clients.
+
+**Behavioral contract:** `docs/plans/2026-05-13-plan-detail-current-state.md`. If a test fails after a refactor step → fix the regression, not the test.
+
+**Design spec:** `docs/superpowers/specs/2026-05-13-plan-detail-refactor-design.md` (see the 2026-05-13 update noting the one-PR delivery decision).
+
+**Branch:** `refactor/plan-detail-maintainability`
+
+---
+
+## Conventions used in every task
+
+- **Format gate**: After any frontend code change, run `pnpm --dir frontend fix` and `pnpm --dir frontend type-check`. They must produce no diff and zero errors before commit.
+- **Test gate**: Run the affected test file(s) with `pnpm --dir frontend test -- <path>`. Existing tests must pass unchanged.
+- **No assertion edits**: When a test moves with its subject, only the import path may change.
+- **Commit cadence**: Commit after every passing test or every cohesive file move. Small commits keep `git bisect` and per-commit review useful.
+- **No compat shims**: Update every consumer in the same diff that moves the file. No one-line re-export files at old paths.
+- **Pre-PR**: Walk `docs/pre-pr-checklist.md` before opening the PR (per AGENTS.md).
+
+---
+
+# Phase 1 — Foundation
+
+**Goal:** Land all infrastructure plan-detail will depend on. No existing plan-detail call sites change in this phase.
+
+## Task 1.1: Add `DatabaseSlice` to the app store
+
+**Files:**
+- Create: `frontend/src/react/stores/app/database.ts`
+- Modify: `frontend/src/react/stores/app/types.ts`
+- Modify: `frontend/src/react/stores/app/index.ts`
+- Test: extend `frontend/src/react/stores/app/index.test.ts`
+
+The slice mirrors the existing `InstanceSlice` pattern (per-name entity cache + request-promise dedup + error map). Only port methods plan-detail actually calls.
+
+**Important proto naming gotcha (verified 2026-05-13):** the resource-`Database` schema generator is exported as `DatabaseSchema$` in `frontend/src/types/proto-es/v1/database_service_pb.d.ts`; `DatabaseSchema` is a different message (DDL metadata). Use `DatabaseSchema$` with `create(...)` in this slice's tests. Also: the proto only defines `getDatabase`, `listDatabases`, `batchGetDatabases` — there is no `searchDatabases` RPC. The slice should expose `fetchDatabase`, `batchFetchDatabases`, and `fetchDatabases` (wrapping `listDatabases`) with shape `{ parent, pageSize, pageToken?, filter?: string, orderBy? }` — the `filter` is the proto's raw CEL string (Pinia's `DatabaseFilter` is a Vue-layer wrapper that compiles to that string via `getListDatabaseFilter`).
+
+- [ ] **Step 1: Write the failing test**
+
+Add to `frontend/src/react/stores/app/index.test.ts` near the existing instance test:
+
+```ts
+test("deduplicates database fetches and caches the result", async () => {
+ const dbName = "instances/i1/databases/db1";
+ const database = createProto(DatabaseSchema$, { name: dbName });
+ mocks.getDatabase.mockResolvedValueOnce(database);
+ const store = createAppStore();
+
+ const [first, second, third] = await Promise.all([
+ store.getState().fetchDatabase(dbName),
+ store.getState().fetchDatabase(dbName),
+ store.getState().fetchDatabase(dbName),
+ ]);
+
+ expect(first).toEqual(database);
+ expect(second).toEqual(database);
+ expect(third).toEqual(database);
+ expect(mocks.getDatabase).toHaveBeenCalledTimes(1);
+ expect(store.getState().databasesByName[dbName]).toEqual(database);
+});
+```
+
+Add to the `mocks` block:
+```ts
+ getDatabase: vi.fn(),
+ batchGetDatabases: vi.fn(),
+ searchDatabases: vi.fn(),
+```
+
+Add to the `vi.mock("@/connect", ...)` block:
+```ts
+ databaseServiceClientConnect: {
+ getDatabase: mocks.getDatabase,
+ batchGetDatabases: mocks.batchGetDatabases,
+ searchDatabases: mocks.searchDatabases,
+ },
+```
+
+Add to top imports:
+```ts
+import { DatabaseSchema } from "@/types/proto-es/v1/database_service_pb";
+```
+
+- [ ] **Step 2: Run test and verify it fails**
+
+```
+pnpm --dir frontend test -- src/react/stores/app/index.test.ts -t "deduplicates database fetches"
+```
+
+Expected: FAIL — `fetchDatabase` is not a function.
+
+- [ ] **Step 3: Add `DatabaseSlice` type to `types.ts`**
+
+Insert after `InstanceSlice`:
+
+```ts
+import type {
+ Database,
+} from "@/types/proto-es/v1/database_service_pb";
+
+export type DatabaseSlice = {
+ databasesByName: Record<string, Database>;
+ databaseRequests: Record<string, Promise<Database | undefined>>;
+ databaseErrorsByName: Record<string, Error | undefined>;
+ fetchDatabase: (name: string) => Promise<Database | undefined>;
+ batchFetchDatabases: (names: string[]) => Promise<Database[]>;
+ searchDatabases: (params: {
+ parent: string;
+ filter?: string;
+ pageSize?: number;
+ pageToken?: string;
+ }) => Promise<{ databases: Database[]; nextPageToken?: string }>;
+};
+```
+
+Append `DatabaseSlice` to the `AppStoreState` union at the bottom.
+
+- [ ] **Step 4: Implement the slice (`database.ts`)**
+
+```ts
+import { create as createProto } from "@bufbuild/protobuf";
+import { databaseServiceClientConnect } from "@/connect";
+import { isValidDatabaseName } from "@/react/lib/resourceName";
+import {
+ BatchGetDatabasesRequestSchema,
+ GetDatabaseRequestSchema,
+ SearchDatabasesRequestSchema,
+} from "@/types/proto-es/v1/database_service_pb";
+import type { AppSliceCreator, DatabaseSlice } from "./types";
+
+function toError(error: unknown): Error {
+ return error instanceof Error ? error : new Error(String(error));
+}
+
+export const createDatabaseSlice: AppSliceCreator<DatabaseSlice> = (set, get) => ({
+ databasesByName: {},
+ databaseRequests: {},
+ databaseErrorsByName: {},
+
+ fetchDatabase: async (name) => {
+ if (!isValidDatabaseName(name)) return undefined;
+ const existing = get().databasesByName[name];
+ if (existing) return existing;
+ const pending = get().databaseRequests[name];
+ if (pending) return pending;
+
+ const request = databaseServiceClientConnect
+ .getDatabase(createProto(GetDatabaseRequestSchema, { name }))
+ .then((database) => {
+ set((state) => {
+ const { [name]: _omit, ...rest } = state.databaseRequests;
+ return {
+ databasesByName: { ...state.databasesByName, [database.name]: database },
+ databaseErrorsByName: { ...state.databaseErrorsByName, [name]: undefined },
+ databaseRequests: rest,
+ };
+ });
+ return database;
+ })
+ .catch((error) => {
+ set((state) => {
+ const { [name]: _omit, ...rest } = state.databaseRequests;
+ return {
+ databaseErrorsByName: { ...state.databaseErrorsByName, [name]: toError(error) },
+ databaseRequests: rest,
+ };
+ });
+ return undefined;
+ });
+
+ set((state) => ({
+ databaseRequests: { ...state.databaseRequests, [name]: request },
+ }));
+ return request;
+ },
+
+ batchFetchDatabases: async (names) => {
+ if (!names.length) return [];
+ const response = await databaseServiceClientConnect.batchGetDatabases(
+ createProto(BatchGetDatabasesRequestSchema, { names })
+ );
+ set((state) => {
+ const next = { ...state.databasesByName };
+ for (const db of response.databases) next[db.name] = db;
+ return { databasesByName: next };
+ });
+ return response.databases;
+ },
+
+ searchDatabases: async ({ parent, filter, pageSize, pageToken }) => {
+ const response = await databaseServiceClientConnect.searchDatabases(
+ createProto(SearchDatabasesRequestSchema, { parent, filter, pageSize, pageToken })
+ );
+ set((state) => {
+ const next = { ...state.databasesByName };
+ for (const db of response.databases) next[db.name] = db;
+ return { databasesByName: next };
+ });
+ return { databases: response.databases, nextPageToken: response.nextPageToken };
+ },
+});
+```
+
+- [ ] **Step 5: Wire the slice into `createAppStore`**
+
+In `frontend/src/react/stores/app/index.ts`:
+
+```ts
+import { createDatabaseSlice } from "./database";
+// ...
+export const createAppStore = () =>
+ create<AppStoreState>()((...args) => ({
+ ...createAuthSlice(...args),
+ ...createWorkspaceSlice(...args),
+ ...createIamSlice(...args),
+ ...createProjectSlice(...args),
+ ...createInstanceSlice(...args),
+ ...createDatabaseSlice(...args),
+ ...createNotificationSlice(...args),
+ ...createPreferencesSlice(...args),
+ }));
+```
+
+- [ ] **Step 6: Run test → PASS. Type-check + format.**
+
+```
+pnpm --dir frontend test -- src/react/stores/app/index.test.ts -t "deduplicates database fetches"
+pnpm --dir frontend type-check
+pnpm --dir frontend fix
+```
+
+- [ ] **Step 7: Commit**
+
+```
+git add frontend/src/react/stores/app/database.ts frontend/src/react/stores/app/types.ts frontend/src/react/stores/app/index.ts frontend/src/react/stores/app/index.test.ts
+git commit -m "feat(react): add DatabaseSlice to app store"
+```
+
+## Task 1.2: Add `DBGroupSlice`
+
+**Files:**
+- Create: `frontend/src/react/stores/app/dbGroup.ts`
+- Modify: `types.ts`, `index.ts`
+- Test: extend `index.test.ts`
+
+- [ ] **Step 1: Write the failing test**
+
+```ts
+test("deduplicates db group fetches and caches the result", async () => {
+ const name = "projects/p1/databaseGroups/g1";
+ const group = createProto(DatabaseGroupSchema, { name });
+ mocks.getDatabaseGroup.mockResolvedValueOnce(group);
+ const store = createAppStore();
+
+ const [first, second] = await Promise.all([
+ store.getState().fetchDBGroup(name),
+ store.getState().fetchDBGroup(name),
+ ]);
+
+ expect(first).toEqual(group);
+ expect(second).toEqual(group);
+ expect(mocks.getDatabaseGroup).toHaveBeenCalledTimes(1);
+});
+```
+
+Add `getDatabaseGroup` and `listDatabaseGroups` to `mocks`. Wire `databaseGroupServiceClientConnect`. Import `DatabaseGroupSchema`.
+
+- [ ] **Step 2: Run test → FAIL.**
+
+- [ ] **Step 3: Add `DBGroupSlice` type**
+
+```ts
+import type { DatabaseGroup } from "@/types/proto-es/v1/database_group_service_pb";
+
+export type DBGroupSlice = {
+ dbGroupsByName: Record<string, DatabaseGroup>;
+ dbGroupRequests: Record<string, Promise<DatabaseGroup | undefined>>;
+ dbGroupErrorsByName: Record<string, Error | undefined>;
+ fetchDBGroup: (name: string) => Promise<DatabaseGroup | undefined>;
+ listDBGroupsForProject: (project: string) => Promise<DatabaseGroup[]>;
+};
+```
+
+Append to `AppStoreState`.
+
+- [ ] **Step 4: Implement `dbGroup.ts`**
+
+```ts
+import { create as createProto } from "@bufbuild/protobuf";
+import { databaseGroupServiceClientConnect } from "@/connect";
+import { isValidDatabaseGroupName } from "@/react/lib/resourceName";
+import {
+ GetDatabaseGroupRequestSchema,
+ ListDatabaseGroupsRequestSchema,
+} from "@/types/proto-es/v1/database_group_service_pb";
+import type { AppSliceCreator, DBGroupSlice } from "./types";
+
+function toError(e: unknown): Error {
+ return e instanceof Error ? e : new Error(String(e));
+}
+
+export const createDBGroupSlice: AppSliceCreator<DBGroupSlice> = (set, get) => ({
+ dbGroupsByName: {},
+ dbGroupRequests: {},
+ dbGroupErrorsByName: {},
+
+ fetchDBGroup: async (name) => {
+ if (!isValidDatabaseGroupName(name)) return undefined;
+ const existing = get().dbGroupsByName[name];
+ if (existing) return existing;
+ const pending = get().dbGroupRequests[name];
+ if (pending) return pending;
+
+ const request = databaseGroupServiceClientConnect
+ .getDatabaseGroup(createProto(GetDatabaseGroupRequestSchema, { name }))
+ .then((group) => {
+ set((state) => {
+ const { [name]: _omit, ...rest } = state.dbGroupRequests;
+ return {
+ dbGroupsByName: { ...state.dbGroupsByName, [group.name]: group },
+ dbGroupErrorsByName: { ...state.dbGroupErrorsByName, [name]: undefined },
+ dbGroupRequests: rest,
+ };
+ });
+ return group;
+ })
+ .catch((error) => {
+ set((state) => {
+ const { [name]: _omit, ...rest } = state.dbGroupRequests;
+ return {
+ dbGroupErrorsByName: { ...state.dbGroupErrorsByName, [name]: toError(error) },
+ dbGroupRequests: rest,
+ };
+ });
+ return undefined;
+ });
+
+ set((state) => ({ dbGroupRequests: { ...state.dbGroupRequests, [name]: request } }));
+ return request;
+ },
+
+ listDBGroupsForProject: async (project) => {
+ const response = await databaseGroupServiceClientConnect.listDatabaseGroups(
+ createProto(ListDatabaseGroupsRequestSchema, { parent: project })
+ );
+ set((state) => {
+ const next = { ...state.dbGroupsByName };
+ for (const g of response.databaseGroups) next[g.name] = g;
+ return { dbGroupsByName: next };
+ });
+ return response.databaseGroups;
+ },
+});
+```
+
+- [ ] **Step 5: Wire into `createAppStore`** (after `createDatabaseSlice`).
+- [ ] **Step 6: Test → PASS. Type-check + fix.**
+- [ ] **Step 7: Commit**
+
+```
+git commit -m "feat(react): add DBGroupSlice to app store"
+```
+
+## Task 1.3: Add `SheetSlice`
+
+**Files:** mirrors Task 1.1.
+
+- [ ] **Step 1: Write the failing test**
+
+```ts
+test("deduplicates sheet fetches and caches the result", async () => {
+ const name = "projects/p1/sheets/s1";
+ const sheet = createProto(SheetSchema, { name, content: new Uint8Array() });
+ mocks.getSheet.mockResolvedValueOnce(sheet);
+ const store = createAppStore();
+
+ const [first, second] = await Promise.all([
+ store.getState().fetchSheet(name),
+ store.getState().fetchSheet(name),
+ ]);
+
+ expect(first).toEqual(sheet);
+ expect(second).toEqual(sheet);
+ expect(mocks.getSheet).toHaveBeenCalledTimes(1);
+});
+```
+
+Add `getSheet` and `createSheet` to mocks; wire `sheetServiceClientConnect`; import `SheetSchema`.
+
+- [ ] **Step 2: Run test → FAIL.**
+
+- [ ] **Step 3: Add `SheetSlice` type**
+
+```ts
+import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";
+
+export type SheetSlice = {
+ sheetsByName: Record<string, Sheet>;
+ sheetRequests: Record<string, Promise<Sheet | undefined>>;
+ sheetErrorsByName: Record<string, Error | undefined>;
+ fetchSheet: (name: string, raw?: boolean) => Promise<Sheet | undefined>;
+ createSheet: (parent: string, sheet: Sheet) => Promise<Sheet>;
+};
+```
+
+Append to `AppStoreState`.
+
+- [ ] **Step 4: Implement `sheet.ts`**
+
+```ts
+import { create as createProto } from "@bufbuild/protobuf";
+import { sheetServiceClientConnect } from "@/connect";
+import { isValidSheetName } from "@/react/lib/resourceName";
+import {
+ CreateSheetRequestSchema,
+ GetSheetRequestSchema,
+} from "@/types/proto-es/v1/sheet_service_pb";
+import type { AppSliceCreator, SheetSlice } from "./types";
+
+function toError(e: unknown): Error {
+ return e instanceof Error ? e : new Error(String(e));
+}
+
+export const createSheetSlice: AppSliceCreator<SheetSlice> = (set, get) => ({
+ sheetsByName: {},
+ sheetRequests: {},
+ sheetErrorsByName: {},
+
+ fetchSheet: async (name, raw = false) => {
+ if (!isValidSheetName(name)) return undefined;
+ const existing = get().sheetsByName[name];
+ if (existing && !raw) return existing;
+ const pending = get().sheetRequests[name];
+ if (pending) return pending;
+
+ const request = sheetServiceClientConnect
+ .getSheet(createProto(GetSheetRequestSchema, { name, raw }))
+ .then((sheet) => {
+ set((state) => {
+ const { [name]: _omit, ...rest } = state.sheetRequests;
+ return {
+ sheetsByName: { ...state.sheetsByName, [sheet.name]: sheet },
+ sheetErrorsByName: { ...state.sheetErrorsByName, [name]: undefined },
+ sheetRequests: rest,
+ };
+ });
+ return sheet;
+ })
+ .catch((error) => {
+ set((state) => {
+ const { [name]: _omit, ...rest } = state.sheetRequests;
+ return {
+ sheetErrorsByName: { ...state.sheetErrorsByName, [name]: toError(error) },
+ sheetRequests: rest,
+ };
+ });
+ return undefined;
+ });
+
+ set((state) => ({ sheetRequests: { ...state.sheetRequests, [name]: request } }));
+ return request;
+ },
+
+ createSheet: async (parent, sheet) => {
+ const created = await sheetServiceClientConnect.createSheet(
+ createProto(CreateSheetRequestSchema, { parent, sheet })
+ );
+ set((state) => ({
+ sheetsByName: { ...state.sheetsByName, [created.name]: created },
+ }));
+ return created;
+ },
+});
+```
+
+- [ ] **Step 5: Wire into `createAppStore`.**
+- [ ] **Step 6: Test → PASS. Type-check + fix.**
+- [ ] **Step 7: Commit**
+
+```
+git commit -m "feat(react): add SheetSlice to app store"
+```
+
+## Task 1.4: Add `InstanceRoleSlice`
+
+- [ ] **Step 1: Write the failing test**
+
+```ts
+test("deduplicates instance role fetches per instance", async () => {
+ const instance = "instances/i1";
+ const roles = [createProto(InstanceRoleSchema, { name: `${instance}/roles/admin` })];
+ mocks.listInstanceRoles.mockResolvedValueOnce({ roles });
+ const store = createAppStore();
+
+ const [first, second] = await Promise.all([
+ store.getState().fetchInstanceRoles(instance),
+ store.getState().fetchInstanceRoles(instance),
+ ]);
+
+ expect(first).toEqual(roles);
+ expect(second).toEqual(roles);
+ expect(mocks.listInstanceRoles).toHaveBeenCalledTimes(1);
+});
+```
+
+Add `listInstanceRoles` mock; wire `instanceRoleServiceClientConnect`; import `InstanceRoleSchema`.
+
+- [ ] **Step 2: Run test → FAIL.**
+
+- [ ] **Step 3: Add `InstanceRoleSlice` type**
+
+```ts
+import type { InstanceRole } from "@/types/proto-es/v1/instance_role_service_pb";
+
+export type InstanceRoleSlice = {
+ rolesByInstance: Record<string, InstanceRole[]>;
+ roleRequests: Record<string, Promise<InstanceRole[]>>;
+ fetchInstanceRoles: (instance: string) => Promise<InstanceRole[]>;
+};
+```
+
+Append to `AppStoreState`.
+
+- [ ] **Step 4: Implement `instanceRole.ts`**
+
+```ts
+import { create as createProto } from "@bufbuild/protobuf";
+import { instanceRoleServiceClientConnect } from "@/connect";
+import { ListInstanceRolesRequestSchema } from "@/types/proto-es/v1/instance_role_service_pb";
+import type { AppSliceCreator, InstanceRoleSlice } from "./types";
+
+export const createInstanceRoleSlice: AppSliceCreator<InstanceRoleSlice> = (set, get) => ({
+ rolesByInstance: {},
+ roleRequests: {},
+
+ fetchInstanceRoles: async (instance) => {
+ const cached = get().rolesByInstance[instance];
+ if (cached) return cached;
+ const pending = get().roleRequests[instance];
+ if (pending) return pending;
+
+ const request = instanceRoleServiceClientConnect
+ .listInstanceRoles(createProto(ListInstanceRolesRequestSchema, { parent: instance }))
+ .then((response) => {
+ set((state) => {
+ const { [instance]: _omit, ...rest } = state.roleRequests;
+ return {
+ rolesByInstance: { ...state.rolesByInstance, [instance]: response.roles },
+ roleRequests: rest,
+ };
+ });
+ return response.roles;
+ })
+ .catch(() => {
+ set((state) => {
+ const { [instance]: _omit, ...rest } = state.roleRequests;
+ return { roleRequests: rest };
+ });
+ return [];
+ });
+
+ set((state) => ({ roleRequests: { ...state.roleRequests, [instance]: request } }));
+ return request;
+ },
+});
+```
+
+- [ ] **Step 5: Wire into `createAppStore`.**
+- [ ] **Step 6: Test → PASS. Type-check + fix.**
+- [ ] **Step 7: Commit**
+
+```
+git commit -m "feat(react): add InstanceRoleSlice to app store"
+```
+
+## Task 1.5: Page-scoped Zustand store skeleton
+
+**Files:**
+- Create: `frontend/src/react/pages/project/plan-detail/shared/stores/types.ts`
+- Create: `.../shared/stores/snapshotSlice.ts`
+- Create: `.../shared/stores/phaseSlice.ts`
+- Create: `.../shared/stores/editingSlice.ts`
+- Create: `.../shared/stores/selectionSlice.ts`
+- Create: `.../shared/stores/pollingSlice.ts`
+- Create: `.../shared/stores/usePlanDetailStore.tsx`
+- Test: `.../shared/stores/__tests__/usePlanDetailStore.test.tsx`
+
+The store is built but not yet wired into the page — wiring happens in Phase 2.
+
+- [ ] **Step 1: Write the failing test**
+
+`shared/stores/__tests__/usePlanDetailStore.test.tsx`:
+
+```tsx
+import { act, renderHook } from "@testing-library/react";
+import { describe, expect, test } from "vitest";
+import type { ReactNode } from "react";
+import {
+ PlanDetailStoreProvider,
+ usePlanDetailStore,
+} from "../usePlanDetailStore";
+
+const wrapper = ({ children }: { children: ReactNode }) => (
+ <PlanDetailStoreProvider>{children}</PlanDetailStoreProvider>
+);
+
+describe("usePlanDetailStore", () => {
+ test("phase slice toggles active phases", () => {
+ const { result } = renderHook(
+ () => ({
+ active: usePlanDetailStore((s) => s.activePhases),
+ toggle: usePlanDetailStore((s) => s.togglePhase),
+ }),
+ { wrapper }
+ );
+
+ expect(result.current.active.has("changes")).toBe(true);
+ act(() => result.current.toggle("changes"));
+ expect(result.current.active.has("changes")).toBe(false);
+ });
+
+ test("editing slice tracks scopes and isEditing", () => {
+ const { result } = renderHook(
+ () => ({
+ scopes: usePlanDetailStore((s) => s.editingScopes),
+ setEditing: usePlanDetailStore((s) => s.setEditing),
+ }),
+ { wrapper }
+ );
+
+ expect(Object.keys(result.current.scopes)).toHaveLength(0);
+ act(() => result.current.setEditing("title", true));
+ expect(result.current.scopes.title).toBe(true);
+ act(() => result.current.setEditing("title", false));
+ expect(result.current.scopes.title).toBeUndefined();
+ });
+
+ test("each provider mount creates an isolated store", () => {
+ const { result: a } = renderHook(() => usePlanDetailStore((s) => s.togglePhase), {
+ wrapper,
+ });
+ const { result: b } = renderHook(() => usePlanDetailStore((s) => s.togglePhase), {
+ wrapper,
+ });
+ expect(a.current).not.toBe(b.current);
+ });
+});
+```
+
+- [ ] **Step 2: Run test → FAIL (module not found).**
+
+```
+pnpm --dir frontend test -- src/react/pages/project/plan-detail/shared/stores/__tests__/usePlanDetailStore.test.tsx
+```
+
+- [ ] **Step 3: Create `types.ts`**
+
+```ts
+import type { Plan, PlanCheckRun } from "@/types/proto-es/v1/plan_service_pb";
+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
+import type { Rollout, TaskRun } from "@/types/proto-es/v1/rollout_service_pb";
+import type { StateCreator } from "zustand";
+
+export type PlanDetailPhase = "changes" | "review" | "deploy";
+
+export interface PlanDetailPageSnapshot {
+ plan?: Plan;
+ issue?: Issue;
+ rollout?: Rollout;
+ taskRuns: TaskRun[];
+ planCheckRuns: PlanCheckRun[];
+ isInitializing: boolean;
+ isNotFound: boolean;
+ isPermissionDenied: boolean;
+}
+
+export type SnapshotSlice = {
+ snapshot: PlanDetailPageSnapshot;
+ setSnapshot: (snapshot: PlanDetailPageSnapshot) => void;
+ patchSnapshot: (patch: Partial<PlanDetailPageSnapshot>) => void;
+};
+
+export type PhaseSlice = {
+ activePhases: Set<PlanDetailPhase>;
+ togglePhase: (phase: PlanDetailPhase) => void;
+ expandPhase: (phase: PlanDetailPhase) => void;
+ collapsePhase: (phase: PlanDetailPhase) => void;
+};
+
+export type EditingSlice = {
+ editingScopes: Record<string, true>;
+ setEditing: (scope: string, editing: boolean) => void;
+ bypassLeaveGuardOnce: () => void;
+ isLeaveGuardBypassed: () => boolean;
+ pendingLeaveTarget: string | null;
+ setPendingLeaveTarget: (target: string | null) => void;
+ pendingLeaveConfirm: boolean;
+ setPendingLeaveConfirm: (open: boolean) => void;
+};
+
+export type SelectionSlice = {
+ routePhase: PlanDetailPhase | undefined;
+ selectedSpecId: string | undefined;
+ selectedStageId: string | undefined;
+ selectedTaskName: string | undefined;
+ setRouteSelection: (selection: {
+ phase?: PlanDetailPhase;
+ specId?: string;
+ stageId?: string;
+ taskName?: string;
+ }) => void;
+};
+
+export type PollingSlice = {
+ isRefreshing: boolean;
+ isRunningChecks: boolean;
+ lastRefreshTime: number;
+ pollTimerId: number | undefined;
+ setRefreshing: (v: boolean) => void;
+ setRunningChecks: (v: boolean) => void;
+ setLastRefreshTime: (t: number) => void;
+ setPollTimerId: (id: number | undefined) => void;
+};
+
+export type PlanDetailStore = SnapshotSlice & PhaseSlice & EditingSlice & SelectionSlice & PollingSlice;
+
+export type PlanDetailSliceCreator<Slice> = StateCreator<PlanDetailStore, [], [], Slice>;
+```
+
+- [ ] **Step 4: Create `snapshotSlice.ts`**
+
+```ts
+import type { PlanDetailPageSnapshot, PlanDetailSliceCreator, SnapshotSlice } from "./types";
+
+const buildDefaultSnapshot = (): PlanDetailPageSnapshot => ({
+ taskRuns: [],
+ planCheckRuns: [],
+ isInitializing: true,
+ isNotFound: false,
+ isPermissionDenied: false,
+});
+
+export const createSnapshotSlice: PlanDetailSliceCreator<SnapshotSlice> = (set) => ({
+ snapshot: buildDefaultSnapshot(),
+ setSnapshot: (snapshot) => set({ snapshot }),
+ patchSnapshot: (patch) =>
+ set((state) => ({ snapshot: { ...state.snapshot, ...patch } })),
+});
+```
+
+- [ ] **Step 5: Create `phaseSlice.ts`**
+
+```ts
+import type { PhaseSlice, PlanDetailPhase, PlanDetailSliceCreator } from "./types";
+
+const defaultActivePhases = (): Set<PlanDetailPhase> => new Set(["changes"]);
+
+export const createPhaseSlice: PlanDetailSliceCreator<PhaseSlice> = (set) => ({
+ activePhases: defaultActivePhases(),
+ togglePhase: (phase) =>
+ set((state) => {
+ const next = new Set(state.activePhases);
+ if (next.has(phase)) next.delete(phase);
+ else next.add(phase);
+ return { activePhases: next };
+ }),
+ expandPhase: (phase) =>
+ set((state) => {
+ if (state.activePhases.has(phase)) return state;
+ const next = new Set(state.activePhases);
+ next.add(phase);
+ return { activePhases: next };
+ }),
+ collapsePhase: (phase) =>
+ set((state) => {
+ if (!state.activePhases.has(phase)) return state;
+ const next = new Set(state.activePhases);
+ next.delete(phase);
+ return { activePhases: next };
+ }),
+});
+```
+
+- [ ] **Step 6: Create `editingSlice.ts`**
+
+```ts
+import type { EditingSlice, PlanDetailSliceCreator } from "./types";
+
+export const createEditingSlice: PlanDetailSliceCreator<EditingSlice> = (set) => {
+ let bypassOnce = false;
+ return {
+ editingScopes: {},
+ setEditing: (scope, editing) =>
+ set((state) => {
+ const next = { ...state.editingScopes };
+ if (editing) next[scope] = true;
+ else delete next[scope];
+ return { editingScopes: next };
+ }),
+ bypassLeaveGuardOnce: () => {
+ bypassOnce = true;
+ },
+ isLeaveGuardBypassed: () => {
+ if (bypassOnce) {
+ bypassOnce = false;
+ return true;
+ }
+ return false;
+ },
+ pendingLeaveTarget: null,
+ setPendingLeaveTarget: (target) => set({ pendingLeaveTarget: target }),
+ pendingLeaveConfirm: false,
+ setPendingLeaveConfirm: (open) => set({ pendingLeaveConfirm: open }),
+ };
+};
+```
+
+- [ ] **Step 7: Create `selectionSlice.ts`**
+
+```ts
+import type { PlanDetailSliceCreator, SelectionSlice } from "./types";
+
+export const createSelectionSlice: PlanDetailSliceCreator<SelectionSlice> = (set) => ({
+ routePhase: undefined,
+ selectedSpecId: undefined,
+ selectedStageId: undefined,
+ selectedTaskName: undefined,
+ setRouteSelection: (selection) =>
+ set({
+ routePhase: selection.phase,
+ selectedSpecId: selection.specId,
+ selectedStageId: selection.stageId,
+ selectedTaskName: selection.taskName,
+ }),
+});
+```
+
+- [ ] **Step 8: Create `pollingSlice.ts`**
+
+```ts
+import type { PlanDetailSliceCreator, PollingSlice } from "./types";
+
+export const createPollingSlice: PlanDetailSliceCreator<PollingSlice> = (set) => ({
+ isRefreshing: false,
+ isRunningChecks: false,
+ lastRefreshTime: 0,
+ pollTimerId: undefined,
+ setRefreshing: (v) => set({ isRefreshing: v }),
+ setRunningChecks: (v) => set({ isRunningChecks: v }),
+ setLastRefreshTime: (t) => set({ lastRefreshTime: t }),
+ setPollTimerId: (id) => set({ pollTimerId: id }),
+});
+```
+
+- [ ] **Step 9: Create `usePlanDetailStore.tsx`**
+
+```tsx
+import { createContext, useContext, useState, type ReactNode } from "react";
+import { create, useStore } from "zustand";
+import { createEditingSlice } from "./editingSlice";
+import { createPhaseSlice } from "./phaseSlice";
+import { createPollingSlice } from "./pollingSlice";
+import { createSelectionSlice } from "./selectionSlice";
+import { createSnapshotSlice } from "./snapshotSlice";
+import type { PlanDetailStore } from "./types";
+
+const createPlanDetailStore = () =>
+ create<PlanDetailStore>()((...args) => ({
+ ...createSnapshotSlice(...args),
+ ...createPhaseSlice(...args),
+ ...createEditingSlice(...args),
+ ...createSelectionSlice(...args),
+ ...createPollingSlice(...args),
+ }));
+
+type PlanDetailStoreApi = ReturnType<typeof createPlanDetailStore>;
+
+const PlanDetailStoreContext = createContext<PlanDetailStoreApi | null>(null);
+
+export const PlanDetailStoreProvider = ({ children }: { children: ReactNode }) => {
+ const [store] = useState(createPlanDetailStore);
+ return (
+ <PlanDetailStoreContext.Provider value={store}>
+ {children}
+ </PlanDetailStoreContext.Provider>
+ );
+};
+
+export function usePlanDetailStore<T>(selector: (s: PlanDetailStore) => T): T {
+ const store = useContext(PlanDetailStoreContext);
+ if (!store) throw new Error("PlanDetailStoreProvider missing");
+ return useStore(store, selector);
+}
+
+export function usePlanDetailStoreApi(): PlanDetailStoreApi {
+ const store = useContext(PlanDetailStoreContext);
+ if (!store) throw new Error("PlanDetailStoreProvider missing");
+ return store;
+}
+```
+
+- [ ] **Step 10: Run test → PASS. Type-check + fix.**
+
+- [ ] **Step 11: Commit**
+
+```
+git commit -m "feat(react): page-scoped plan-detail Zustand store skeleton"
+```
+
+## Task 1.6: Extract `shell/leaveGuard.ts` as pure functions
+
+**Files:**
+- Create: `frontend/src/react/pages/project/plan-detail/shell/leaveGuard.ts`
+- Test: `frontend/src/react/pages/project/plan-detail/shell/__tests__/leaveGuard.test.ts`
+
+- [ ] **Step 1: Write the failing test**
+
+```ts
+import { describe, expect, test } from "vitest";
+import { decideLeaveAction } from "../leaveGuard";
+
+describe("decideLeaveAction", () => {
+ test("allows navigation when no scopes are editing", () => {
+ expect(
+ decideLeaveAction({ editingScopes: {}, isBypassed: false, targetPath: "/x" })
+ ).toEqual({ action: "allow" });
+ });
+
+ test("allows navigation when bypass flag is set", () => {
+ expect(
+ decideLeaveAction({ editingScopes: { title: true }, isBypassed: true, targetPath: "/x" })
+ ).toEqual({ action: "allow" });
+ });
+
+ test("intercepts when an edit scope is open", () => {
+ expect(
+ decideLeaveAction({ editingScopes: { title: true }, isBypassed: false, targetPath: "/x" })
+ ).toEqual({ action: "intercept", pendingTarget: "/x" });
+ });
+
+ test("intercepts when multiple scopes are open", () => {
+ expect(
+ decideLeaveAction({
+ editingScopes: { title: true, description: true },
+ isBypassed: false,
+ targetPath: "/y",
+ })
+ ).toEqual({ action: "intercept", pendingTarget: "/y" });
+ });
+});
+```
+
+- [ ] **Step 2: Run test → FAIL.**
+
+- [ ] **Step 3: Implement `leaveGuard.ts`**
+
+```ts
+export type LeaveAction =
+ | { action: "allow" }
+ | { action: "intercept"; pendingTarget: string };
+
+export function decideLeaveAction(input: {
+ editingScopes: Record<string, true>;
+ isBypassed: boolean;
+ targetPath: string;
+}): LeaveAction {
+ if (input.isBypassed) return { action: "allow" };
+ const hasEditing = Object.keys(input.editingScopes).length > 0;
+ if (!hasEditing) return { action: "allow" };
+ return { action: "intercept", pendingTarget: input.targetPath };
+}
+```
+
+- [ ] **Step 4: Run test → PASS. Type-check + fix. Commit.**
+
+```
+git commit -m "feat(react): extract leave-guard decision as pure function"
+```
+
+## Task 1.7: CI guard against Pinia reads inside plan-detail/ (strict)
+
+**Files:** the existing cross-framework CI guard.
+
+- [ ] **Step 1: Locate the existing guard**
+
+```
+git log --oneline | grep -iE "cross-framework|cross framework" | head -5
+git show <commit> --stat
+```
+
+Identify the script (likely `frontend/scripts/check-react-imports.*` or similar).
+
+- [ ] **Step 2: Add the strict rule**
+
+Append to the existing guard (or create a sibling check) a rule that fails CI when `useVueState` inside `plan-detail/` references a Pinia store hook (`use[A-Z][A-Za-z]+Store`), unless the read is for the Vue router (`useRouter()` / `useRoute()`).
+
+Minimal grep-based form:
+
+```bash
+PLAN_DETAIL_DIR="frontend/src/react/pages/project/plan-detail"
+VIOLATIONS=$(
+ grep -rnE "useVueState\(\s*\(\)\s*=>\s*use[A-Z][A-Za-z]+Store" \
+ "$PLAN_DETAIL_DIR" \
+ --include="*.ts" --include="*.tsx" \
+ | grep -v "useRouter\|useRoute" || true
+)
+if [ -n "$VIOLATIONS" ]; then
+ echo "Pinia reads via useVueState are forbidden in plan-detail/. Use Zustand slices instead:"
+ echo "$VIOLATIONS"
+ exit 1
+fi
+```
+
+If the existing guard is a Node script, port the same logic to JS. No warning-mode flag.
+
+- [ ] **Step 3: Verify locally**
+
+Running the guard NOW (before later phases land) will report violations — they exist throughout the existing code. **Do not commit the guard yet.** Leave the file edited locally; we will commit it only after Phase 5 makes the violation count zero.
+
+Track the edit:
+
+```
+git stash -u -- frontend/<guard-script-path>
+```
+
+We will pop this stash near the end of the work (Task 6.4).
+
+- [ ] **Step 4: No commit yet for the guard.**
+
+## Task 1.8: E2E smoke test for plan-detail (hard gate)
+
+**Files:**
+- Create: `frontend/e2e/plan-detail-smoke.spec.ts` (location depends on existing e2e setup)
+
+- [ ] **Step 1: Find the existing e2e setup**
+
+```
+find frontend -name "playwright.config*" -o -name "*.spec.ts" -path "*e2e*" | head -10
+```
+
+If nothing comes back, **stop and ask the user before continuing** — adding e2e infrastructure is outside this refactor's scope. The user requested the e2e smoke test as a hard gate, so we cannot proceed without it.
+
+- [ ] **Step 2: Add the smoke spec**
+
+`plan-detail-smoke.spec.ts` exercises:
+- open `/projects/<seeded>/plans/<seeded>` for a seeded plan in the e2e environment
+- assert page title renders
+- assert Changes phase is expanded
+- assert at least one spec tab is visible
+
+Keep it minimal — the full golden-path journey remains a manual gate per spec Section 6.
+
+- [ ] **Step 3: Run the spec locally; iterate until it passes.**
+
+- [ ] **Step 4: Commit**
+
+```
+git add frontend/e2e/plan-detail-smoke.spec.ts
+git commit -m "test(e2e): plan detail page renders smoke test"
+```
+
+---
+
+# Phase 2 — Shell + page-hook restructure
+
+**Goal:** Break `usePlanDetailPage` (741 lines) into composed phase-scoped hooks; route data through the page-scoped Zustand store. Move `ProjectPlanDetailPage` into `plan-detail/`. **Behavior is byte-identical.**
+
+**Critical context:** The current `usePlanDetailPage.ts` is the entire page's spine. Read it end-to-end before starting Phase 2. The composition root we produce must call the extracted hooks in the same effect order so React's effect-flush semantics are preserved.
+
+## Task 2.1: Move `ProjectPlanDetailPage.tsx` into `plan-detail/`
+
+**Files:**
+- Move: `frontend/src/react/pages/project/ProjectPlanDetailPage.tsx` → `frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx`
+- Create: `frontend/src/react/pages/project/plan-detail/index.ts`
+- Modify: every import site of `ProjectPlanDetailPage`
+
+- [ ] **Step 1: Find all import sites**
+
+```
+grep -rn "ProjectPlanDetailPage" frontend/src --include="*.ts" --include="*.tsx" --include="*.vue"
+```
+
+- [ ] **Step 2: Move the file**
+
+```
+git mv frontend/src/react/pages/project/ProjectPlanDetailPage.tsx \
+ frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx
+```
+
+- [ ] **Step 3: Create barrel `index.ts`**
+
+```ts
+export { ProjectPlanDetailPage } from "./ProjectPlanDetailPage";
+```
+
+- [ ] **Step 4: Update internal imports inside the moved file**
+
+Paths like `./plan-detail/<x>` become `./<x>`; paths like `../<x>` become `../../<x>`.
+
+- [ ] **Step 5: Update all external import sites**
+
+Each call site changes from `@/react/pages/project/ProjectPlanDetailPage` to `@/react/pages/project/plan-detail`.
+
+- [ ] **Step 6: Type-check + fix + test + manual smoke. Commit.**
+
+```
+git commit -m "refactor(plan-detail): move ProjectPlanDetailPage into plan-detail/"
+```
+
+## Task 2.2: Wrap page with `PlanDetailStoreProvider`
+
+**File:** `frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx`
+
+- [ ] **Step 1: Wrap the JSX**
+
+```tsx
+import { PlanDetailStoreProvider } from "./shared/stores/usePlanDetailStore";
+// ...
+return (
+ <PlanDetailStoreProvider>
+ {/* existing content */}
+ </PlanDetailStoreProvider>
+);
+```
+
+NotFound / PermissionDenied early returns do not need the provider.
+
+- [ ] **Step 2: Type-check + test + manual smoke. Commit.**
+
+```
+git commit -m "refactor(plan-detail): wrap page in PlanDetailStoreProvider"
+```
+
+## Task 2.3: Extract `usePhaseState` hook
+
+**Files:**
+- Create: `shell/hooks/usePhaseState.ts`
+- Modify: `hooks/usePlanDetailPage.ts`
+
+- [ ] **Step 1: Write the hook**
+
+```ts
+import { useCallback } from "react";
+import { usePlanDetailStore } from "../../shared/stores/usePlanDetailStore";
+import type { PlanDetailPhase } from "../../shared/stores/types";
+
+export function usePhaseState() {
+ const activePhases = usePlanDetailStore((s) => s.activePhases);
+ const togglePhase = usePlanDetailStore((s) => s.togglePhase);
+ const expandPhase = usePlanDetailStore((s) => s.expandPhase);
+ const collapsePhase = usePlanDetailStore((s) => s.collapsePhase);
+
+ const isActive = useCallback(
+ (phase: PlanDetailPhase) => activePhases.has(phase),
+ [activePhases]
+ );
+
+ return { activePhases, isActive, togglePhase, expandPhase, collapsePhase };
+}
+```
+
+- [ ] **Step 2: Replace usage in `usePlanDetailPage`** — delete local `activePhases` `useState` + `togglePhase` + `expandPhase`; call `usePhaseState()` instead.
+
+- [ ] **Step 3: Type-check, test, manual smoke. Commit.**
+
+```
+git commit -m "refactor(plan-detail): extract usePhaseState into shell/hooks"
+```
+
+## Task 2.4: Extract `useEditingScopes` hook
+
+**Files:**
+- Create: `shell/hooks/useEditingScopes.ts`
+- Modify: `hooks/usePlanDetailPage.ts`
+
+- [ ] **Step 1: Write the hook**
+
+```ts
+import { useCallback, useMemo } from "react";
+import { usePlanDetailStore } from "../../shared/stores/usePlanDetailStore";
+
+export function useEditingScopes() {
+ const editingScopes = usePlanDetailStore((s) => s.editingScopes);
+ const setEditing = usePlanDetailStore((s) => s.setEditing);
+ const bypassLeaveGuardOnce = usePlanDetailStore((s) => s.bypassLeaveGuardOnce);
+ const pendingLeaveConfirm = usePlanDetailStore((s) => s.pendingLeaveConfirm);
+ const setPendingLeaveConfirm = usePlanDetailStore((s) => s.setPendingLeaveConfirm);
+
+ const isEditing = useMemo(
+ () => Object.keys(editingScopes).length > 0,
+ [editingScopes]
+ );
+
+ const setScopeEditing = useCallback(
+ (scope: string, editing: boolean) => setEditing(scope, editing),
+ [setEditing]
+ );
+
+ return {
+ editingScopes,
+ isEditing,
+ setEditing: setScopeEditing,
+ bypassLeaveGuardOnce,
+ pendingLeaveConfirm,
+ setPendingLeaveConfirm,
+ };
+}
+```
+
+- [ ] **Step 2: Replace usage in `usePlanDetailPage`** — delete `editingScopes` state + `setEditing` callback + `isEditing` derivation + `bypassLeaveGuardOnce` callback + `pendingLeaveConfirm` state. Call `useEditingScopes()`.
+
+- [ ] **Step 3: Type-check, test, manual smoke. Commit.**
+
+```
+git commit -m "refactor(plan-detail): extract useEditingScopes into shell/hooks"
+```
+
+## Task 2.5: Extract `useSidebarMode` hook + `shell/constants.ts`
+
+**Files:**
+- Create: `shell/hooks/useSidebarMode.ts`
+- Create: `shell/constants.ts`
+- Modify: `hooks/usePlanDetailPage.ts`
+
+- [ ] **Step 1: Create `shell/constants.ts`** with the breakpoint and poller constants currently at the top of `usePlanDetailPage.ts` (lines 61-77):
+
+```ts
+export const POLLER_INTERVAL = {
+ // copy the exact values currently in usePlanDetailPage lines 61-67
+} as const;
+
+export const PROJECT_NAME_PREFIX = "projects/";
+
+export const MOBILE_BREAKPOINT_PX = 780;
+export const WIDE_SIDEBAR_BREAKPOINT_PX = 1280;
+export const SIDEBAR_WIDTH_NARROW_PX = 240;
+export const SIDEBAR_WIDTH_WIDE_PX = 336;
+```
+
+- [ ] **Step 2: Create `useSidebarMode.ts`** that owns the container-width effect:
+
+```ts
+import { useEffect, useState } from "react";
+import {
+ MOBILE_BREAKPOINT_PX,
+ SIDEBAR_WIDTH_NARROW_PX,
+ SIDEBAR_WIDTH_WIDE_PX,
+ WIDE_SIDEBAR_BREAKPOINT_PX,
+} from "../constants";
+
+export type PlanDetailSidebarMode = "NONE" | "DESKTOP" | "MOBILE";
+
+export function useSidebarMode(containerRef: React.RefObject<HTMLElement>) {
+ const [sidebarMode, setSidebarMode] = useState<PlanDetailSidebarMode>("NONE");
+ const [isMobileSidebarOpen, setMobileSidebarOpen] = useState(false);
+ const [sidebarWidth, setSidebarWidth] = useState<number>(SIDEBAR_WIDTH_NARROW_PX);
+
+ useEffect(() => {
+ // Move the existing ResizeObserver / width-tracking effect from usePlanDetailPage here verbatim,
+ // calling setSidebarMode / setSidebarWidth based on container width vs the imported breakpoints.
+ }, [containerRef]);
+
+ return { sidebarMode, sidebarWidth, isMobileSidebarOpen, setMobileSidebarOpen };
+}
+```
+
+- [ ] **Step 3: Replace usage in `usePlanDetailPage`.** Update internal callers (`PlanDetailLayout` etc.) to import the constants from `shell/constants` instead of from `hooks/usePlanDetailPage`.
+
+- [ ] **Step 4: Type-check, test, manual smoke (resize window; sidebar mode toggles). Commit.**
+
+```
+git commit -m "refactor(plan-detail): extract useSidebarMode and shell/constants"
+```
+
+## Task 2.6: Extract `useRouteSelection` hook
+
+**Files:**
+- Create: `shell/hooks/useRouteSelection.ts`
+- Modify: `hooks/usePlanDetailPage.ts`
+
+- [ ] **Step 1: Write the hook**
+
+```ts
+import { useEffect } from "react";
+import { usePlanDetailStore } from "../../shared/stores/usePlanDetailStore";
+import type { PlanDetailPhase } from "../../shared/stores/types";
+
+function getRouteQueryString(value: unknown): string | undefined {
+ if (typeof value === "string") return value || undefined;
+ if (Array.isArray(value)) return getRouteQueryString(value[0]);
+ return undefined;
+}
+
+export function useRouteSelection(params: {
+ routeQuery: Record<string, unknown>;
+ specId?: string;
+}) {
+ const setRouteSelection = usePlanDetailStore((s) => s.setRouteSelection);
+
+ const phase = getRouteQueryString(params.routeQuery.phase) as PlanDetailPhase | undefined;
+ const stageId = getRouteQueryString(params.routeQuery.stageId);
+ const taskId = getRouteQueryString(params.routeQuery.taskId);
+
+ useEffect(() => {
+ setRouteSelection({ phase, stageId, taskName: taskId, specId: params.specId });
+ }, [setRouteSelection, phase, stageId, taskId, params.specId]);
+
+ return { phase, stageId, taskId };
+}
+```
+
+- [ ] **Step 2: Replace usage in `usePlanDetailPage`** — remove `convertRouteQuery`, the route-query refs, and the derived `routePhase/Stage/Task`. Call `useRouteSelection({ routeQuery, specId })`.
+
+- [ ] **Step 3: Type-check, test, manual smoke (navigate with `?phase=deploy&taskId=...`). Commit.**
+
+```
+git commit -m "refactor(plan-detail): extract useRouteSelection into shell/hooks"
+```
+
+## Task 2.7: Extract `fetchPlanSnapshot` + `useInitialFetch` + `usePolling`
+
+**Files:**
+- Create: `shell/hooks/fetchPlanSnapshot.ts`
+- Create: `shell/hooks/useInitialFetch.ts`
+- Create: `shell/hooks/usePolling.ts`
+- Modify: `hooks/usePlanDetailPage.ts`
+
+The snapshot fetch + polling lifecycle lives across `usePlanDetailPage.ts` lines 188-376. Riskiest extraction in Phase 2 — effect ordering matters.
+
+- [ ] **Step 1: Re-read source lines 188-376** of `hooks/usePlanDetailPage.ts` end-to-end. Note `fetchPlanDetailSnapshot` (188-285) is a pure async function; the init-fetch and polling effects are coupled by `latestSnapshotRef`.
+
+- [ ] **Step 2: Move `fetchPlanDetailSnapshot` verbatim into `fetchPlanSnapshot.ts`** — rename only if needed. Inside, replace Pinia reads with new app-store calls:
+ - `useDatabaseV1Store.getDatabaseByName(...)` → `useAppStore.getState().fetchDatabase(...)`
+ - `useDBGroupStore.getDBGroupByName(...)` → `useAppStore.getState().fetchDBGroup(...)`
+ - `useSheetV1Store.getSheetByName(...)` → `useAppStore.getState().fetchSheet(...)`
+ - `useProjectV1Store.getProjectByName(...)` → `useAppStore.getState().fetchProject(...)`
+ - `useEnvironmentV1Store` reads → existing `WorkspaceSlice.environmentList`
+
+List every replacement in the commit message.
+
+- [ ] **Step 3: Write `useInitialFetch.ts`**
+
+```ts
+import { useEffect, useRef } from "react";
+import { usePlanDetailStore } from "../../shared/stores/usePlanDetailStore";
+import { fetchPlanSnapshot } from "./fetchPlanSnapshot";
+
+export function useInitialFetch(params: {
+ projectId: string;
+ planId: string;
+ routeQuery: Record<string, unknown>;
+}) {
+ const setSnapshot = usePlanDetailStore((s) => s.setSnapshot);
+ const setLastRefreshTime = usePlanDetailStore((s) => s.setLastRefreshTime);
+ const didRunRef = useRef(false);
+
+ useEffect(() => {
+ if (didRunRef.current) return;
+ didRunRef.current = true;
+ let cancelled = false;
+ fetchPlanSnapshot(params).then((snapshot) => {
+ if (cancelled) return;
+ setSnapshot(snapshot);
+ setLastRefreshTime(Date.now());
+ });
+ return () => {
+ cancelled = true;
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [params.projectId, params.planId]);
+}
+```
+
+- [ ] **Step 4: Write `usePolling.ts`**
+
+Port the predicates `snapshotIsEqual` and `allTasksDoneOrSkipped` from the body of the current `usePlanDetailPage.ts` verbatim — they exist today and define the polling stop condition.
+
+```ts
+import { useEffect } from "react";
+import { POLLER_INTERVAL } from "../constants";
+import {
+ usePlanDetailStore,
+ usePlanDetailStoreApi,
+} from "../../shared/stores/usePlanDetailStore";
+import type { PlanDetailPageSnapshot } from "../../shared/stores/types";
+import { fetchPlanSnapshot } from "./fetchPlanSnapshot";
+
+function snapshotIsEqual(a: PlanDetailPageSnapshot, b: PlanDetailPageSnapshot): boolean {
+ // Lift the existing equality check from the current usePlanDetailPage polling
+ // effect (it compared plan/issue/rollout/taskRuns identity). Reproduce
+ // exactly the comparison used today.
+ return false; // placeholder — replace with ported body
+}
+
+function allTasksDoneOrSkipped(s: PlanDetailPageSnapshot): boolean {
+ // Port the existing "every task done or skipped" predicate. Today it iterates
+ // s.taskRuns and s.rollout?.stages and returns true when no task is in a
+ // pending/running state.
+ return false; // placeholder — replace with ported body
+}
+
+export function usePolling(params: {
+ projectId: string;
+ planId: string;
+ routeQuery: Record<string, unknown>;
+ enabled: boolean;
+}) {
+ const storeApi = usePlanDetailStoreApi();
+ const setSnapshot = usePlanDetailStore((s) => s.setSnapshot);
+ const setLastRefreshTime = usePlanDetailStore((s) => s.setLastRefreshTime);
+
+ useEffect(() => {
+ if (!params.enabled) return;
+
+ let cancelled = false;
+ let timerId: number | undefined;
+
+ const tick = async () => {
+ if (cancelled) return;
+ const snapshot = await fetchPlanSnapshot(params);
+ if (cancelled) return;
+ const current = storeApi.getState().snapshot;
+ if (snapshotIsEqual(current, snapshot)) {
+ timerId = window.setTimeout(tick, POLLER_INTERVAL.default);
+ return;
+ }
+ setSnapshot(snapshot);
+ setLastRefreshTime(Date.now());
+ if (allTasksDoneOrSkipped(snapshot)) return;
+ timerId = window.setTimeout(tick, POLLER_INTERVAL.default);
+ };
+
+ timerId = window.setTimeout(tick, POLLER_INTERVAL.default);
+
+ return () => {
+ cancelled = true;
+ if (timerId !== undefined) window.clearTimeout(timerId);
+ };
+ }, [params.enabled, params.projectId, params.planId, storeApi, setSnapshot, setLastRefreshTime]);
+}
+```
+
+When porting the two predicates, copy the exact comparison and iteration the current `usePlanDetailPage` uses — do not redesign them.
+
+- [ ] **Step 5: Replace usage in `usePlanDetailPage`** — delete the init + polling effects. Call `useInitialFetch(...)` and `usePolling({ ..., enabled: !isCreateMode })`.
+
+- [ ] **Step 6: Type-check, test, manual smoke**: open a plan with a running rollout (page refetches); open a plan with all tasks done (polling stops).
+
+- [ ] **Step 7: Commit**
+
+```
+git commit -m "refactor(plan-detail): extract fetchPlanSnapshot/useInitialFetch/usePolling + slice migration"
+```
+
+## Task 2.8: Extract `useRedirects`
+
+**Files:** create `shell/hooks/useRedirects.ts`. Move the redirect effect from `usePlanDetailPage.ts` (NotFound / PermissionDenied / linked-issue → issue-detail, around lines 396-485) into the hook. Call it from the page hook.
+
+- [ ] Type-check, test, commit.
+
+```
+git commit -m "refactor(plan-detail): extract useRedirects into shell/hooks"
+```
+
+## Task 2.9: Extract `useLeaveGuard`
+
+**Files:** create `shell/hooks/useLeaveGuard.ts` wired to `shell/leaveGuard.ts` (from Task 1.6).
+
+- [ ] **Step 1: Write the hook**
+
+```ts
+import { useEffect } from "react";
+import { router } from "@/router";
+import {
+ usePlanDetailStore,
+ usePlanDetailStoreApi,
+} from "../../shared/stores/usePlanDetailStore";
+import { decideLeaveAction } from "../leaveGuard";
+
+export function useLeaveGuard() {
+ const storeApi = usePlanDetailStoreApi();
+ const setPendingLeaveTarget = usePlanDetailStore((s) => s.setPendingLeaveTarget);
+ const setPendingLeaveConfirm = usePlanDetailStore((s) => s.setPendingLeaveConfirm);
+
+ useEffect(() => {
+ const off = router.beforeEach((to, _from, next) => {
+ const state = storeApi.getState();
+ const decision = decideLeaveAction({
+ editingScopes: state.editingScopes,
+ isBypassed: state.isLeaveGuardBypassed(),
+ targetPath: to.fullPath,
+ });
+
+ if (decision.action === "allow") {
+ next();
+ return;
+ }
+ setPendingLeaveTarget(decision.pendingTarget);
+ setPendingLeaveConfirm(true);
+ next(false);
+ });
+ return () => off();
+ }, [storeApi, setPendingLeaveTarget, setPendingLeaveConfirm]);
+}
+```
+
+- [ ] **Step 2: Replace usage in `usePlanDetailPage`** — delete the `beforeEach` registration and the ref-based dance.
+
+- [ ] **Step 3: Manual smoke**: open title editor, attempt navigation → confirm dialog appears; confirm → navigation proceeds. Commit.
+
+```
+git commit -m "refactor(plan-detail): extract useLeaveGuard wired to pure decideLeaveAction"
+```
+
+## Task 2.10: Extract `useDerivedPlanState` selectors
+
+**Files:**
+- Create: `shell/hooks/useDerivedPlanState.ts`
+- Create: `shell/hooks/types.ts` (move `PlanDetailPageState` shape here)
+
+- [ ] **Step 1: Write the hook** — move the final big `useMemo` of `usePlanDetailPage.ts` (around line 692+) into the hook. Read every store field the returned shape needs via `usePlanDetailStore` selectors.
+
+```ts
+import { useMemo } from "react";
+import { usePlanDetailStore } from "../../shared/stores/usePlanDetailStore";
+import type { PlanDetailPageState } from "./types";
+
+export function useDerivedPlanState(): PlanDetailPageState {
+ const snapshot = usePlanDetailStore((s) => s.snapshot);
+ const activePhases = usePlanDetailStore((s) => s.activePhases);
+ // ... read every store field the returned shape needs
+
+ return useMemo(() => ({
+ // derive readonly, ready, isPlanDone, selectedTaskName, sidebarStatus, etc.
+ // EXACTLY as the current final useMemo of usePlanDetailPage does
+ }), [snapshot, activePhases /* ... */]);
+}
+```
+
+- [ ] **Step 2: Replace the final `useMemo` in `usePlanDetailPage` with `return useDerivedPlanState();`.**
+
+- [ ] **Step 3: Type-check, test, commit.**
+
+```
+git commit -m "refactor(plan-detail): extract useDerivedPlanState selectors"
+```
+
+## Task 2.11: Reduce `usePlanDetailPage` to composition root and move
+
+**Files:**
+- Move: `frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailPage.ts` → `frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.ts`
+- Update every import site of `usePlanDetailPage`, `MOBILE_BREAKPOINT_PX`, `WIDE_SIDEBAR_BREAKPOINT_PX`, `SIDEBAR_WIDTH_NARROW_PX`, `SIDEBAR_WIDTH_WIDE_PX`, `PlanDetailSidebarMode`, `PlanDetailPhase`, `PlanDetailPageSnapshot`, `PlanDetailPageState`
+
+- [ ] **Step 1: Verify size**
+
+```
+wc -l frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailPage.ts
+```
+
+Expected: under 120 lines. The body should be a thin composition:
+
+```ts
+export function usePlanDetailPage(params: PageParams): PlanDetailPageState {
+ useInitialFetch(params);
+ usePolling({ ...params, enabled: !isCreateMode(params) });
+ useRouteSelection(params);
+ useRedirects(params);
+ useLeaveGuard();
+ return useDerivedPlanState();
+}
+```
+
+If still bloated, extract another hook.
+
+- [ ] **Step 2: Move the file**
+
+```
+git mv frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailPage.ts \
+ frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.ts
+```
+
+Fix imports inside.
+
+- [ ] **Step 3: Update every external import site**
+
+```
+grep -rn "from \"@/react/pages/project/plan-detail/hooks/usePlanDetailPage\"" frontend/src
+```
+
+Repoint each match to `@/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage`.
+
+For exports that lived at the old path but now logically live in `shell/constants.ts` or `shared/stores/types.ts`, repoint those imports to their new canonical homes. The hook file should only re-export from itself.
+
+- [ ] **Step 4: Delete the old `hooks/` folder** if empty (`usePlanCheckActions.tsx` and `usePlanDetailSpecValidation.ts` move in Phase 3 — leave the folder until then if they're still there).
+
+- [ ] **Step 5: Type-check, test, manual smoke. Commit.**
+
+```
+git commit -m "refactor(plan-detail): usePlanDetailPage as composition root in shell/hooks"
+```
+
+## Task 2.12: Move `PlanDetailContext`
+
+**Files:**
+- Move: `context/PlanDetailContext.tsx` → `shell/PlanDetailContext.tsx`
+- Update every importer
+
+- [ ] **Step 1: Find importers**
+
+```
+grep -rn "from \"@/react/pages/project/plan-detail/context/PlanDetailContext\"" frontend/src
+grep -rn "from \"../../context/PlanDetailContext\"" frontend/src/react/pages/project/plan-detail
+```
+
+- [ ] **Step 2: Move the file**
+
+```
+git mv frontend/src/react/pages/project/plan-detail/context/PlanDetailContext.tsx \
+ frontend/src/react/pages/project/plan-detail/shell/PlanDetailContext.tsx
+```
+
+- [ ] **Step 3: Update every import to the new path.** Delete the now-empty `context/` folder if applicable.
+
+- [ ] **Step 4: Type-check, test, manual smoke. Commit.**
+
+```
+git commit -m "refactor(plan-detail): move PlanDetailContext into shell/"
+```
+
+---
+
+# Phase 3 — Changes phase
+
+**Goal:** Split `PlanDetailChangesBranch.tsx` (1969) and `PlanDetailStatementSection.tsx` (748) into ~17 focused files under `changes/`. Switch the 10 Pinia reads to the new app-store slices. Apply `/simplify`.
+
+**Reference source line ranges** (from `git show HEAD:frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx` at Phase 3 start — verify before each extraction):
+- `pushSpecDetailRoute`: 143
+- `IsolationLevel` type: 153-167
+- `PlanDetailChangesBranch` main: 168-651
+- `OptionsSection`: 652-1121
+- `TargetsSection`: 1122-1369
+- `TargetSelectorSheet`: 1370-1459
+- `DatabaseAndGroupSelector`: 1460-1530
+- `DatabaseSelector`: 1531-1706
+- `DatabaseGroupSelector`: 1707-1790
+- `DatabaseTarget`: 1791-1822
+- `DatabaseGroupTarget`: 1823-1916
+- `parseStatement`: 1917-1969
+
+## Task 3.1: Extract `parseStatement` with new tests
+
+**Files:**
+- Create: `changes/StatementSection/parseStatement.ts`
+- Create: `changes/StatementSection/__tests__/parseStatement.test.ts`
+- Modify: `components/PlanDetailChangesBranch.tsx`
+
+Pure function; no existing tests — start with TDD.
+
+- [ ] **Step 1: Write the failing test**
+
+Fill these stubs by reading lines 1917-1969 of the source and writing the expected output for each input case:
+
+```ts
+import { describe, expect, test } from "vitest";
+import { parseStatement } from "../parseStatement";
+
+describe("parseStatement", () => {
+ test("returns empty result for empty input", () => {
+ expect(parseStatement("")).toEqual(/* shape per current impl */);
+ });
+
+ test("handles a single statement without trailing semicolon", () => { /* ... */ });
+ test("splits multiple statements by semicolon", () => { /* ... */ });
+ test("preserves semicolons inside string literals", () => { /* ... */ });
+ test("strips line comments", () => { /* ... */ });
+});
+```
+
+- [ ] **Step 2: Run test → FAIL.**
+
+- [ ] **Step 3: Create `parseStatement.ts`** — function body lifted verbatim from lines 1917-1969 of the source.
+
+- [ ] **Step 4: Run test → PASS.**
+
+- [ ] **Step 5: Replace the inline `parseStatement` in `PlanDetailChangesBranch.tsx` with an import. Delete the original lines 1917-1969.**
+
+- [ ] **Step 6: Type-check + existing `PlanDetailChangesBranch.test.tsx`. Commit.**
+
+```
+git commit -m "refactor(plan-detail): extract changes/parseStatement with tests"
+```
+
+## Task 3.2: Extract `DatabaseTarget` and `DatabaseGroupTarget`
+
+**Files:**
+- Create: `changes/TargetsSection/DatabaseTarget.tsx`
+- Create: `changes/TargetsSection/DatabaseGroupTarget.tsx`
+- Modify: `components/PlanDetailChangesBranch.tsx`
+- Update: every external importer of these names
+
+Both are exported today (`export function DatabaseTarget`, `export function DatabaseGroupTarget`).
+
+- [ ] **Step 1: Read the current bodies**
+
+```
+sed -n '1791,1916p' frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx
+```
+
+- [ ] **Step 2: Create the two files** with the lifted function + required imports.
+
+- [ ] **Step 3: Remove the inline definitions from `PlanDetailChangesBranch.tsx`.** Do not add re-exports at the old path.
+
+- [ ] **Step 4: Update every external importer**
+
+```
+grep -rn "DatabaseTarget\|DatabaseGroupTarget" frontend/src --include="*.ts" --include="*.tsx"
+```
+
+Repoint each match to the new path.
+
+- [ ] **Step 5: `/simplify` checklist on the new files.** Type-check + tests + commit.
+
+```
+git commit -m "refactor(plan-detail): extract DatabaseTarget and DatabaseGroupTarget"
+```
+
+## Task 3.3: Extract `DatabaseGroupSelector` (with slice migration)
+
+**Files:** Create `changes/TargetsSection/DatabaseGroupSelector.tsx`.
+
+- [ ] **Step 1: Lift function body** (source lines 1707-1790) into the new file.
+
+- [ ] **Step 2: Replace Pinia reads with app-store calls.**
+
+Before:
+```ts
+const dbGroupStore = useVueState(() => useDBGroupStore());
+const groups = dbGroupStore.dbGroupsByProject(projectName);
+```
+
+After:
+```ts
+import { useAppStore } from "@/react/stores/app";
+// ...
+const listDBGroups = useAppStore((s) => s.listDBGroupsForProject);
+const groupsByName = useAppStore((s) => s.dbGroupsByName);
+useEffect(() => { listDBGroups(projectName); }, [listDBGroups, projectName]);
+const groups = useMemo(
+ () => Object.values(groupsByName).filter((g) => g.name.startsWith(`${projectName}/`)),
+ [groupsByName, projectName]
+);
+```
+
+Verify the resulting list matches what the Pinia store produces today.
+
+- [ ] **Step 3: `/simplify` checklist.**
+
+- [ ] **Step 4: Remove inline definition; import the new file in `PlanDetailChangesBranch.tsx`.**
+
+- [ ] **Step 5: Type-check + test + manual smoke (target selector → switch to group mode → list renders). Commit.**
+
+```
+git commit -m "refactor(plan-detail): extract DatabaseGroupSelector + slice migration"
+```
+
+## Task 3.4: Extract `DatabaseSelector` (with slice migration)
+
+**Files:** Create `changes/TargetsSection/DatabaseSelector.tsx`.
+
+- [ ] **Step 1: Lift source lines 1531-1706.**
+
+- [ ] **Step 2: Replace `useDatabaseV1Store` with `useAppStore`.**
+
+**Plan correction (2026-05-13):** the proto has `listDatabases` (not `searchDatabases`). Task 1.1 added `fetchDatabases` to the slice with shape `{ parent, pageSize, pageToken?, filter?: string, orderBy? }`. The Pinia store's `fetchDatabases` accepts a structured `DatabaseFilter` and compiles it down to the proto's CEL string `filter`; the React slice takes the CEL string directly. If `DatabaseSelector` currently builds a `DatabaseFilter` and passes it to the Pinia store, compile it to a string via the existing `getListDatabaseFilter` helper before calling the slice.
+
+Before:
+```ts
+const dbStore = useVueState(() => useDatabaseV1Store());
+const result = await dbStore.fetchDatabases({ parent, filter, pageSize, pageToken });
+```
+
+After:
+```ts
+import { getListDatabaseFilter } from "@/store/modules/v1/database"; // or a React-local copy
+// ...
+const fetchDatabases = useAppStore((s) => s.fetchDatabases);
+const result = await fetchDatabases({
+ parent,
+ filter: getListDatabaseFilter(filter ?? {}),
+ pageSize,
+ pageToken,
+});
+```
+
+- [ ] **Step 3: `/simplify` checklist.**
+
+- [ ] **Step 4: Remove inline; import; type-check + test + manual smoke (search, select all, load more). Commit.**
+
+```
+git commit -m "refactor(plan-detail): extract DatabaseSelector + slice migration"
+```
+
+## Task 3.5: Extract `DatabaseAndGroupSelector`, `TargetSelectorSheet`, `TargetsSection`
+
+**Files:**
+- Create `changes/TargetsSection/DatabaseAndGroupSelector.tsx` (source 1460-1530)
+- Create `changes/TargetsSection/TargetSelectorSheet.tsx` (source 1370-1459)
+- Create `changes/TargetsSection/TargetsSection.tsx` (source 1122-1369)
+
+Bottom-up extraction order. Each file: lift verbatim, replace Pinia reads with app-store calls, `/simplify`, remove inline definition, type-check + test + manual smoke, commit.
+
+```
+git commit -m "refactor(plan-detail): extract DatabaseAndGroupSelector"
+git commit -m "refactor(plan-detail): extract TargetSelectorSheet"
+git commit -m "refactor(plan-detail): extract TargetsSection"
+```
+
+## Task 3.6: Split `OptionsSection` per directive
+
+**Files:**
+- Create: `changes/OptionsSection/OptionsSection.tsx`
+- Create: `changes/OptionsSection/RoleDirective.tsx`
+- Create: `changes/OptionsSection/TransactionModeDirective.tsx`
+- Create: `changes/OptionsSection/IsolationLevelDirective.tsx`
+- Create: `changes/OptionsSection/PriorBackupToggle.tsx`
+- Create: `changes/OptionsSection/GhostMigrationDirective.tsx`
+
+Source: lines 652-1121.
+
+- [ ] **Step 1: Read the current `OptionsSection` end-to-end.** Identify the five branches (role / transaction-mode / isolation-level / prior-backup / ghost). Each has its own visibility predicate + form UI + onChange wiring.
+
+- [ ] **Step 2: For each directive, create one file** that takes `{ selectedSpec }` and returns `null` when its visibility predicate fails:
+
+```tsx
+// e.g. RoleDirective.tsx
+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
+
+export function RoleDirective({ selectedSpec }: { selectedSpec: Plan_Spec }) {
+ if (!shouldShowRoleDirective(selectedSpec)) return null;
+ // UI + onChange wiring lifted from current OptionsSection's role branch
+ return (/* JSX */);
+}
+
+function shouldShowRoleDirective(spec: Plan_Spec): boolean {
+ // port the predicate currently inline in OptionsSection
+}
+```
+
+Repeat for the other four directives.
+
+- [ ] **Step 3: Rewrite `OptionsSection.tsx` as composition**
+
+```tsx
+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
+import { GhostMigrationDirective } from "./GhostMigrationDirective";
+import { IsolationLevelDirective } from "./IsolationLevelDirective";
+import { PriorBackupToggle } from "./PriorBackupToggle";
+import { RoleDirective } from "./RoleDirective";
+import { TransactionModeDirective } from "./TransactionModeDirective";
+
+export function OptionsSection({ selectedSpec }: { selectedSpec: Plan_Spec }) {
+ return (
+ <div className="space-y-2">
+ <RoleDirective selectedSpec={selectedSpec} />
+ <TransactionModeDirective selectedSpec={selectedSpec} />
+ <IsolationLevelDirective selectedSpec={selectedSpec} />
+ <PriorBackupToggle selectedSpec={selectedSpec} />
+ <GhostMigrationDirective selectedSpec={selectedSpec} />
+ </div>
+ );
+}
+```
+
+- [ ] **Step 4: Remove the inline `OptionsSection`** from `PlanDetailChangesBranch.tsx`; import the new one.
+
+- [ ] **Step 5: `/simplify` each new file (six total).**
+
+- [ ] **Step 6: Type-check + run `utils/options.test.ts` (visibility logic) + run `PlanDetailChangesBranch.test.tsx`. Manual smoke**: open each spec type (DML, DDL, ghost-eligible) and verify the correct directives render.
+
+- [ ] **Step 7: Commit**
+
+```
+git commit -m "refactor(plan-detail): split OptionsSection per directive"
+```
+
+## Task 3.7: Extract `SpecTabStrip`
+
+**Files:** Create `changes/SpecTabStrip.tsx`.
+
+- [ ] **Step 1: Identify the spec-tabs JSX** in `PlanDetailChangesBranch.tsx` (lines 168-651) — typically the first JSX block: numbered tabs, empty-statement markers, add/delete controls.
+
+- [ ] **Step 2: Lift into `SpecTabStrip.tsx`** with props `{ specs, selectedSpecId, onSelect, onAdd, onDelete, canAdd, canDelete }`.
+
+- [ ] **Step 3: Replace inline JSX with `<SpecTabStrip ... />`.**
+
+- [ ] **Step 4: `/simplify`. Type-check + test + manual smoke (add a spec, switch tabs, delete a spec). Commit.**
+
+```
+git commit -m "refactor(plan-detail): extract SpecTabStrip"
+```
+
+## Task 3.8: Split `PlanDetailStatementSection.tsx`
+
+**Files:**
+- Create: `changes/StatementSection/StatementSection.tsx` (composition)
+- Create: `changes/StatementSection/StatementEditor.tsx`
+- Create: `changes/StatementSection/ReleaseFileSummary.tsx`
+- Create: `changes/StatementSection/OversizedSheetNotice.tsx`
+
+Source: `components/PlanDetailStatementSection.tsx` (748 lines).
+
+- [ ] **Step 1: Read end-to-end. Identify the three render branches**: oversized notice / release-backed view / editable editor.
+
+- [ ] **Step 2: Extract `OversizedSheetNotice.tsx`** (smallest first).
+
+- [ ] **Step 3: Extract `ReleaseFileSummary.tsx`** (release-backed read-only view).
+
+- [ ] **Step 4: Extract `StatementEditor.tsx`** (Monaco-backed editor + upload). Replace `useSheetV1Store` with `useAppStore.fetchSheet` / `useAppStore.createSheet`.
+
+- [ ] **Step 5: Rewrite source as `StatementSection.tsx`** composition selecting one of the three children based on spec/sheet state.
+
+- [ ] **Step 6: Move + update importers (no shim)**
+
+```
+git mv frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx \
+ frontend/src/react/pages/project/plan-detail/changes/StatementSection/StatementSection.tsx
+```
+
+```
+grep -rn "PlanDetailStatementSection" frontend/src --include="*.ts" --include="*.tsx"
+```
+
+Repoint each import to the new path, renaming `PlanDetailStatementSection` → `StatementSection` at every call site.
+
+- [ ] **Step 7: Type-check + tests + manual smoke (small SQL, large SQL → oversized notice, release-backed plan). Commit.**
+
+```
+git commit -m "refactor(plan-detail): split StatementSection 4 ways + slice migration"
+```
+
+## Task 3.9: Move `ChangesBranch` and its test
+
+**Files:**
+- Move: `components/PlanDetailChangesBranch.tsx` → `changes/ChangesBranch.tsx`
+- Move: `components/PlanDetailChangesBranch.test.tsx` → `changes/__tests__/ChangesBranch.test.tsx`
+- Update: every external importer
+
+- [ ] **Step 1: Verify size of the source file** — after all earlier extractions it should be ≤400 lines.
+
+```
+wc -l frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx
+```
+
+- [ ] **Step 2: Move**
+
+```
+git mv frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx \
+ frontend/src/react/pages/project/plan-detail/changes/ChangesBranch.tsx
+git mv frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx \
+ frontend/src/react/pages/project/plan-detail/changes/__tests__/ChangesBranch.test.tsx
+```
+
+Rename the export inside from `PlanDetailChangesBranch` to `ChangesBranch`. Update test imports — **no assertion changes**.
+
+- [ ] **Step 3: Update every external importer**
+
+```
+grep -rn "PlanDetailChangesBranch" frontend/src --include="*.ts" --include="*.tsx"
+```
+
+Repoint each match.
+
+- [ ] **Step 4: `/simplify` checklist on `ChangesBranch.tsx`.**
+
+- [ ] **Step 5: Type-check + run `ChangesBranch.test.tsx` (must pass with no assertion changes) + manual full walk of Changes phase. Commit.**
+
+```
+git commit -m "refactor(plan-detail): move ChangesBranch and tests into changes/"
+```
+
+## Task 3.10: Move `PlanDetailChecks`, `PlanDetailDraftChecks`, `SchemaEditorSheet`, Changes-only hooks
+
+For each, `git mv` to its new home, update internal imports, update external importers, apply `/simplify`, no shims.
+
+```
+git mv components/PlanDetailChecks.tsx changes/ChecksSection.tsx
+git mv components/PlanDetailDraftChecks.tsx changes/DraftChecks.tsx
+git mv components/SchemaEditorSheet.tsx changes/SchemaEditorSheet.tsx
+git mv hooks/usePlanCheckActions.tsx changes/hooks/usePlanCheckActions.tsx
+git mv hooks/usePlanDetailSpecValidation.ts changes/hooks/useSpecValidation.ts
+```
+
+After each move, rename internal exports (`PlanDetailChecks` → `ChecksSection`, etc.) and update every importer.
+
+- [ ] **Step 1: Run each `git mv` above.**
+
+- [ ] **Step 2: Update internal imports inside each moved file.**
+
+- [ ] **Step 3: Update every external importer**
+
+```
+grep -rn "PlanDetailChecks\|PlanDetailDraftChecks\|SchemaEditorSheet\|usePlanCheckActions\|usePlanDetailSpecValidation" frontend/src --include="*.ts" --include="*.tsx"
+```
+
+- [ ] **Step 4: `/simplify` each.**
+
+- [ ] **Step 5: Type-check + tests + manual smoke. Commit (one cohesive commit is fine).**
+
+```
+git commit -m "refactor(plan-detail): move Checks/SchemaEditor/hooks into changes/"
+```
+
+---
+
+# Phase 4 — Review phase
+
+**Goal:** Split `PlanDetailApprovalFlow.tsx` (864) into 8 files under `review/`. Migrate the 17 `useVueState` calls to app-store slices and direct Connect calls. Apply `/simplify`.
+
+## Task 4.1: Extract small leaves (`IssueLinkButton`, `ReviewStatusTag`)
+
+For each: identify the function inside `components/PlanDetailApprovalFlow.tsx`, copy to a new file (`review/IssueLinkButton.tsx`, `review/ReviewStatusTag.tsx`), remove inline definition, update any external importer. `/simplify` checklist. Type-check + test + commit per file.
+
+```
+git commit -m "refactor(plan-detail): extract IssueLinkButton"
+git commit -m "refactor(plan-detail): extract ReviewStatusTag"
+```
+
+## Task 4.2: Extract `FutureReviewNotice`
+
+Same procedure → `review/FutureReviewNotice.tsx`.
+
+```
+git commit -m "refactor(plan-detail): extract FutureReviewNotice"
+```
+
+## Task 4.3: Extract `ApproverList` (with slice migration)
+
+**File:** `review/ApproverList.tsx`.
+
+Contains Pinia reads (likely `useUserStore` for user lookups; `useCurrentUserV1` for self).
+
+- [ ] **Step 1: Inspect the subtree's Pinia usages.**
+
+- [ ] **Step 2: If a user-store read is needed and no app-store slice covers it**, stop and add a `UserSlice` (mirror `ProjectSlice` shape) as a new sub-task before continuing. Otherwise read users from data the page snapshot already loaded.
+
+- [ ] **Step 3: Replace `useCurrentUserV1` reads with `useAppStore((s) => s.currentUser)`.**
+
+- [ ] **Step 4: Lift the subtree. `/simplify`. Type-check + test + commit.**
+
+```
+git commit -m "refactor(plan-detail): extract ApproverList + slice migration"
+```
+
+## Task 4.4: Extract `RejectionBanner` (with slice migration)
+
+**File:** `review/RejectionBanner.tsx`. Contains the re-request-review action — keep direct Connect service-client calls.
+
+- [ ] Lift. Replace Pinia reads. `/simplify`. Manual smoke (open a rejected issue → banner renders → re-request flow works). Commit.
+
+```
+git commit -m "refactor(plan-detail): extract RejectionBanner + slice migration"
+```
+
+## Task 4.5: Extract `ApprovalStepItem` (with slice migration)
+
+**File:** `review/ApprovalStepItem.tsx`. Renders one step (avatars, role names — likely Pinia-heavy).
+
+- [ ] Lift. Replace Pinia. `/simplify`. Commit.
+
+```
+git commit -m "refactor(plan-detail): extract ApprovalStepItem + slice migration"
+```
+
+## Task 4.6: Extract `ReviewActions`
+
+**File:** `review/ReviewActions.tsx`. Re-request + label-update actions. Service-client calls stay; replace Pinia reads.
+
+```
+git commit -m "refactor(plan-detail): extract ReviewActions + slice migration"
+```
+
+## Task 4.7: Move `ApprovalFlow` composition and test
+
+- [ ] **Step 1: Move**
+
+```
+git mv frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsx \
+ frontend/src/react/pages/project/plan-detail/review/ApprovalFlow.tsx
+git mv frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.test.tsx \
+ frontend/src/react/pages/project/plan-detail/review/__tests__/ApprovalFlow.test.tsx
+```
+
+Rename export `PlanDetailApprovalFlow` → `ApprovalFlow`. Update test imports — no assertion changes.
+
+- [ ] **Step 2: Update every external importer**
+
+```
+grep -rn "PlanDetailApprovalFlow" frontend/src --include="*.ts" --include="*.tsx"
+```
+
+- [ ] **Step 3: `/simplify` on the composition.**
+
+- [ ] **Step 4: Type-check + tests + manual smoke. Commit.**
+
+```
+git commit -m "refactor(plan-detail): move ApprovalFlow and tests into review/"
+```
+
+## Task 4.8: Create `ReviewBranch.tsx`
+
+**File:** `review/ReviewBranch.tsx`. New file — the Review phase's outer JSX is currently inlined in `ProjectPlanDetailPage`.
+
+- [ ] **Step 1: Identify the Review JSX in `ProjectPlanDetailPage.tsx`** (the block rendering `<ApprovalFlow />` vs. `<FutureReviewNotice />`).
+
+- [ ] **Step 2: Lift into `review/ReviewBranch.tsx`. Replace the page's inline JSX with `<ReviewBranch />`.**
+
+- [ ] **Step 3: Type-check + test + manual smoke. Commit.**
+
+```
+git commit -m "refactor(plan-detail): introduce ReviewBranch composition"
+```
+
+---
+
+# Phase 5 — Deploy phase
+
+**Goal:** Split `PlanDetailDeployFuture.tsx` (437) into 3 files. Split `PlanDetailTaskRolloutActionPanel.tsx` (743) into 7 action-specific files + a panel shell. Rename `Deploy`-prefixed files inside `deploy/`. Apply `/simplify` to touched files.
+
+## Task 5.1: Split `PlanDetailDeployFuture.tsx`
+
+**Files:**
+- Create: `deploy/DeployFuture.tsx` (composition; ~180)
+- Create: `deploy/RolloutRequirementsList.tsx`
+- Create: `deploy/CreateRolloutSheet.tsx`
+
+- [ ] **Step 1: Read source `components/PlanDetailDeployFuture.tsx`.** Three subtrees: requirements list, manual-rollout hint + create button, create-rollout sheet body.
+
+- [ ] **Step 2: Extract `CreateRolloutSheet.tsx`** (sheet body, warning bypass, submit).
+
+- [ ] **Step 3: Extract `RolloutRequirementsList.tsx`** (per-row done/pending/failed/optional state).
+
+- [ ] **Step 4: Rewrite as `deploy/DeployFuture.tsx`** composition.
+
+- [ ] **Step 5: Move + update importers (no shim)**
+
+```
+git mv frontend/src/react/pages/project/plan-detail/components/PlanDetailDeployFuture.tsx \
+ frontend/src/react/pages/project/plan-detail/deploy/DeployFuture.tsx
+grep -rn "PlanDetailDeployFuture" frontend/src --include="*.ts" --include="*.tsx"
+```
+
+Repoint each match; rename the export `PlanDetailDeployFuture` → `DeployFuture`.
+
+- [ ] **Step 6: `/simplify` each. Type-check + test + manual smoke (open a plan needing rollout → Create Rollout → warnings listed). Commit.**
+
+```
+git commit -m "refactor(plan-detail): split DeployFuture into requirements + sheet"
+```
+
+## Task 5.2: Split `PlanDetailTaskRolloutActionPanel.tsx`
+
+**Files:**
+- Create: `deploy/actions/TaskRolloutActionPanel.tsx`
+- Create: `deploy/actions/RunTaskAction.tsx`
+- Create: `deploy/actions/RetryTaskAction.tsx`
+- Create: `deploy/actions/SkipTaskAction.tsx`
+- Create: `deploy/actions/CancelTaskAction.tsx`
+- Create: `deploy/actions/ScheduleTaskAction.tsx`
+- Create: `deploy/actions/SkipPriorBackupAction.tsx`
+
+Source: 743 lines.
+
+- [ ] **Step 1: Read source.** Identify each action's predicate + confirmation sheet + onClick.
+
+- [ ] **Step 2: Move existing co-located action helpers under `deploy/actions/`**
+
+```
+git mv frontend/src/react/pages/project/plan-detail/components/deploy/taskActions.tsx \
+ frontend/src/react/pages/project/plan-detail/deploy/actions/taskActions.tsx
+git mv frontend/src/react/pages/project/plan-detail/components/deploy/taskActions.test.tsx \
+ frontend/src/react/pages/project/plan-detail/deploy/actions/__tests__/taskActions.test.tsx
+git mv frontend/src/react/pages/project/plan-detail/components/deploy/taskActionState.ts \
+ frontend/src/react/pages/project/plan-detail/deploy/actions/taskActionState.ts
+git mv frontend/src/react/pages/project/plan-detail/components/deploy/useDeployTaskStatement.tsx \
+ frontend/src/react/pages/project/plan-detail/deploy/actions/useDeployTaskStatement.tsx
+```
+
+Update test imports — no assertion changes.
+
+- [ ] **Step 3: Create each action file (six files).** Each takes `{ task, taskRun, onConfirm }` and renders `null` if its predicate fails (predicates reuse `taskActionState.ts`).
+
+```tsx
+// deploy/actions/RunTaskAction.tsx
+export function RunTaskAction({ task, taskRun, onConfirm }: ActionProps) {
+ if (!canRun({ task, taskRun, perms })) return null;
+ // confirm sheet + button
+}
+```
+
+- [ ] **Step 4: Create `TaskRolloutActionPanel.tsx`** as the composing shell:
+
+```tsx
+export function TaskRolloutActionPanel({ task, taskRun }: PanelProps) {
+ const onConfirm = useTaskActionConfirm();
+ return (
+ <div className="flex gap-x-2">
+ <RunTaskAction task={task} taskRun={taskRun} onConfirm={onConfirm} />
+ <RetryTaskAction task={task} taskRun={taskRun} onConfirm={onConfirm} />
+ <SkipTaskAction task={task} taskRun={taskRun} onConfirm={onConfirm} />
+ <CancelTaskAction task={task} taskRun={taskRun} onConfirm={onConfirm} />
+ <ScheduleTaskAction task={task} taskRun={taskRun} onConfirm={onConfirm} />
+ <SkipPriorBackupAction task={task} taskRun={taskRun} onConfirm={onConfirm} />
+ </div>
+ );
+}
+```
+
+- [ ] **Step 5: Move the original file + update importers**
+
+```
+git mv frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRolloutActionPanel.tsx \
+ frontend/src/react/pages/project/plan-detail/deploy/actions/TaskRolloutActionPanel.tsx
+grep -rn "PlanDetailTaskRolloutActionPanel" frontend/src --include="*.ts" --include="*.tsx"
+```
+
+Rename export to `TaskRolloutActionPanel`; repoint every importer.
+
+- [ ] **Step 6: `/simplify` each new file.**
+
+- [ ] **Step 7: Type-check + run `taskActions.test.tsx` (no assertion changes) + manual smoke for each action (run / retry / skip with reason / cancel / schedule / skip prior backup). Commit.**
+
+```
+git commit -m "refactor(plan-detail): split TaskRolloutActionPanel per action"
+```
+
+## Task 5.3: Rename remaining `Deploy*` and `PlanDetailTaskRun*` files
+
+For each pair below, `git mv` to the new location, rename the export (drop `Deploy` / `PlanDetail` prefix), update every importer, apply `/simplify`. No shims.
+
+```
+git mv components/deploy/DeployBranch.tsx deploy/DeployBranch.tsx # keep prefix on the branch entry
+git mv components/deploy/DeployTaskList.tsx deploy/tasks/TaskList.tsx
+git mv components/deploy/DeployTaskDetailPanel.tsx deploy/tasks/TaskDetailPanel.tsx
+git mv components/deploy/DeployTaskRow.tsx deploy/tasks/TaskRow.tsx
+git mv components/deploy/DeployTaskItem.tsx deploy/tasks/TaskItem.tsx
+git mv components/deploy/DeployTaskFilter.tsx deploy/tasks/TaskFilter.tsx
+git mv components/deploy/DeployTaskToolbar.tsx deploy/tasks/TaskToolbar.tsx
+git mv components/deploy/DeployTaskStatus.tsx deploy/tasks/TaskStatus.tsx
+git mv components/deploy/DeployLatestTaskRunInfo.tsx deploy/tasks/LatestTaskRunInfo.tsx
+git mv components/deploy/DeployStageCard.tsx deploy/StageCard.tsx
+git mv components/deploy/DeployStageContentView.tsx deploy/StageContentView.tsx
+git mv components/deploy/DeployStageContentSidebar.tsx deploy/StageContentSidebar.tsx
+git mv components/deploy/DeployStageActionSection.tsx deploy/StageActionSection.tsx
+git mv components/deploy/DeployPendingTasksSection.tsx deploy/PendingTasksSection.tsx
+git mv components/deploy/DeployReleaseInfoCard.tsx deploy/ReleaseInfoCard.tsx
+git mv components/deploy/taskRunUtils.ts deploy/utils/taskRunUtils.ts
+git mv components/deploy/types.ts deploy/utils/types.ts
+git mv components/PlanDetailTaskRunTable.tsx deploy/tasks/TaskRunTable.tsx
+git mv components/PlanDetailTaskRunSession.tsx deploy/tasks/TaskRunSession.tsx
+git mv components/PlanDetailTaskRunDetail.tsx deploy/tasks/TaskRunDetail.tsx
+git mv components/PlanDetailRollbackSheet.tsx deploy/tasks/RollbackSheet.tsx
+```
+
+- [ ] **Step 1: Run each move above.** Commit per logical group:
+
+```
+git commit -m "refactor(plan-detail): rename deploy/tasks/* (drop Deploy prefix)"
+git commit -m "refactor(plan-detail): rename deploy/Stage*.tsx (drop Deploy prefix)"
+git commit -m "refactor(plan-detail): rename deploy/{Release,Pending}* and utils"
+git commit -m "refactor(plan-detail): move PlanDetailTaskRun*/RollbackSheet into deploy/tasks/"
+```
+
+- [ ] **Step 2: For each moved file**: update its internal imports, update its exported name, update every external importer. `/simplify` checklist.
+
+- [ ] **Step 3: After all moves**, verify line budgets:
+
+```
+wc -l frontend/src/react/pages/project/plan-detail/deploy/**/*.{ts,tsx} | sort -rn
+```
+
+No file over ~400.
+
+- [ ] **Step 4: Full type-check + test + manual smoke of deploy phase (stage select, run task, skip with reason, cancel, schedule, rollback).**
+
+---
+
+# Phase 6 — Header + Sidebar + cleanup
+
+**Goal:** Split `PlanDetailHeader.tsx` (761) and `PlanDetailMetadataSidebar.tsx` (371). Land the CI guard from Task 1.7 (now that violation count is zero). Add the addendum to the current-state doc. Final verification + open the PR.
+
+## Task 6.1: Split `PlanDetailHeader.tsx`
+
+**Files:**
+- Create: `header/PlanDetailHeader.tsx` (composition)
+- Create: `header/TitleEditor.tsx`
+- Create: `header/DescriptionEditor.tsx`
+- Create: `header/ReadyForReviewPopover.tsx`
+- Create: `header/CreatePlanButton.tsx`
+- Create: `header/CloseReopenActions.tsx`
+- Create: `header/MobileDetailsButton.tsx`
+
+Source: `components/PlanDetailHeader.tsx` (761 lines).
+
+- [ ] **Step 1: Extract leaves bottom-up** (smallest first):
+ - `MobileDetailsButton`
+ - `CreatePlanButton`
+ - `CloseReopenActions`
+ - `TitleEditor` (owns draft + save state)
+ - `DescriptionEditor` (owns draft + collapsed-when-long)
+ - `ReadyForReviewPopover` (largest leaf)
+
+For each: lift, `/simplify`, replace inline with import, type-check + test + commit.
+
+- [ ] **Step 2: Move the composition**
+
+```
+git mv frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx \
+ frontend/src/react/pages/project/plan-detail/header/PlanDetailHeader.tsx
+grep -rn "PlanDetailHeader" frontend/src --include="*.ts" --include="*.tsx"
+```
+
+Update every importer (the exported name `PlanDetailHeader` is kept — Header is the area's public entry).
+
+- [ ] **Step 3: Manual smoke**: edit title, edit description (long + short), Ready-for-Review with required label, close+reopen draft, mobile details button on mobile viewport. Commit.
+
+```
+git commit -m "refactor(plan-detail): split PlanDetailHeader into 7 focused files"
+```
+
+## Task 6.2: Split `PlanDetailMetadataSidebar.tsx`
+
+**Files:**
+- Create: `sidebar/MetadataSidebar.tsx` (composition)
+- Create: `sidebar/CreatedBySection.tsx`
+- Create: `sidebar/StatusSection.tsx`
+- Create: `sidebar/PlanCheckSummary.tsx`
+- Create: `sidebar/ApprovalSummary.tsx`
+- Create: `sidebar/IssueLabelsSection.tsx`
+- Create: `sidebar/RolloutStageProgress.tsx`
+- Create: `sidebar/RefreshControl.tsx`
+- Create: `sidebar/FutureSectionHint.tsx`
+
+Same pattern: lift each section into its own file, rewrite parent as composition.
+
+- [ ] **Step 1: Extract each section file by file.** Per section: lift, `/simplify`, replace inline.
+
+- [ ] **Step 2: Move and rename**
+
+```
+git mv frontend/src/react/pages/project/plan-detail/components/PlanDetailMetadataSidebar.tsx \
+ frontend/src/react/pages/project/plan-detail/sidebar/MetadataSidebar.tsx
+grep -rn "PlanDetailMetadataSidebar" frontend/src --include="*.ts" --include="*.tsx"
+```
+
+Repoint each importer; rename export `PlanDetailMetadataSidebar` → `MetadataSidebar`.
+
+- [ ] **Step 3: Type-check + test + manual smoke. Commit.**
+
+```
+git commit -m "refactor(plan-detail): split MetadataSidebar per section"
+```
+
+## Task 6.3: Delete empty legacy folders
+
+- [ ] **Step 1: Verify they are empty**
+
+```
+find frontend/src/react/pages/project/plan-detail/components -type f
+find frontend/src/react/pages/project/plan-detail/hooks -type f
+find frontend/src/react/pages/project/plan-detail/context -type f
+```
+
+Each command must return no files (everything has been moved).
+
+- [ ] **Step 2: Remove the directories**
+
+```
+git rm -r frontend/src/react/pages/project/plan-detail/components
+git rm -r frontend/src/react/pages/project/plan-detail/hooks
+git rm -r frontend/src/react/pages/project/plan-detail/context
+```
+
+- [ ] **Step 3: Commit**
+
+```
+git commit -m "refactor(plan-detail): remove emptied legacy folders"
+```
+
+## Task 6.4: Land the strict CI guard
+
+Recover the stashed guard from Task 1.7.
+
+- [ ] **Step 1: Verify no Pinia reads remain in plan-detail/**
+
+```
+PLAN_DETAIL_DIR=frontend/src/react/pages/project/plan-detail
+grep -rnE "useVueState\(\s*\(\)\s*=>\s*use[A-Z][A-Za-z]+Store" "$PLAN_DETAIL_DIR" \
+ --include="*.ts" --include="*.tsx" \
+ | grep -v "useRouter\|useRoute"
+```
+
+Must return empty. If anything appears, stop and clean it up before continuing.
+
+- [ ] **Step 2: Pop the stash from Task 1.7**
+
+```
+git stash list # find the index of the stash with the guard edit
+git stash pop <index>
+```
+
+- [ ] **Step 3: Run the guard locally**
+
+It must exit cleanly (zero violations).
+
+- [ ] **Step 4: Commit**
+
+```
+git add <guard-script-path>
+git commit -m "ci: forbid Pinia reads inside plan-detail/ via useVueState"
+```
+
+## Task 6.5: Addendum to current-state doc
+
+**File:** `docs/plans/2026-05-13-plan-detail-current-state.md`
+
+- [ ] **Step 1: Append an "Update — 2026-XX-XX" section** listing:
+ - the refactor landed (link to the PR)
+ - the new file locations replacing the "Implementation Pointers" section
+ - the legacy `components/`, `hooks/`, `context/` folders no longer exist
+
+- [ ] **Step 2: Commit**
+
+```
+git commit -m "docs(plan-detail): addendum noting refactor landed and new paths"
+```
+
+## Task 6.6: Final verification
+
+- [ ] **Step 1: Verify line budgets**
+
+```
+find frontend/src/react/pages/project/plan-detail -type f \( -name "*.ts" -o -name "*.tsx" \) -exec wc -l {} + | sort -rn | head -10
+```
+
+Top file ≤ ~400 lines. `usePlanDetailPage.ts` ≤ 120 lines.
+
+- [ ] **Step 2: Verify folder layout matches spec**
+
+```
+ls -la frontend/src/react/pages/project/plan-detail
+```
+
+Expected top-level: `ProjectPlanDetailPage.tsx`, `index.ts`, `shell/`, `header/`, `changes/`, `review/`, `deploy/`, `sidebar/`, `shared/`. No `components/`, `hooks/`, `context/`.
+
+- [ ] **Step 3: Full type-check + fix + test**
+
+```
+pnpm --dir frontend type-check
+pnpm --dir frontend fix
+pnpm --dir frontend test
+```
+
+- [ ] **Step 4: Run the e2e smoke test from Task 1.8**
+
+Must pass.
+
+- [ ] **Step 5: Manual full-journey walk** (per spec Section 6):
+- open empty draft plan → edit a SQL statement → run checks → Ready for Review (creates issue) → approve the issue → create rollout → run one task → observe task done
+- on desktop wide / desktop narrow / mobile
+
+- [ ] **Step 6: Walk `docs/pre-pr-checklist.md`.**
+
+## Task 6.7: Open the PR
+
+- [ ] **Step 1: Push**
+
+```
+git push -u origin refactor/plan-detail-maintainability
+```
+
+- [ ] **Step 2: Open the PR**
+
+```
+gh pr create --title "refactor(plan-detail): maintainability pass" --body "$(cat <<'EOF'
+## Summary
+
+Maintainability refactor for `frontend/src/react/pages/project/plan-detail/` before resuming feature work.
+
+- Splits 6 oversized files (largest 1969 lines) into ~60 focused files; no file >400 lines after.
+- New folder layout: `shell/ header/ changes/ review/ deploy/ sidebar/ shared/`. Legacy `components/`, `hooks/`, `context/` folders removed.
+- `usePlanDetailPage` reduced from 741 lines to a ~120-line composition of phase-scoped hooks under `shell/hooks/`.
+- Plan-detail's Pinia reads replaced with new app-store Zustand slices (`DatabaseSlice`, `DBGroupSlice`, `SheetSlice`, `InstanceRoleSlice`); a page-scoped Zustand store under `shared/stores/` holds page state (snapshot, phases, editing, selection, polling).
+- CI guard added: `useVueState` inside `plan-detail/` may not reference Pinia store hooks (router excepted).
+- `/simplify` checklist applied per split file (excluding `useMemo`/`useCallback` rewrites per design).
+- New unit tests for `parseStatement`, `decideLeaveAction`, each new app-store slice, and the page-scoped store.
+- E2E smoke test for plan-detail page load.
+
+Design spec: `docs/superpowers/specs/2026-05-13-plan-detail-refactor-design.md`.
+
+Behavior is preserved. All pre-refactor tests pass unchanged.
+
+## Test plan
+- [ ] pnpm --dir frontend type-check
+- [ ] pnpm --dir frontend fix (no diff)
+- [ ] pnpm --dir frontend test
+- [ ] CI guard for Pinia reads passes
+- [ ] E2E smoke test passes
+- [ ] Manual: full golden-path journey on desktop wide / narrow / mobile
+
+🤖 Generated with [Claude Code](https://claude.com/claude-code)
+EOF
+)"
+```
+
+Return the PR URL.
+
+---
+
+# After merge
+
+- [ ] Verify the current-state doc addendum reflects the merged state.
+- [ ] Verify CI runs the strict guard on `main`.
+- [ ] Unblock feature work on plan-detail.
diff --git a/docs/superpowers/specs/2026-05-13-plan-detail-refactor-design.md b/docs/superpowers/specs/2026-05-13-plan-detail-refactor-design.md
new file mode 100644
index 0000000000..1676e089ce
--- /dev/null
+++ b/docs/superpowers/specs/2026-05-13-plan-detail-refactor-design.md
@@ -0,0 +1,602 @@
+# Plan Detail Refactor — Design
+
+Date: 2026-05-13
+Status: design (pre-implementation)
+Companion: [docs/plans/2026-05-13-plan-detail-current-state.md](../../plans/2026-05-13-plan-detail-current-state.md) — behavioral contract this refactor preserves
+
+## Update — 2026-05-13 (post-design)
+
+**Single-PR delivery chosen.** Despite the "Implementation sequencing" section below recommending six independently revertable PRs, the user chose to land the entire refactor in **one PR** at plan-writing time. The phased structure (PR 1 Foundation → PR 6 Header/Sidebar/cleanup) survives as internal commit groupings on a single branch, but there is no inter-PR merge gate.
+
+Consequences:
+- Intermediate compatibility shims are dropped — every consumer is updated in the same diff, so re-exports at old paths are not needed at any step.
+- The CI guard for Pinia reads inside `plan-detail/` is strict from the first commit (no warning-mode flag).
+- "Manual gates" become commit-time checks; no merge-to-main pauses.
+- Rollback is all-or-nothing — there is no PR-N revert option.
+
+The "Implementation sequencing" section below remains as a record of the original recommendation. The implementation plan at [docs/superpowers/plans/2026-05-13-plan-detail-refactor.md](../plans/2026-05-13-plan-detail-refactor.md) reflects the one-PR decision.
+
+## Context
+
+The Plan Detail page (`/projects/:projectId/plans/:planId` and child routes) is a standalone React workflow page. Its current React tree under `frontend/src/react/pages/project/plan-detail/` is 63 files / ~14,300 lines. Six files exceed 700 lines; the largest is `PlanDetailChangesBranch.tsx` at 1,969 lines and packs seven components plus a SQL parser.
+
+The page still reads server state through Pinia stores via `useVueState`, leaving the React migration incomplete. The data hook `usePlanDetailPage` is 741 lines and owns twelve pieces of state plus four refs.
+
+Upcoming feature work on Plan Detail is paused so we can land a maintainability pass first. This document is the design for that pass.
+
+## Goals
+
+1. No file in `plan-detail/` exceeds ~400 lines after the refactor. Anything larger is split into co-located children with a clear name.
+2. Folder layout maps 1:1 to the page's product structure: shell / changes / review / deploy / header / sidebar / shared. A new contributor can find the right file by reading the URL or the page screenshot.
+3. `usePlanDetailPage` becomes a thin composition of phase-scoped hooks. Each hook is independently testable.
+4. Pinia reads inside plan-detail go through new Zustand slices in `frontend/src/react/stores/app/` (database, dbGroup, sheet, instanceRole). The page itself has no `useVueState` calls into Pinia for data — only into the Vue router, where it is unavoidable.
+5. `/simplify` pass on each split unit: drop dead code, collapse duplicate Tailwind / JSX patterns, tighten naming, replace native controls with `react/components/ui` wrappers where supported.
+6. Behavior is preserved. All existing tests pass; no UI/UX changes ship in this refactor.
+
+## Non-goals
+
+- No new product features. The current-state doc is the behavioral contract.
+- No Connect-query infrastructure. Server reads stay imperative through service clients, cached by the new Zustand slices (mirroring the existing app-store pattern).
+- No migration of unrelated Pinia stores. Only the four plan-detail uses get slices.
+- No changes to the Vue router or `ReactPageMount.vue` bridge.
+- No proto / schema changes.
+- No CSS-token overhaul.
+- No removal or rewriting of `useMemo` / `useCallback` calls. Leave existing memoization as-is, even where it looks unnecessary. A separate, measurement-backed pass can revisit later.
+- No new abstractions added "for future use." Two duplications stay duplicated; three earns a helper.
+- No prop-shape changes to `react/components/ui/` components.
+- No Tailwind theme / token changes.
+- No proto field reshaping or selector rewrites.
+- No reordering of effects unless a bug is being fixed (and we are not fixing bugs in this refactor).
+- No batch-rename of i18n keys.
+- No visual-regression / screenshot tests added.
+
+## Target folder layout
+
+```
+frontend/src/react/pages/project/plan-detail/
+├── ProjectPlanDetailPage.tsx (moved here from /pages/project/; thin shell)
+├── index.ts (re-exports the page; nothing else)
+│
+├── shell/
+│ ├── PlanDetailLayout.tsx (three-phase timeline + responsive frame)
+│ ├── PlanDetailContext.tsx (provider only; no logic)
+│ ├── types.ts (PlanDetailPageSnapshot, PlanDetailPhase, breakpoints)
+│ ├── constants.ts (POLLER_INTERVAL, breakpoint pxs, route-query keys)
+│ ├── leaveGuard.ts (pure; navigation-cancel/re-issue logic)
+│ └── hooks/
+│ ├── usePlanDetailPage.ts (composition root, ≤120 lines)
+│ ├── usePlanSnapshot.ts (fetch + poll + refresh)
+│ ├── usePhaseState.ts (activePhases, toggle, expand, collapse)
+│ ├── useEditingScopes.ts (editingScopes, leave-guard wiring)
+│ ├── useRouteSelection.ts (route → selected phase/stage/task/spec)
+│ ├── useSidebarMode.ts (responsive sidebar mode)
+│ └── useDerivedPlanState.ts (selectors → PlanDetailPageState)
+│
+├── header/
+│ ├── PlanDetailHeader.tsx ≤150 composition + layout
+│ ├── TitleEditor.tsx ≤130 inline edit + draft
+│ ├── DescriptionEditor.tsx ≤130 inline edit + collapsed-when-long
+│ ├── ReadyForReviewPopover.tsx ≤220 popover, label pick, warn-ack
+│ ├── CreatePlanButton.tsx ≤80 create mode only
+│ ├── CloseReopenActions.tsx ≤90 draft-only actions
+│ └── MobileDetailsButton.tsx ≤50
+│
+├── changes/
+│ ├── ChangesBranch.tsx ≤200
+│ ├── SpecTabStrip.tsx ≤150
+│ ├── StatementSection/
+│ │ ├── StatementSection.tsx ≤200
+│ │ ├── StatementEditor.tsx ≤220
+│ │ ├── ReleaseFileSummary.tsx ≤140
+│ │ ├── OversizedSheetNotice.tsx ≤60
+│ │ └── parseStatement.ts ≤80 pure (was inline at line 1917)
+│ ├── TargetsSection/
+│ │ ├── TargetsSection.tsx ≤180
+│ │ ├── TargetSelectorSheet.tsx ≤180
+│ │ ├── DatabaseAndGroupSelector.tsx ≤120
+│ │ ├── DatabaseSelector.tsx ≤260
+│ │ ├── DatabaseGroupSelector.tsx ≤200
+│ │ ├── DatabaseTarget.tsx ≤80
+│ │ └── DatabaseGroupTarget.tsx ≤80
+│ ├── OptionsSection/
+│ │ ├── OptionsSection.tsx ≤180
+│ │ ├── RoleDirective.tsx ≤120
+│ │ ├── TransactionModeDirective.tsx ≤100
+│ │ ├── IsolationLevelDirective.tsx ≤100
+│ │ ├── PriorBackupToggle.tsx ≤90
+│ │ └── GhostMigrationDirective.tsx ≤110
+│ ├── ChecksSection.tsx ≤180 was PlanDetailChecks
+│ ├── DraftChecks.tsx ≤120 was PlanDetailDraftChecks
+│ ├── SchemaEditorSheet.tsx ≤300 /simplify pass only
+│ └── hooks/
+│ ├── usePlanCheckActions.tsx
+│ └── useSpecValidation.ts (was usePlanDetailSpecValidation)
+│
+├── review/
+│ ├── ReviewBranch.tsx ≤150
+│ ├── ApprovalFlow.tsx ≤200
+│ ├── ApprovalStepItem.tsx ≤180
+│ ├── ApproverList.tsx ≤140
+│ ├── RejectionBanner.tsx ≤180
+│ ├── ReviewStatusTag.tsx ≤90
+│ ├── ReviewActions.tsx ≤140
+│ ├── IssueLinkButton.tsx ≤60
+│ └── FutureReviewNotice.tsx ≤80
+│
+├── deploy/
+│ ├── DeployBranch.tsx (already exists; trimmed)
+│ ├── DeployFuture.tsx ≤180
+│ ├── RolloutRequirementsList.tsx ≤180 extracted from DeployFuture
+│ ├── CreateRolloutSheet.tsx ≤220 extracted from DeployFuture
+│ ├── StageNav.tsx (was inline in DeployBranch)
+│ ├── StageCard.tsx (already exists)
+│ ├── StageContentView.tsx (already exists; trimmed)
+│ ├── StageContentSidebar.tsx (already exists; trimmed)
+│ ├── StageActionSection.tsx (already exists)
+│ ├── ReleaseInfoCard.tsx (renamed from DeployReleaseInfoCard)
+│ ├── PendingTasksSection.tsx (already exists)
+│ ├── tasks/
+│ │ ├── TaskList.tsx
+│ │ ├── TaskRow.tsx
+│ │ ├── TaskItem.tsx
+│ │ ├── TaskFilter.tsx
+│ │ ├── TaskToolbar.tsx
+│ │ ├── TaskStatus.tsx
+│ │ ├── TaskDetailPanel.tsx
+│ │ ├── TaskRunTable.tsx
+│ │ ├── TaskRunSession.tsx
+│ │ ├── TaskRunDetail.tsx
+│ │ ├── LatestTaskRunInfo.tsx
+│ │ └── RollbackSheet.tsx
+│ ├── actions/
+│ │ ├── TaskRolloutActionPanel.tsx ≤220 panel shell
+│ │ ├── RunTaskAction.tsx ≤140
+│ │ ├── RetryTaskAction.tsx ≤120
+│ │ ├── SkipTaskAction.tsx ≤160
+│ │ ├── CancelTaskAction.tsx ≤120
+│ │ ├── ScheduleTaskAction.tsx ≤160
+│ │ ├── SkipPriorBackupAction.tsx ≤120
+│ │ ├── taskActions.tsx (keep)
+│ │ ├── taskActionState.ts (keep)
+│ │ └── useDeployTaskStatement.tsx (keep)
+│ └── utils/
+│ ├── taskRunUtils.ts
+│ └── types.ts
+│
+├── sidebar/
+│ ├── MetadataSidebar.tsx ≤120 composition
+│ ├── CreatedBySection.tsx ≤60
+│ ├── StatusSection.tsx ≤80
+│ ├── PlanCheckSummary.tsx ≤100
+│ ├── ApprovalSummary.tsx ≤80
+│ ├── IssueLabelsSection.tsx ≤90
+│ ├── RolloutStageProgress.tsx ≤100
+│ ├── RefreshControl.tsx ≤80
+│ └── FutureSectionHint.tsx ≤50
+│
+└── shared/
+ ├── stores/ (page-scoped Zustand store)
+ │ ├── usePlanDetailStore.ts
+ │ ├── snapshotSlice.ts
+ │ ├── phaseSlice.ts
+ │ ├── editingSlice.ts
+ │ ├── selectionSlice.ts
+ │ ├── pollingSlice.ts
+ │ └── types.ts
+ └── utils/
+ ├── createPlan.ts
+ ├── directiveUtils.ts
+ ├── header.ts
+ ├── invalidate.ts (cross-store mutation invalidation map)
+ ├── localSheet.ts
+ ├── options.ts
+ ├── phaseSummary.ts
+ ├── planCheck.ts
+ ├── rolloutPreview.ts
+ ├── sidebarStatus.ts
+ ├── spec.ts
+ ├── specMutation.ts
+ ├── sqlAdvice.ts
+ ├── targets.ts
+ └── __tests__/ (existing *.test.ts files moved here)
+```
+
+### Naming conventions
+
+- Drop the redundant `PlanDetail` prefix inside `plan-detail/`. The folder already namespaces.
+- Drop the redundant `Deploy` prefix inside `deploy/`. Same reason.
+- `useXxxStore` is reserved for Zustand stores. Local React hooks use `useXxx`.
+- `Xxx.tsx` for components; `xxx.ts` for pure utilities; `useXxx.ts(x)` for hooks.
+
+### Compatibility shims
+
+PRs 3–5 leave one-line re-exports at the old paths so any straggling import keeps working:
+
+```ts
+// plan-detail/components/PlanDetailHeader.tsx (shim during migration)
+export { PlanDetailHeader } from "../header/PlanDetailHeader";
+```
+
+PR 6 deletes all shims.
+
+## State architecture
+
+Three layers, each with one job.
+
+```
+┌─────────────────────────────────────────────────────────────┐
+│ Layer 1: Global app-store slices (react/stores/app/) │
+│ Pinia replacements; cross-page caches; long-lived │
+└─────────────────────────────────────────────────────────────┘
+ ▲
+ │ read-only / loader calls
+ │
+┌─────────────────────────────────────────────────────────────┐
+│ Layer 2: Page-scoped Zustand store (plan-detail/shared/) │
+│ snapshot · phase · editing · selection · polling │
+│ lifetime = one ProjectPlanDetailPage instance │
+└─────────────────────────────────────────────────────────────┘
+ ▲
+ │ selectors via shallow equality
+ │
+┌─────────────────────────────────────────────────────────────┐
+│ Layer 3: Component-local state (useState / useReducer) │
+│ transient UI: input drafts, popover open, modal step │
+└─────────────────────────────────────────────────────────────┘
+```
+
+### Layer 1 — new global app-store slices
+
+Add four slices in `frontend/src/react/stores/app/`, following the existing pattern (state + request-promise dedup + loader fns):
+
+```ts
+// database.ts
+export type DatabaseSlice = {
+ databasesByName: Record<string, Database>;
+ databaseRequests: Record<string, Promise<Database | undefined>>;
+ databaseErrorsByName: Record<string, Error | undefined>;
+ fetchDatabase: (name: string) => Promise<Database | undefined>;
+ batchFetchDatabases: (names: string[]) => Promise<Database[]>;
+ searchDatabases: (params: DatabaseSearchParams) => Promise<{
+ databases: Database[];
+ nextPageToken?: string;
+ }>;
+};
+
+// dbGroup.ts
+export type DBGroupSlice = {
+ dbGroupsByName: Record<string, DatabaseGroup>;
+ dbGroupRequests: Record<string, Promise<DatabaseGroup | undefined>>;
+ fetchDBGroup: (name: string) => Promise<DatabaseGroup | undefined>;
+ listDBGroupsForProject: (project: string) => Promise<DatabaseGroup[]>;
+};
+
+// sheet.ts
+export type SheetSlice = {
+ sheetsByName: Record<string, Sheet>;
+ sheetRequests: Record<string, Promise<Sheet | undefined>>;
+ fetchSheet: (name: string, raw?: boolean) => Promise<Sheet | undefined>;
+ createSheet: (parent: string, sheet: Sheet) => Promise<Sheet>;
+};
+
+// instanceRole.ts
+export type InstanceRoleSlice = {
+ rolesByInstance: Record<string, InstanceRole[]>;
+ roleRequests: Record<string, Promise<InstanceRole[]>>;
+ fetchInstanceRoles: (instance: string) => Promise<InstanceRole[]>;
+};
+```
+
+Only port the methods plan-detail actually calls; do not migrate the full Pinia surface. Each new slice gets a unit test that proves request dedup works (the property the Pinia stores guarantee today).
+
+**Cache coexistence during migration.** Pinia stores remain the source of truth for Vue pages. The new Zustand slices fetch independently. We accept a duplicate cache for the migration window. Mutations from plan-detail invalidate both: the slice's own cache and, where the Vue layer cares, a call into the Pinia store. The page has a tiny `shared/utils/invalidate.ts` helper that lists the cross-store invalidations needed by each mutation, so the surface is auditable.
+
+### Layer 2 — page-scoped Zustand store
+
+Replaces the `useState` cluster inside `usePlanDetailPage` (snapshot, activePhases, editingScopes, isRefreshing, isRunningChecks, lastRefreshTime, pendingLeaveConfirm, plus the four refs). Created fresh per page mount via React context, so navigating away and back gives a clean store.
+
+```ts
+// shared/stores/usePlanDetailStore.ts
+const createPlanDetailStore = () =>
+ create<PlanDetailStore>()((...a) => ({
+ ...createSnapshotSlice(...a),
+ ...createPhaseSlice(...a),
+ ...createEditingSlice(...a),
+ ...createSelectionSlice(...a),
+ ...createPollingSlice(...a),
+ }));
+
+const PlanDetailStoreContext =
+ createContext<ReturnType<typeof createPlanDetailStore> | null>(null);
+
+export const PlanDetailStoreProvider = ({ children }: { children: ReactNode }) => {
+ const [store] = useState(createPlanDetailStore);
+ return (
+ <PlanDetailStoreContext.Provider value={store}>
+ {children}
+ </PlanDetailStoreContext.Provider>
+ );
+};
+
+export function usePlanDetailStore<T>(selector: (s: PlanDetailStore) => T): T {
+ const store = useContext(PlanDetailStoreContext);
+ if (!store) throw new Error("PlanDetailStoreProvider missing");
+ return useStore(store, selector);
+}
+```
+
+Slices:
+
+- `SnapshotSlice` — `snapshot`, `setSnapshot`, `patchSnapshot`, `refresh()`
+- `PhaseSlice` — `activePhases: Set<Phase>`, `togglePhase`, `expandPhase`, `collapsePhase`
+- `EditingSlice` — `editingScopes: Record<string, true>`, `setEditing`, `isEditing` selector, `bypassLeaveGuardOnce`, `pendingLeaveConfirm`, `resolveLeaveConfirm`, `pendingLeaveTarget`
+- `SelectionSlice` — mirrors URL-derived selection so components don't re-parse route query every render: `selectedSpecId`, `selectedStageId`, `selectedTaskName`, `routePhase`
+- `PollingSlice` — `isRefreshing`, `isRunningChecks`, `lastRefreshTime`, `pollTimerId`, `startPolling`, `stopPolling`
+
+Why a Zustand store instead of more React state: ~12 pieces of state read by many leaves (context re-render storm if pushed through React context); stable getters needed by the polling timer and leave guard (uniform with `getState()` instead of refs); reducer-like actions live next to the state they touch.
+
+### Layer 3 — component-local state
+
+Anything that does not outlive a single subtree stays local: search-input drafts, modal open/closed booleans, the wizard step cursor inside `CreateRolloutSheet`, draft strings for `TitleEditor` / `DescriptionEditor`. The rule: if only one component reads it and it dies with the component, it stays local.
+
+### What `usePlanDetailPage` becomes
+
+```ts
+// shell/hooks/usePlanDetailPage.ts (≤120 lines target)
+export function usePlanDetailPage(params: PageParams): PlanDetailPageState {
+ useInitialFetch(params); // populates SnapshotSlice once
+ usePolling(); // owns the timer; respects done-state
+ useRouteSelection(params); // syncs SelectionSlice from route
+ useRedirects(params); // NotFound / PermissionDenied / linked-issue redirect
+ useLeaveGuard(); // wires editing → router beforeEach
+ return useDerivedPlanState(); // selectors only; returns PlanDetailPageState
+}
+```
+
+Each `useXxx` lives in its own file under `shell/hooks/`, ≤120 lines, with its own test.
+
+### Vue router exception
+
+The Vue router and its `route.query` reactive object stay; we keep `useVueState` for those. Rule enforced by CI: `useVueState` may only wrap Vue router/route inside `plan-detail/`. Any other Pinia read is a CI failure. We add a grep-based guard mirroring the existing cross-framework guard (commit `2a806ce64d`).
+
+## Per-area splits
+
+Line budgets below are caps, not minimums. If a unit comes in well under, that is fine. If a unit balloons during simplification, split further.
+
+### Header
+
+Today: `PlanDetailHeader.tsx` (761 lines) holds title editor, description editor, the Ready-for-Review popover with its validation + label-pick + warning-ack tree, the Create button, Close/Reopen actions, mobile-details trigger, and a composing wrapper.
+
+After: 7 files in `header/`. Each editor owns its own draft state and "saving" boolean. The popover lifts out unchanged in this pass; its validation chain is simplified in Section 5 cleanup.
+
+### Changes
+
+Today: `PlanDetailChangesBranch.tsx` (1969) + `PlanDetailStatementSection.tsx` (748). The biggest payoff.
+
+After: ~17 files split four ways — Statement / Targets / Options / Checks. Each section reads `selectedSpec` from the store and pushes mutations back through `patchSnapshot`; no cross-section prop drilling. Per-directive splits in Options because each directive has its own visibility rules and the future-feature path almost certainly adds directives. `parseStatement` extracted as a pure file with its first unit tests.
+
+### Review
+
+Today: `PlanDetailApprovalFlow.tsx` (864). Approval steps, approver list, rejection banner with re-request action, status tag, issue link button, future-state guidance for plans without an issue.
+
+After: 8 files in `review/`. The 17 `useVueState` calls cluster in the approver-list and rejection-banner subtrees, so splitting those lets us migrate them piecewise.
+
+### Deploy
+
+Today: mostly already nested under `deploy/`. Two big files remain: `PlanDetailDeployFuture.tsx` (437) and `PlanDetailTaskRolloutActionPanel.tsx` (743).
+
+After: `DeployFuture` splits 3 ways (composition / requirements list / create-rollout sheet). `TaskRolloutActionPanel` splits into a panel shell + one file per action type (run / retry / skip / cancel / schedule / skip-prior-backup); each action owns its own confirmation sheet. Other deploy files get renamed (drop `Deploy` prefix) and a `/simplify` pass; no further structural splits.
+
+### Sidebar
+
+Today: `PlanDetailMetadataSidebar.tsx` (371) — under the 400-line cap, but every section is independently useful and the future-feature path almost certainly adds sidebar sections.
+
+After: 8 files in `sidebar/`. Adding a section becomes a one-file change.
+
+### Shell + page hook
+
+`usePlanDetailPage` splits 7 ways per Section 3. Leave-guard logic extracted as `shell/leaveGuard.ts` (pure functions over the editing slice) with a unit test for the cancel-then-confirm sequence.
+
+## `/simplify` pass scope
+
+### What `/simplify` runs over
+
+Only the units that were split or moved in the per-area work above. A file untouched in the structural pass does not get a simplification pass in this refactor. The `shared/utils/` folder is mostly already pure and tested; run `/simplify` over it only where its tests stay green without modification.
+
+### In-scope cleanups
+
+1. Replace native controls with `react/components/ui/` wrappers, where the shared component already supports the needed behavior.
+2. Collapse duplicated Tailwind class strings via `cva` variant or `cn(...)` helper inside the same file.
+3. Drop dead branches the type system already proves unreachable.
+4. Drop dead state — `useState` whose setter is never called, refs no component reads, props no caller passes.
+5. Tighten naming where the new name is unambiguously better and the rename stays inside the file.
+6. Inline single-use one-line helpers that obscure rather than clarify.
+7. Replace `space-x-*` button rows with `gap-x-2` per AGENTS.md.
+8. Drop empty-object i18n keys per AGENTS.md.
+
+### Out-of-scope cleanups
+
+(Listed alongside the global non-goals above.) Notably: no `useMemo` / `useCallback` removal; no new abstractions added "for future use"; no prop-shape changes to shared UI components.
+
+### Per-file checklist
+
+```
+[ ] Imports: organized, no unused, no deep relative paths
+[ ] Native controls replaced with react/components/ui where supported
+[ ] Tailwind: gap-x for button rows; no redundant arbitrary values; no
+ duplicated long class strings (collapse with cn / cva inside file)
+[ ] State: every useState / useRef is read; every prop is consumed
+[ ] Effects: dependencies honest; no missing deps; no spurious deps
+[ ] Branches: switch defaults / unreachable else removed
+[ ] Naming: file-local renames only, where the new name is clearly better
+[ ] Comments: drop comments that restate the code; keep WHY comments
+[ ] i18n: no hardcoded user-facing strings; no empty-object keys
+[ ] Tests: existing tests still pass without modification
+```
+
+Same list per file; no judgment beyond it.
+
+### Ordering inside a commit
+
+For each split unit:
+
+1. Move/split first — copy code to its new file, leave behavior identical, get tests green.
+2. Simplify second — run the checklist over the new file only.
+
+Doing simplification before splitting produces edits the split erases.
+
+## Testing strategy
+
+The refactor's success criterion is "behavior preserved," so tests exist to detect regressions, not verify new behavior.
+
+### Layer A — existing tests, unchanged
+
+Existing tests in `plan-detail/`:
+
+```
+utils/sqlAdvice.test.ts
+utils/header.test.ts
+utils/phaseSummary.test.ts
+utils/targets.test.ts
+utils/sidebarStatus.test.ts
+utils/options.test.ts
+utils/planCheck.test.ts
+utils/spec.test.ts
+components/PlanDetailChangesBranch.test.tsx
+components/PlanDetailApprovalFlow.test.tsx
+components/deploy/taskActions.test.tsx
+```
+
+These tests move alongside their subjects; their import paths are fixed. **No assertion or setup code changes.** If a test starts failing after a move, the refactor introduced a regression — fix the regression, not the test. The two component tests continue to test the composed parent shells (`ChangesBranch.tsx`, `ApprovalFlow.tsx`).
+
+### Layer B — new unit tests for newly-exposed pure logic
+
+1. `changes/StatementSection/parseStatement.ts` — first unit tests (empty, single, multiple, with comments, with semicolons in strings).
+2. `shell/leaveGuard.ts` — tests for editing→navigate→cancel, editing→navigate→confirm, no-edit→navigate→passthrough, bypass-once flag.
+3. `shell/hooks/useDerivedPlanState.ts` — priority ladder `creating → closed/deleted → canceled issue → rollout status → review status → draft` from the current-state doc.
+4. New Zustand app-store slices — each gets a request-dedup test.
+
+Cap: roughly 8–12 new unit-test files. More than that means we are testing plumbing instead of behavior.
+
+### Layer C — one end-to-end smoke test
+
+One Playwright-style smoke test walking the page's golden path:
+
+```
+open empty draft plan → edit a SQL statement → run checks →
+Ready for Review (creates issue) → approve the issue →
+create rollout → run one task → observe task done
+```
+
+If no plan-detail e2e exists today, it is added in PR 1 and stays after the refactor — not just scaffolding.
+
+### Per-slice merge gate
+
+```
+[ ] Layer A: all moved tests pass with no assertion changes
+[ ] Layer B: any newly-extracted pure logic has unit tests
+[ ] Layer C: the e2e smoke test passes
+[ ] pnpm --dir frontend type-check passes
+[ ] pnpm --dir frontend fix produces no diff
+[ ] Manual: open the page in dev, walk the journey for any visibly-touched area
+```
+
+The manual step is non-negotiable per AGENTS.md. Each PR description lists which areas were manually exercised, on desktop wide / desktop narrow / mobile.
+
+### Not included
+
+- No visual-regression / screenshot tests.
+- No new test framework.
+- No tests for Zustand selectors directly; they are exercised through components.
+- No tests for file moves themselves; the compiler catches broken imports.
+
+## Implementation sequencing
+
+One spec; six PRs. Each PR is independently revertable.
+
+### PR 1: Foundation
+
+Add the new global Zustand slices (database, dbGroup, sheet, instanceRole) and the page-scoped store skeleton. No call-site changes yet.
+
+- New: `react/stores/app/{database,dbGroup,sheet,instanceRole}.ts` + slice tests
+- New: `plan-detail/shared/stores/*` (empty slices, provider, hook)
+- New: `plan-detail/shell/leaveGuard.ts` + tests
+- New: e2e smoke test
+- CI guard updated to forbid Pinia reads inside `plan-detail/` (lands here so later PRs cannot backslide)
+
+Risk: ~zero — no existing code paths changed.
+
+### PR 2: Shell + page-hook restructure
+
+Break `usePlanDetailPage` into `shell/hooks/*`; route data through the page-scoped store. Move `ProjectPlanDetailPage.tsx` into `plan-detail/`.
+
+- Touched: `usePlanDetailPage`, `ProjectPlanDetailPage`, `PlanDetailContext`
+- Behavior: identical
+- Risk: high — page's data spine. PR 1's groundwork makes it tractable.
+
+### PR 3: Changes phase
+
+Split the 1969-line file. Switch its data reads to new app-store slices. `/simplify` per the checklist.
+
+- Touched: `PlanDetailChangesBranch`, `PlanDetailStatementSection`, related utils
+- New: ~17 files under `changes/`
+- Risk: high — biggest payoff and biggest diff. Existing component tests are the safety net.
+
+### PR 4: Review phase
+
+Split `PlanDetailApprovalFlow`. Switch its 17 Pinia reads to slices.
+
+- Touched: `PlanDetailApprovalFlow` → `review/*`
+- Risk: medium — clear seams, existing tests.
+
+### PR 5: Deploy phase
+
+Split `PlanDetailDeployFuture` + `PlanDetailTaskRolloutActionPanel`. Rename `Deploy`-prefixed files inside `deploy/`. `/simplify` pass.
+
+- Touched: `deploy/*` (already partly nested)
+- Risk: medium.
+
+### PR 6: Header + Sidebar + cleanup
+
+Split `PlanDetailHeader` and `PlanDetailMetadataSidebar`. Remove compatibility shim re-exports. Drop the `PlanDetail` prefix on the renamed-but-not-yet-cleaned files.
+
+- Risk: low — header/sidebar are the most self-contained.
+
+### Ordering rationale
+
+- PR 1 is foundation: nothing else compiles cleanly without it. Safe to sit on `main` for days.
+- PR 2 before any phase PR: phase splits read from the page-scoped store; without PR 2, every phase is rewritten twice.
+- Changes before Review before Deploy by payoff and risk. Header / Sidebar last because they are most self-contained.
+
+### Concurrent feature work
+
+Feature work on plan-detail is paused for the duration. If a feature must land mid-refactor:
+
+- It lands on top of the most-recently-merged refactor PR.
+- It uses the new structure if its area is already refactored; old structure otherwise.
+- No rebasing the in-flight refactor PR onto the new feature.
+
+### Rough timeline
+
+- PR 1: 0.5 day
+- PR 2: 2 days
+- PR 3: 2–3 days
+- PR 4: 1–1.5 days
+- PR 5: 1–1.5 days
+- PR 6: 1 day
+
+Total ~8–10 working days. Longer if PR 2 or PR 3 surfaces a snag.
+
+### Rollback
+
+Each PR is revertable on its own. `git revert` of PR N restores prior behavior; PRs N+1+ rebase or also revert. No feature-flag rollbacks.
+
+## Definition of done
+
+- Every file in `plan-detail/` ≤ ~400 lines (documented exceptions if any).
+- Folder layout matches the target tree above.
+- `usePlanDetailPage.ts` ≤ 120 lines.
+- Zero `useVueState` calls into Pinia inside `plan-detail/` (router uses allowed). CI guard enforces.
+- All pre-refactor tests pass unchanged. New unit + e2e tests pass.
+- Manual walk of the journey in the current-state doc: golden path + at least one branch per phase, on desktop wide / desktop narrow / mobile.
+- The current-state doc (`docs/plans/2026-05-13-plan-detail-current-state.md`) gets a short addendum noting the refactor landed and pointing at the new file locations.
diff --git a/frontend/src/react/mount.ts b/frontend/src/react/mount.ts
index 3b8b8e9580..b12b75fdfb 100644
--- a/frontend/src/react/mount.ts
+++ b/frontend/src/react/mount.ts
@@ -1,7 +1,10 @@
// Use import.meta.glob so vue-tsc does not follow the import into React .tsx files.
// Vite resolves the glob at build time and creates a lazy chunk for the matched module.
const settingsPageLoaders = import.meta.glob("./pages/settings/*.tsx");
-const projectPageLoaders = import.meta.glob("./pages/project/*.tsx");
+const projectPageLoaders = import.meta.glob([
+ "./pages/project/*.tsx",
+ "./pages/project/plan-detail/ProjectPlanDetailPage.tsx",
+]);
const pluginComponentLoaders = import.meta.glob(
"./plugins/agent/components/AgentWindow.tsx"
);
@@ -64,6 +67,7 @@ async function loadCoreDeps() {
const pageDirs = [
"./pages/settings",
"./pages/project",
+ "./pages/project/plan-detail",
"./plugins/agent/components",
"./pages/workspace",
"./pages/auth",
diff --git a/frontend/src/react/pages/project/ProjectPlanDetailPage.test.tsx b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.test.tsx
similarity index 89%
rename from frontend/src/react/pages/project/ProjectPlanDetailPage.test.tsx
rename to frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.test.tsx
index c71c269095..50ad0b3cf0 100644
--- a/frontend/src/react/pages/project/ProjectPlanDetailPage.test.tsx
+++ b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.test.tsx
@@ -3,7 +3,7 @@ import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { State } from "@/types/proto-es/v1/common_pb";
-import type { PlanDetailPageState } from "./plan-detail/hooks/usePlanDetailPage";
+import type { PlanDetailPageState } from "./shell/hooks/types";
(
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
@@ -68,19 +68,19 @@ vi.mock("@/react/lib/utils", () => ({
classes.filter(Boolean).join(" "),
}));
-vi.mock("./plan-detail/components/deploy/DeployBranch", () => ({
+vi.mock("./components/deploy/DeployBranch", () => ({
DeployBranch: () => null,
}));
-vi.mock("./plan-detail/components/deploy/DeployTaskDetailPanel", () => ({
+vi.mock("./components/deploy/DeployTaskDetailPanel", () => ({
DeployTaskDetailPanel: () => null,
}));
-vi.mock("./plan-detail/components/PlanDetailApprovalFlow", () => ({
+vi.mock("./components/PlanDetailApprovalFlow", () => ({
PlanDetailReviewApprovalFlow: () => null,
}));
-vi.mock("./plan-detail/components/PlanDetailChangesBranch", () => ({
+vi.mock("./components/PlanDetailChangesBranch", () => ({
PlanDetailChangesBranch: ({
onSelectedSpecIdChange,
selectedSpecId,
@@ -97,25 +97,28 @@ vi.mock("./plan-detail/components/PlanDetailChangesBranch", () => ({
),
}));
-vi.mock("./plan-detail/components/PlanDetailDeployFuture", () => ({
+vi.mock("./components/PlanDetailDeployFuture", () => ({
PlanDetailDeployFuture: () => null,
}));
-vi.mock("./plan-detail/components/PlanDetailHeader", () => ({
+vi.mock("./components/PlanDetailHeader", () => ({
PlanDetailHeader: () => null,
}));
-vi.mock("./plan-detail/components/PlanDetailMetadataSidebar", () => ({
+vi.mock("./components/PlanDetailMetadataSidebar", () => ({
PlanDetailMetadataSidebar: () => null,
}));
-vi.mock("./plan-detail/hooks/usePlanDetailPage", () => ({
+vi.mock("./shell/constants", () => ({
SIDEBAR_WIDTH_NARROW_PX: 320,
WIDE_SIDEBAR_BREAKPOINT_PX: 1024,
+}));
+
+vi.mock("./shell/hooks/usePlanDetailPage", () => ({
usePlanDetailPage: mocks.usePlanDetailPage,
}));
-vi.mock("./plan-detail/utils/phaseSummary", () => ({
+vi.mock("./utils/phaseSummary", () => ({
buildChangesSummary: () => "",
buildDeploySummary: () => "",
buildReviewSummary: () => "",
diff --git a/frontend/src/react/pages/project/ProjectPlanDetailPage.tsx b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx
similarity index 94%
rename from frontend/src/react/pages/project/ProjectPlanDetailPage.tsx
rename to frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx
index 6d588b1053..97f1c8ae4b 100644
--- a/frontend/src/react/pages/project/ProjectPlanDetailPage.tsx
+++ b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx
@@ -21,29 +21,44 @@ import { cn } from "@/react/lib/utils";
import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";
import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";
import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
-import { DeployBranch } from "./plan-detail/components/deploy/DeployBranch";
-import { DeployTaskDetailPanel } from "./plan-detail/components/deploy/DeployTaskDetailPanel";
-import { PlanDetailReviewApprovalFlow } from "./plan-detail/components/PlanDetailApprovalFlow";
-import { PlanDetailChangesBranch } from "./plan-detail/components/PlanDetailChangesBranch";
-import { PlanDetailDeployFuture } from "./plan-detail/components/PlanDetailDeployFuture";
-import { PlanDetailHeader } from "./plan-detail/components/PlanDetailHeader";
-import { PlanDetailMetadataSidebar } from "./plan-detail/components/PlanDetailMetadataSidebar";
-import {
- PlanDetailProvider,
- usePlanDetailContext,
-} from "./plan-detail/context/PlanDetailContext";
+import { DeployBranch } from "./components/deploy/DeployBranch";
+import { DeployTaskDetailPanel } from "./components/deploy/DeployTaskDetailPanel";
+import { PlanDetailReviewApprovalFlow } from "./components/PlanDetailApprovalFlow";
+import { PlanDetailChangesBranch } from "./components/PlanDetailChangesBranch";
+import { PlanDetailDeployFuture } from "./components/PlanDetailDeployFuture";
+import { PlanDetailHeader } from "./components/PlanDetailHeader";
+import { PlanDetailMetadataSidebar } from "./components/PlanDetailMetadataSidebar";
+import { PlanDetailStoreProvider } from "./shared/stores/PlanDetailStoreProvider";
import {
SIDEBAR_WIDTH_NARROW_PX,
- usePlanDetailPage,
WIDE_SIDEBAR_BREAKPOINT_PX,
-} from "./plan-detail/hooks/usePlanDetailPage";
+} from "./shell/constants";
+import { usePlanDetailPage } from "./shell/hooks/usePlanDetailPage";
+import {
+ PlanDetailProvider,
+ usePlanDetailContext,
+} from "./shell/PlanDetailContext";
import {
buildChangesSummary,
buildDeploySummary,
buildReviewSummary,
-} from "./plan-detail/utils/phaseSummary";
+} from "./utils/phaseSummary";
+
+export function ProjectPlanDetailPage(props: {
+ projectId: string;
+ planId: string;
+ routeName?: string;
+ routeQuery?: Record<string, unknown>;
+ specId?: string;
+}) {
+ return (
+ <PlanDetailStoreProvider>
+ <ProjectPlanDetailPageInner {...props} />
+ </PlanDetailStoreProvider>
+ );
+}
-export function ProjectPlanDetailPage({
+function ProjectPlanDetailPageInner({
projectId,
planId,
routeName,
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.test.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.test.tsx
index 0a98184a3a..37f12ca5c6 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.test.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.test.tsx
@@ -5,8 +5,8 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
import { Issue_Approver_Status } from "@/types/proto-es/v1/issue_service_pb";
-import { PlanDetailProvider } from "../context/PlanDetailContext";
-import type { PlanDetailPageState } from "../hooks/usePlanDetailPage";
+import type { PlanDetailPageState } from "../shell/hooks/types";
+import { PlanDetailProvider } from "../shell/PlanDetailContext";
import { PlanDetailReviewApprovalFlow } from "./PlanDetailApprovalFlow";
(
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsx
index 8a8b2bbc10..bc2138462a 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsx
@@ -57,7 +57,7 @@ import {
memberMapToRolesInProjectIAM,
} from "@/utils";
import { extractIssueUID } from "@/utils/v1/issue/issue";
-import { usePlanDetailContext } from "../context/PlanDetailContext";
+import { usePlanDetailContext } from "../shell/PlanDetailContext";
type ApprovalStepStatus = "approved" | "rejected" | "current" | "pending";
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx
index 6b8c3cab1e..281abd678e 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.test.tsx
@@ -5,8 +5,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { State } from "@/types/proto-es/v1/common_pb";
import type { PlanCheckRun } from "@/types/proto-es/v1/plan_service_pb";
import type { CheckReleaseResponse_CheckResult } from "@/types/proto-es/v1/release_service_pb";
-import { PlanDetailProvider } from "../context/PlanDetailContext";
-import type { PlanDetailPageState } from "../hooks/usePlanDetailPage";
+import type { PlanDetailPageState } from "../shell/hooks/types";
+import { PlanDetailProvider } from "../shell/PlanDetailContext";
import { PlanDetailChangesBranch } from "./PlanDetailChangesBranch";
(
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx
index 854658c4ae..0b41b6a9b8 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx
@@ -106,8 +106,8 @@ import {
getSheetStatement,
setSheetStatement as setLocalSheetStatement,
} from "@/utils/v1/sheet";
-import { usePlanDetailContext } from "../context/PlanDetailContext";
import { usePlanDetailSpecValidation } from "../hooks/usePlanDetailSpecValidation";
+import { usePlanDetailContext } from "../shell/PlanDetailContext";
import {
getDefaultGhostConfig,
getGhostConfig as getGhostConfigFromStatement,
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChecks.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChecks.tsx
index cd4acbcfc0..fbd206163f 100644
Binary files a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChecks.tsx and b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChecks.tsx differ
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailDeployFuture.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailDeployFuture.tsx
index c7e05dd373..7326e85d50 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailDeployFuture.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailDeployFuture.tsx
@@ -28,7 +28,7 @@ import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";
import { CreateRolloutRequestSchema } from "@/types/proto-es/v1/rollout_service_pb";
import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";
import { isApprovalCompleted } from "../../issue-detail/utils/approval";
-import { usePlanDetailContext } from "../context/PlanDetailContext";
+import { usePlanDetailContext } from "../shell/PlanDetailContext";
export function PlanDetailDeployFuture() {
const { t } = useTranslation();
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsx
index 02c6278362..102226b000 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsx
@@ -14,7 +14,7 @@ import {
} from "@/types/proto-es/v1/release_service_pb";
import { extractProjectResourceName } from "@/utils";
import { getSheetStatement } from "@/utils/v1/sheet";
-import { usePlanDetailContext } from "../context/PlanDetailContext";
+import { usePlanDetailContext } from "../shell/PlanDetailContext";
import { getLocalSheetByName } from "../utils/localSheet";
import { transformReleaseCheckResultsToPlanCheckRuns } from "../utils/planCheck";
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx
index bedb936f8c..2bcdf9a22b 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx
@@ -42,8 +42,8 @@ import {
extractSheetUID,
hasProjectPermissionV2,
} from "@/utils";
-import { usePlanDetailContext } from "../context/PlanDetailContext";
import { usePlanDetailSpecValidation } from "../hooks/usePlanDetailSpecValidation";
+import { usePlanDetailContext } from "../shell/PlanDetailContext";
import {
getCreateIssueBlockingErrors,
getCreateIssueConfirmErrors,
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailMetadataSidebar.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailMetadataSidebar.tsx
index 4fce78fc35..5ffffd33f5 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailMetadataSidebar.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailMetadataSidebar.tsx
@@ -31,8 +31,8 @@ import {
hasProjectPermissionV2,
humanizeTs,
} from "@/utils";
-import { usePlanDetailContext } from "../context/PlanDetailContext";
import { usePlanCheckActions } from "../hooks/usePlanCheckActions";
+import { usePlanDetailContext } from "../shell/PlanDetailContext";
import { getPlanCheckSummaryWithFallback } from "../utils/planCheck";
import { getPlanDetailSidebarStatusInfo } from "../utils/sidebarStatus";
import { PlanDetailSidebarApprovalFlow } from "./PlanDetailApprovalFlow";
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx
index c9ef1bb090..b1cf28e150 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx
@@ -44,7 +44,7 @@ import {
getSheetStatement,
setSheetStatement,
} from "@/utils/v1/sheet";
-import { usePlanDetailContext } from "../context/PlanDetailContext";
+import { usePlanDetailContext } from "../shell/PlanDetailContext";
import {
createEmptyLocalSheet,
getLocalSheetByName,
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRolloutActionPanel.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRolloutActionPanel.tsx
index 0659c4c945..4da5512338 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRolloutActionPanel.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRolloutActionPanel.tsx
@@ -50,7 +50,7 @@ import {
preloadRolloutPermissionContext,
RUNNABLE_TASK_STATUSES,
} from "../../issue-detail/utils/rollout";
-import { usePlanDetailContext } from "../context/PlanDetailContext";
+import { usePlanDetailContext } from "../shell/PlanDetailContext";
const DEFAULT_RUN_DELAY_MS = 60 * 60 * 1000;
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployBranch.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployBranch.tsx
index 46caa5faad..c06a3197de 100644
--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployBranch.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployBranch.tsx
@@ -8,7 +8,7 @@ import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
import type { Rollout, Task } from "@/types/proto-es/v1/rollout_service_pb";
import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
import { hasProjectPermissionV2 } from "@/utils";
-import { usePlanDetailContext } from "../../context/PlanDetailContext";
+import { usePlanDetailContext } from "../../shell/PlanDetailContext";
import { generateRolloutPreview } from "../../utils/rolloutPreview";
import { DeployPendingTasksSection } from "./DeployPendingTasksSection";
import { DeployStageList } from "./DeployStageCard";
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageActionSection.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageActionSection.tsx
index 2ec2cce102..76ca7159e4 100644
--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageActionSection.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageActionSection.tsx
@@ -6,7 +6,7 @@ import {
Task_Status,
TaskRun_Status,
} from "@/types/proto-es/v1/rollout_service_pb";
-import { usePlanDetailContext } from "../../context/PlanDetailContext";
+import { usePlanDetailContext } from "../../shell/PlanDetailContext";
import { PlanDetailRollbackSheet } from "../PlanDetailRollbackSheet";
import {
type PlanDetailTaskRolloutAction,
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentSidebar.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentSidebar.tsx
index 5587646fd2..1832731bb7 100644
--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentSidebar.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentSidebar.tsx
@@ -18,7 +18,7 @@ import {
TaskRun_Status,
} from "@/types/proto-es/v1/rollout_service_pb";
import { extractDatabaseResourceName, humanizeDate } from "@/utils";
-import { usePlanDetailContext } from "../../context/PlanDetailContext";
+import { usePlanDetailContext } from "../../shell/PlanDetailContext";
import { PlanDetailRollbackSheet } from "../PlanDetailRollbackSheet";
import { PlanDetailTaskRunTable } from "../PlanDetailTaskRunTable";
import { DeployTaskStatus } from "./DeployTaskStatus";
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.tsx
index 1e3a72dbbd..361127e384 100644
--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.tsx
@@ -15,7 +15,7 @@ import {
preloadRolloutPermissionContext,
RUNNABLE_TASK_STATUSES,
} from "../../../issue-detail/utils/rollout";
-import { usePlanDetailContext } from "../../context/PlanDetailContext";
+import { usePlanDetailContext } from "../../shell/PlanDetailContext";
import { PlanDetailTaskRolloutActionPanel } from "../PlanDetailTaskRolloutActionPanel";
import { DeployStageContentSidebar } from "./DeployStageContentSidebar";
import { DeployTaskFilter } from "./DeployTaskFilter";
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskDetailPanel.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskDetailPanel.tsx
index 4867cee765..69f099914e 100644
--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskDetailPanel.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskDetailPanel.tsx
@@ -22,7 +22,7 @@ import {
isReleaseBasedTask,
releaseNameOfTaskV1,
} from "@/utils/v1/issue/rollout";
-import { usePlanDetailContext } from "../../context/PlanDetailContext";
+import { usePlanDetailContext } from "../../shell/PlanDetailContext";
import { DatabaseTarget } from "../PlanDetailChangesBranch";
import { PlanDetailRollbackSheet } from "../PlanDetailRollbackSheet";
import {
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskItem.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskItem.tsx
index 2333ff3a9c..87a722372e 100644
--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskItem.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskItem.tsx
@@ -26,7 +26,7 @@ import {
isReleaseBasedTask,
releaseNameOfTaskV1,
} from "@/utils/v1/issue/rollout";
-import { usePlanDetailContext } from "../../context/PlanDetailContext";
+import { usePlanDetailContext } from "../../shell/PlanDetailContext";
import { DatabaseTarget } from "../PlanDetailChangesBranch";
import { PlanDetailRollbackSheet } from "../PlanDetailRollbackSheet";
import {
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.tsx
index 6ed2b2efb0..71c06684d2 100644
--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.tsx
@@ -2,7 +2,7 @@ import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/react/components/ui/button";
import type { Stage, Task } from "@/types/proto-es/v1/rollout_service_pb";
-import { usePlanDetailContext } from "../../context/PlanDetailContext";
+import { usePlanDetailContext } from "../../shell/PlanDetailContext";
import { DeployTaskItem } from "./DeployTaskItem";
import { DeployTaskToolbar } from "./DeployTaskToolbar";
import { isDeployTaskSelectable } from "./taskActionState";
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskToolbar.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskToolbar.tsx
index 936e34364c..a8b1604960 100644
--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskToolbar.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskToolbar.tsx
@@ -12,7 +12,7 @@ import {
preloadRolloutPermissionContext,
RUNNABLE_TASK_STATUSES,
} from "../../../issue-detail/utils/rollout";
-import { usePlanDetailContext } from "../../context/PlanDetailContext";
+import { usePlanDetailContext } from "../../shell/PlanDetailContext";
import {
type PlanDetailTaskRolloutAction,
PlanDetailTaskRolloutActionPanel,
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/taskActions.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/taskActions.tsx
index c3ef915e17..7be63016a5 100644
--- a/frontend/src/react/pages/project/plan-detail/components/deploy/taskActions.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/taskActions.tsx
@@ -4,7 +4,7 @@ import {
canRolloutTasks,
preloadRolloutPermissionContext,
} from "../../../issue-detail/utils/rollout";
-import { usePlanDetailContext } from "../../context/PlanDetailContext";
+import { usePlanDetailContext } from "../../shell/PlanDetailContext";
import {
type DeployTaskActionState,
getDeployTaskActionState,
diff --git a/frontend/src/react/pages/project/plan-detail/hooks/usePlanCheckActions.tsx b/frontend/src/react/pages/project/plan-detail/hooks/usePlanCheckActions.tsx
index 58243c59e5..918efd47c7 100644
--- a/frontend/src/react/pages/project/plan-detail/hooks/usePlanCheckActions.tsx
+++ b/frontend/src/react/pages/project/plan-detail/hooks/usePlanCheckActions.tsx
@@ -17,7 +17,7 @@ import {
RunPlanChecksRequestSchema,
} from "@/types/proto-es/v1/plan_service_pb";
import { hasProjectPermissionV2 } from "@/utils";
-import { usePlanDetailContext } from "../context/PlanDetailContext";
+import { usePlanDetailContext } from "../shell/PlanDetailContext";
// Wraps the run / refresh logic shared between PlanDetailChecks (per-spec
// section in the body) and the plan-level summary in PlanDetailMetadataSidebar.
diff --git a/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailPage.ts b/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailPage.ts
deleted file mode 100644
index 0e6ed183c7..0000000000
--- a/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailPage.ts
+++ /dev/null
@@ -1,741 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { Code, ConnectError } from "@connectrpc/connect";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { useTranslation } from "react-i18next";
-import {
- issueServiceClientConnect,
- planServiceClientConnect,
- projectServiceClientConnect,
- rolloutServiceClientConnect,
- userServiceClientConnect,
-} from "@/connect";
-import { router } from "@/router";
-import {
- PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
- PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,
-} from "@/router/dashboard/projectV1";
-import {
- getRouteQueryString,
- PLAN_DETAIL_PHASE_DEPLOY,
-} from "@/router/dashboard/projectV1RouteHelpers";
-import {
- WORKSPACE_ROUTE_403,
- WORKSPACE_ROUTE_404,
-} from "@/router/dashboard/workspaceRoutes";
-import { State } from "@/types/proto-es/v1/common_pb";
-import {
- GetIssueRequestSchema,
- type Issue,
- IssueStatus,
-} from "@/types/proto-es/v1/issue_service_pb";
-import {
- GetPlanCheckRunRequestSchema,
- GetPlanRequestSchema,
- type Plan,
- type PlanCheckRun,
-} from "@/types/proto-es/v1/plan_service_pb";
-import {
- GetProjectRequestSchema,
- type Project,
-} from "@/types/proto-es/v1/project_service_pb";
-import {
- GetRolloutRequestSchema,
- ListTaskRunsRequestSchema,
- type Rollout,
- Task_Status,
- type TaskRun,
-} from "@/types/proto-es/v1/rollout_service_pb";
-import type { User } from "@/types/proto-es/v1/user_service_pb";
-import { unknownPlan } from "@/types/v1/issue/plan";
-import { unknownProject } from "@/types/v1/project";
-import { unknownUser } from "@/types/v1/user";
-import {
- getIssueRoute,
- getRolloutFromPlan,
- hasProjectPermissionV2,
- minmax,
- setDocumentTitle,
-} from "@/utils";
-import { createPlanSkeleton } from "../utils/createPlan";
-
-const POLLER_INTERVAL = {
- min: 1000,
- max: 30000,
- growth: 2,
- jitter: 250,
-} as const;
-
-const PROJECT_NAME_PREFIX = "projects/";
-
-// Width below which the sidebar collapses into a mobile drawer.
-export const MOBILE_BREAKPOINT_PX = 780;
-// Width at or above which the sidebar widens.
-export const WIDE_SIDEBAR_BREAKPOINT_PX = 1280;
-export const SIDEBAR_WIDTH_NARROW_PX = 240;
-export const SIDEBAR_WIDTH_WIDE_PX = 336;
-
-export type PlanDetailSidebarMode = "NONE" | "DESKTOP" | "MOBILE";
-export type PlanDetailPhase = "changes" | "review" | "deploy";
-
-export interface PlanDetailPageSnapshot {
- projectId: string;
- planId: string;
- specId?: string;
- pageKey: string;
- projectTitle: string;
- projectRequireIssueApproval: boolean;
- projectRequirePlanCheckNoError: boolean;
- projectCanCreateRollout: boolean;
- currentUser: User;
- project: Project;
- isCreating: boolean;
- isInitializing: boolean;
- ready: boolean;
- readonly: boolean;
- plan: Plan;
- issue?: Issue;
- rollout?: Rollout;
- planCheckRuns: PlanCheckRun[];
- taskRuns: TaskRun[];
- sidebarMode: PlanDetailSidebarMode;
- containerWidth: number;
- desktopSidebarWidth: number;
- mobileSidebarOpen: boolean;
-}
-
-export interface PlanDetailPageState extends PlanDetailPageSnapshot {
- isEditing: boolean;
- isRefreshing: boolean;
- isRunningChecks: boolean;
- setIsRunningChecks: (running: boolean) => void;
- lastRefreshTime: number;
- activePhases: Set<PlanDetailPhase>;
- routeName?: string;
- routePhase?: string;
- routeStageId?: string;
- routeTaskId?: string;
- selectedTaskName?: string;
- pendingLeaveConfirm: boolean;
- patchState: (patch: Partial<PlanDetailPageSnapshot>) => void;
- refreshState: () => Promise<void>;
- bypassLeaveGuardOnce: () => void;
- setEditing: (scope: string, editing: boolean) => void;
- setMobileSidebarOpen: (open: boolean) => void;
- togglePhase: (phase: PlanDetailPhase) => void;
- expandPhase: (phase: PlanDetailPhase) => void;
- closeTaskPanel: () => void;
- resolveLeaveConfirm: (confirmed: boolean) => void;
-}
-
-const buildDefaultSnapshot = (
- projectId: string,
- planId: string,
- specId?: string
-): PlanDetailPageSnapshot => ({
- projectId,
- planId,
- specId,
- pageKey: `${projectId}/${planId}/${specId ?? ""}`,
- projectTitle: "",
- projectRequireIssueApproval: true,
- projectRequirePlanCheckNoError: true,
- projectCanCreateRollout: false,
- currentUser: unknownUser(),
- project: unknownProject(),
- isCreating: planId.toLowerCase() === "create",
- isInitializing: true,
- ready: false,
- readonly: true,
- plan: unknownPlan(),
- issue: undefined,
- rollout: undefined,
- planCheckRuns: [],
- taskRuns: [],
- sidebarMode: "NONE",
- containerWidth: 0,
- desktopSidebarWidth: 0,
- mobileSidebarOpen: false,
-});
-
-const applyDerivedState = (
- snapshot: PlanDetailPageSnapshot
-): PlanDetailPageSnapshot => {
- const readonly =
- snapshot.plan.state === State.DELETED ||
- (snapshot.issue ? snapshot.issue.status !== IssueStatus.OPEN : false);
- return {
- ...snapshot,
- readonly,
- ready: !snapshot.isInitializing && !!snapshot.plan.name,
- };
-};
-
-const shouldRedirectToIssueDetail = (plan: Plan, issue?: Issue) => {
- if (!issue?.name) {
- return false;
- }
- if (plan.specs.length === 0) {
- return false;
- }
- return plan.specs.every((spec) => {
- return (
- spec.config?.case === "createDatabaseConfig" ||
- spec.config?.case === "exportDataConfig"
- );
- });
-};
-
-const fetchPlanDetailSnapshot = async (
- projectId: string,
- planId: string,
- routeQuery: Record<string, unknown> = {}
-): Promise<Partial<PlanDetailPageSnapshot>> => {
- const [project, currentUser] = await Promise.all([
- projectServiceClientConnect.getProject(
- create(GetProjectRequestSchema, {
- name: `${PROJECT_NAME_PREFIX}${projectId}`,
- })
- ),
- userServiceClientConnect.getCurrentUser({}),
- ]);
-
- if (planId.toLowerCase() === "create") {
- const plan = await createPlanSkeleton(
- project,
- convertRouteQuery(routeQuery)
- );
- return {
- currentUser,
- plan,
- project,
- projectTitle: project.title,
- projectCanCreateRollout: hasProjectPermissionV2(
- project,
- "bb.rollouts.create"
- ),
- projectRequireIssueApproval: project.requireIssueApproval,
- projectRequirePlanCheckNoError: project.requirePlanCheckNoError,
- issue: undefined,
- rollout: undefined,
- planCheckRuns: [],
- taskRuns: [],
- };
- }
-
- const plan = await planServiceClientConnect.getPlan(
- create(GetPlanRequestSchema, {
- name: `${PROJECT_NAME_PREFIX}${projectId}/plans/${planId}`,
- })
- );
-
- const [issue, planCheckRuns, rollout] = await Promise.all([
- plan.issue
- ? issueServiceClientConnect
- .getIssue(create(GetIssueRequestSchema, { name: plan.issue }))
- .catch(() => undefined)
- : Promise.resolve(undefined),
- planServiceClientConnect
- .getPlanCheckRun(
- create(GetPlanCheckRunRequestSchema, {
- name: `${plan.name}/planCheckRun`,
- })
- )
- .then((run) => [run] as PlanCheckRun[])
- .catch(() => []),
- plan.hasRollout
- ? rolloutServiceClientConnect
- .getRollout(
- create(GetRolloutRequestSchema, {
- name: getRolloutFromPlan(plan.name),
- })
- )
- .catch(() => undefined)
- : Promise.resolve(undefined),
- ]);
-
- const taskRuns =
- rollout !== undefined
- ? await rolloutServiceClientConnect
- .listTaskRuns(
- create(ListTaskRunsRequestSchema, {
- parent: `${rollout.name}/stages/-/tasks/-`,
- })
- )
- .then((response) => response.taskRuns)
- .catch(() => [])
- : [];
-
- return {
- currentUser,
- plan,
- project,
- projectTitle: project.title,
- projectCanCreateRollout: hasProjectPermissionV2(
- project,
- "bb.rollouts.create"
- ),
- projectRequireIssueApproval: project.requireIssueApproval,
- projectRequirePlanCheckNoError: project.requirePlanCheckNoError,
- issue,
- rollout,
- planCheckRuns,
- taskRuns,
- };
-};
-
-const defaultActivePhases = (): Set<PlanDetailPhase> =>
- new Set<PlanDetailPhase>(["changes", "review", "deploy"]);
-
-const convertRouteQuery = (query: Record<string, unknown>) => {
- const kv: Record<string, string> = {};
- for (const [key, value] of Object.entries(query)) {
- if (typeof value === "string") {
- kv[key] = value;
- }
- }
- return kv;
-};
-
-export const usePlanDetailPage = ({
- projectId,
- planId,
- routeName,
- routeQuery = {},
- specId,
- pageHost,
-}: {
- projectId: string;
- planId: string;
- routeName?: string;
- routeQuery?: Record<string, unknown>;
- specId?: string;
- pageHost: HTMLDivElement | null;
-}): PlanDetailPageState => {
- const { t } = useTranslation();
- const [snapshot, setSnapshot] = useState<PlanDetailPageSnapshot>(() =>
- buildDefaultSnapshot(projectId, planId, specId)
- );
- const [activePhases, setActivePhases] = useState<Set<PlanDetailPhase>>(() =>
- defaultActivePhases()
- );
- const [editingScopes, setEditingScopes] = useState<Record<string, true>>({});
- const [isRefreshing, setIsRefreshing] = useState(false);
- const [isRunningChecks, setIsRunningChecks] = useState(false);
- const [lastRefreshTime, setLastRefreshTime] = useState(0);
- const [pendingLeaveConfirm, setPendingLeaveConfirm] = useState(false);
- const latestSnapshotRef = useRef(snapshot);
- const bypassLeaveGuardOnceRef = useRef(false);
- const pollTimerRef = useRef<number | undefined>(undefined);
- // Target route captured when the guard intercepts a navigation. We cancel
- // that navigation synchronously and re-issue it after the user confirms.
- const pendingLeaveTargetRef = useRef<string | null>(null);
- const isEditing = Object.keys(editingScopes).length > 0;
-
- // 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.
- const routeQueryRef = useRef(routeQuery);
- routeQueryRef.current = routeQuery;
- const routePhase = getRouteQueryString(routeQuery.phase as never);
- const routeStageId = getRouteQueryString(routeQuery.stageId as never);
- const routeTaskId = getRouteQueryString(routeQuery.taskId as never);
-
- useEffect(() => {
- latestSnapshotRef.current = snapshot;
- }, [snapshot]);
-
- const stopPolling = useCallback(() => {
- if (!pollTimerRef.current) {
- return;
- }
- window.clearTimeout(pollTimerRef.current);
- pollTimerRef.current = undefined;
- }, []);
-
- const patchState = useCallback((patch: Partial<PlanDetailPageSnapshot>) => {
- setSnapshot((prev) => applyDerivedState({ ...prev, ...patch }));
- }, []);
-
- const refreshState = useCallback(async () => {
- try {
- setIsRefreshing(true);
- const current = latestSnapshotRef.current;
- const patch = await fetchPlanDetailSnapshot(
- current.projectId,
- current.planId,
- routeQueryRef.current
- );
- patchState(patch);
- setLastRefreshTime(Date.now());
- } finally {
- setIsRefreshing(false);
- }
- }, [patchState]);
-
- const setMobileSidebarOpen = useCallback(
- (open: boolean) => {
- patchState({ mobileSidebarOpen: open });
- },
- [patchState]
- );
-
- const setEditing = useCallback((scope: string, editing: boolean) => {
- setEditingScopes((prev) => {
- if (editing) {
- if (prev[scope]) return prev;
- return { ...prev, [scope]: true };
- }
- if (!prev[scope]) return prev;
- const next = { ...prev };
- delete next[scope];
- return next;
- });
- }, []);
-
- const bypassLeaveGuardOnce = useCallback(() => {
- bypassLeaveGuardOnceRef.current = true;
- }, []);
-
- const togglePhase = useCallback((phase: PlanDetailPhase) => {
- setActivePhases((prev) => {
- const next = new Set(prev);
- if (next.has(phase)) {
- next.delete(phase);
- } else {
- next.add(phase);
- }
- return next;
- });
- }, []);
-
- const expandPhase = useCallback((phase: PlanDetailPhase) => {
- setActivePhases((prev) => new Set([...prev, phase]));
- }, []);
-
- const closeTaskPanel = useCallback(() => {
- void router.replace({
- query: {
- ...(routePhase ? { phase: routePhase } : {}),
- ...(routeStageId ? { stageId: routeStageId } : {}),
- },
- });
- }, [routePhase, routeStageId]);
-
- useEffect(() => {
- setEditingScopes({});
- patchState({
- projectId,
- planId,
- specId,
- pageKey: `${projectId}/${planId}/${specId ?? ""}`,
- projectTitle: "",
- isCreating: planId.toLowerCase() === "create",
- isInitializing: true,
- plan: unknownPlan(),
- issue: undefined,
- rollout: undefined,
- planCheckRuns: [],
- taskRuns: [],
- });
-
- let canceled = false;
-
- const load = async () => {
- try {
- const patch = await fetchPlanDetailSnapshot(
- projectId,
- planId,
- routeQueryRef.current
- );
- if (canceled) {
- return;
- }
- patchState({
- ...patch,
- isInitializing: false,
- specId,
- });
- } catch (error) {
- if (canceled) {
- return;
- }
- if (error instanceof ConnectError) {
- if (error.code === Code.NotFound) {
- void router.push({ name: WORKSPACE_ROUTE_404 });
- } else if (error.code === Code.PermissionDenied) {
- void router.push({ name: WORKSPACE_ROUTE_403 });
- }
- patchState({ isInitializing: false });
- return;
- }
-
- patchState({ isInitializing: false });
- throw error;
- }
- };
-
- void load();
-
- return () => {
- canceled = true;
- };
- }, [patchState, planId, projectId, specId]);
-
- const resolveLeaveConfirm = useCallback((confirmed: boolean) => {
- const target = confirmed ? pendingLeaveTargetRef.current : null;
- pendingLeaveTargetRef.current = null;
- setPendingLeaveConfirm(false);
- if (target) {
- bypassLeaveGuardOnceRef.current = true;
- // Replace (not push) so a confirmed-discard navigation doesn't leave
- // an extra entry that lets Back return to the discarded plan. Works
- // correctly whether the original navigation was push, replace, or
- // browser back/forward.
- void router.replace(target);
- }
- }, []);
-
- useEffect(() => {
- if (!isEditing) {
- // Editing scope ended (e.g. async save completed) while a leave
- // prompt is open — there's nothing unsaved anymore, so navigate to
- // the captured target without further confirmation.
- if (pendingLeaveTargetRef.current) {
- resolveLeaveConfirm(true);
- }
- return;
- }
-
- const onBeforeUnload = (event: BeforeUnloadEvent) => {
- event.returnValue = t("common.leave-without-saving");
- event.preventDefault();
- };
- window.addEventListener("beforeunload", onBeforeUnload);
- const removeGuard = router.beforeEach((to, _from, next) => {
- if (bypassLeaveGuardOnceRef.current) {
- bypassLeaveGuardOnceRef.current = false;
- next();
- return;
- }
- // Cancel the navigation synchronously and remember the target so we
- // can re-issue it from resolveLeaveConfirm after the user confirms.
- // Always overwrite the pending target — the latest navigation wins.
- pendingLeaveTargetRef.current = to.fullPath;
- setPendingLeaveConfirm(true);
- next(false);
- });
-
- return () => {
- window.removeEventListener("beforeunload", onBeforeUnload);
- removeGuard();
- };
- }, [isEditing, resolveLeaveConfirm, t]);
-
- useEffect(() => {
- if (snapshot.isCreating) {
- setDocumentTitle(t("plan.new-plan"), snapshot.projectTitle);
- return;
- }
- if (snapshot.ready && snapshot.plan.title) {
- setDocumentTitle(snapshot.plan.title, snapshot.projectTitle);
- }
- }, [
- snapshot.isCreating,
- snapshot.plan.title,
- snapshot.projectTitle,
- snapshot.ready,
- t,
- ]);
-
- useEffect(() => {
- if (
- snapshot.ready &&
- shouldRedirectToIssueDetail(snapshot.plan, snapshot.issue)
- ) {
- void router.replace(getIssueRoute({ name: snapshot.issue?.name ?? "" }));
- }
- }, [snapshot.issue, snapshot.plan, snapshot.ready]);
-
- useEffect(() => {
- if (
- routeName === PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS ||
- routeName === PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL
- ) {
- expandPhase("changes");
- }
- if (
- routePhase === PLAN_DETAIL_PHASE_DEPLOY ||
- routeStageId ||
- routeTaskId
- ) {
- expandPhase("deploy");
- }
- }, [expandPhase, routeName, routePhase, routeStageId, routeTaskId]);
-
- useEffect(() => {
- if (!pageHost) {
- patchState({
- containerWidth: 0,
- desktopSidebarWidth: 0,
- mobileSidebarOpen: false,
- sidebarMode: "NONE",
- });
- return;
- }
-
- const updateSidebar = () => {
- const containerWidth = pageHost.getBoundingClientRect().width;
- const sidebarMode: PlanDetailSidebarMode =
- containerWidth === 0
- ? "NONE"
- : containerWidth < MOBILE_BREAKPOINT_PX
- ? "MOBILE"
- : "DESKTOP";
- patchState({
- containerWidth,
- desktopSidebarWidth:
- containerWidth < WIDE_SIDEBAR_BREAKPOINT_PX
- ? SIDEBAR_WIDTH_NARROW_PX
- : SIDEBAR_WIDTH_WIDE_PX,
- mobileSidebarOpen:
- sidebarMode === "MOBILE"
- ? latestSnapshotRef.current.mobileSidebarOpen
- : false,
- sidebarMode,
- });
- };
-
- updateSidebar();
- const observer = new ResizeObserver(() => updateSidebar());
- observer.observe(pageHost);
-
- return () => observer.disconnect();
- }, [pageHost, patchState]);
-
- const isPlanDone = useMemo(() => {
- if (!snapshot.rollout) {
- return false;
- }
- const allTasks = snapshot.rollout.stages.flatMap((stage) => stage.tasks);
- return (
- allTasks.length > 0 &&
- allTasks.every(
- (task) =>
- task.status === Task_Status.DONE ||
- task.status === Task_Status.SKIPPED
- )
- );
- }, [snapshot.rollout]);
-
- useEffect(() => {
- if (!snapshot.ready || snapshot.isCreating || isPlanDone) {
- stopPolling();
- return;
- }
-
- let canceled = false;
-
- const poll = (interval: number) => {
- stopPolling();
- const nextInterval = minmax(
- interval +
- Math.floor(Math.random() * (POLLER_INTERVAL.jitter * 2 + 1)) -
- POLLER_INTERVAL.jitter,
- POLLER_INTERVAL.min,
- POLLER_INTERVAL.max
- );
-
- pollTimerRef.current = window.setTimeout(async () => {
- if (canceled) {
- return;
- }
- await refreshState().catch(() => undefined);
- if (canceled) {
- return;
- }
- poll(
- Math.min(nextInterval * POLLER_INTERVAL.growth, POLLER_INTERVAL.max)
- );
- }, nextInterval);
- };
-
- poll(POLLER_INTERVAL.min);
-
- return () => {
- canceled = true;
- stopPolling();
- };
- }, [
- isPlanDone,
- refreshState,
- snapshot.isCreating,
- snapshot.ready,
- stopPolling,
- ]);
-
- const selectedTaskName = useMemo(() => {
- if (!routeTaskId || !snapshot.rollout) {
- return undefined;
- }
- for (const stage of snapshot.rollout.stages) {
- const task = stage.tasks.find((item) =>
- item.name.endsWith(`/${routeTaskId}`)
- );
- if (task) {
- return task.name;
- }
- }
- return undefined;
- }, [routeTaskId, snapshot.rollout]);
-
- return useMemo(
- () => ({
- ...snapshot,
- isEditing,
- isRefreshing,
- isRunningChecks,
- setIsRunningChecks,
- lastRefreshTime,
- activePhases,
- routeName,
- routePhase,
- routeStageId,
- routeTaskId,
- selectedTaskName,
- pendingLeaveConfirm,
- bypassLeaveGuardOnce,
- patchState,
- refreshState,
- setEditing,
- setMobileSidebarOpen,
- togglePhase,
- expandPhase,
- closeTaskPanel,
- resolveLeaveConfirm,
- }),
- [
- activePhases,
- bypassLeaveGuardOnce,
- closeTaskPanel,
- isEditing,
- isRefreshing,
- isRunningChecks,
- lastRefreshTime,
- patchState,
- pendingLeaveConfirm,
- refreshState,
- resolveLeaveConfirm,
- routeName,
- routePhase,
- routeStageId,
- routeTaskId,
- selectedTaskName,
- setEditing,
- setMobileSidebarOpen,
- snapshot,
- togglePhase,
- expandPhase,
- ]
- );
-};
diff --git a/frontend/src/react/pages/project/plan-detail/index.ts b/frontend/src/react/pages/project/plan-detail/index.ts
new file mode 100644
index 0000000000..7e1117054e
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/index.ts
@@ -0,0 +1 @@
+export { ProjectPlanDetailPage } from "./ProjectPlanDetailPage";
diff --git a/frontend/src/react/pages/project/plan-detail/shared/stores/PlanDetailStoreProvider.tsx b/frontend/src/react/pages/project/plan-detail/shared/stores/PlanDetailStoreProvider.tsx
new file mode 100644
index 0000000000..3d908e5fd7
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shared/stores/PlanDetailStoreProvider.tsx
@@ -0,0 +1,18 @@
+import { type ReactNode, useState } from "react";
+import {
+ createPlanDetailStore,
+ PlanDetailStoreContext,
+} from "./usePlanDetailStore";
+
+export const PlanDetailStoreProvider = ({
+ children,
+}: {
+ children: ReactNode;
+}) => {
+ const [store] = useState(createPlanDetailStore);
+ return (
+ <PlanDetailStoreContext.Provider value={store}>
+ {children}
+ </PlanDetailStoreContext.Provider>
+ );
+};
diff --git a/frontend/src/react/pages/project/plan-detail/shared/stores/__tests__/usePlanDetailStore.test.tsx b/frontend/src/react/pages/project/plan-detail/shared/stores/__tests__/usePlanDetailStore.test.tsx
new file mode 100644
index 0000000000..0fbbd0bc6c
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shared/stores/__tests__/usePlanDetailStore.test.tsx
@@ -0,0 +1,57 @@
+import { act, renderHook } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { describe, expect, test } from "vitest";
+import { PlanDetailStoreProvider } from "../PlanDetailStoreProvider";
+import { usePlanDetailStore } from "../usePlanDetailStore";
+
+const wrapper = ({ children }: { children: ReactNode }) => (
+ <PlanDetailStoreProvider>{children}</PlanDetailStoreProvider>
+);
+
+describe("usePlanDetailStore", () => {
+ test("phase slice toggles active phases", () => {
+ const { result } = renderHook(
+ () => ({
+ active: usePlanDetailStore((s) => s.activePhases),
+ toggle: usePlanDetailStore((s) => s.togglePhase),
+ }),
+ { wrapper }
+ );
+
+ expect(result.current.active.has("changes")).toBe(true);
+ act(() => result.current.toggle("changes"));
+ expect(result.current.active.has("changes")).toBe(false);
+ });
+
+ test("editing slice tracks scopes and isEditing", () => {
+ const { result } = renderHook(
+ () => ({
+ scopes: usePlanDetailStore((s) => s.editingScopes),
+ setEditing: usePlanDetailStore((s) => s.setEditing),
+ }),
+ { wrapper }
+ );
+
+ expect(Object.keys(result.current.scopes)).toHaveLength(0);
+ act(() => result.current.setEditing("title", true));
+ expect(result.current.scopes.title).toBe(true);
+ act(() => result.current.setEditing("title", false));
+ expect(result.current.scopes.title).toBeUndefined();
+ });
+
+ test("each provider mount creates an isolated store", () => {
+ const { result: a } = renderHook(
+ () => usePlanDetailStore((s) => s.togglePhase),
+ {
+ wrapper,
+ }
+ );
+ const { result: b } = renderHook(
+ () => usePlanDetailStore((s) => s.togglePhase),
+ {
+ wrapper,
+ }
+ );
+ expect(a.current).not.toBe(b.current);
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/shared/stores/editingSlice.ts b/frontend/src/react/pages/project/plan-detail/shared/stores/editingSlice.ts
new file mode 100644
index 0000000000..ca875c0d6f
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shared/stores/editingSlice.ts
@@ -0,0 +1,31 @@
+import type { EditingSlice, PlanDetailSliceCreator } from "./types";
+
+export const createEditingSlice: PlanDetailSliceCreator<EditingSlice> = (
+ set
+) => {
+ let bypassOnce = false;
+ return {
+ editingScopes: {},
+ setEditing: (scope, editing) =>
+ set((state) => {
+ const next = { ...state.editingScopes };
+ if (editing) next[scope] = true;
+ else delete next[scope];
+ return { editingScopes: next };
+ }),
+ bypassLeaveGuardOnce: () => {
+ bypassOnce = true;
+ },
+ isLeaveGuardBypassed: () => {
+ if (bypassOnce) {
+ bypassOnce = false;
+ return true;
+ }
+ return false;
+ },
+ pendingLeaveTarget: null,
+ setPendingLeaveTarget: (target) => set({ pendingLeaveTarget: target }),
+ pendingLeaveConfirm: false,
+ setPendingLeaveConfirm: (open) => set({ pendingLeaveConfirm: open }),
+ };
+};
diff --git a/frontend/src/react/pages/project/plan-detail/shared/stores/phaseSlice.ts b/frontend/src/react/pages/project/plan-detail/shared/stores/phaseSlice.ts
new file mode 100644
index 0000000000..1e13cf9d8d
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shared/stores/phaseSlice.ts
@@ -0,0 +1,33 @@
+import type {
+ PhaseSlice,
+ PlanDetailPhase,
+ PlanDetailSliceCreator,
+} from "./types";
+
+const defaultActivePhases = (): Set<PlanDetailPhase> =>
+ new Set(["changes", "review", "deploy"]);
+
+export const createPhaseSlice: PlanDetailSliceCreator<PhaseSlice> = (set) => ({
+ activePhases: defaultActivePhases(),
+ togglePhase: (phase) =>
+ set((state) => {
+ const next = new Set(state.activePhases);
+ if (next.has(phase)) next.delete(phase);
+ else next.add(phase);
+ return { activePhases: next };
+ }),
+ expandPhase: (phase) =>
+ set((state) => {
+ if (state.activePhases.has(phase)) return state;
+ const next = new Set(state.activePhases);
+ next.add(phase);
+ return { activePhases: next };
+ }),
+ collapsePhase: (phase) =>
+ set((state) => {
+ if (!state.activePhases.has(phase)) return state;
+ const next = new Set(state.activePhases);
+ next.delete(phase);
+ return { activePhases: next };
+ }),
+});
diff --git a/frontend/src/react/pages/project/plan-detail/shared/stores/pollingSlice.ts b/frontend/src/react/pages/project/plan-detail/shared/stores/pollingSlice.ts
new file mode 100644
index 0000000000..f8b812c04c
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shared/stores/pollingSlice.ts
@@ -0,0 +1,14 @@
+import type { PlanDetailSliceCreator, PollingSlice } from "./types";
+
+export const createPollingSlice: PlanDetailSliceCreator<PollingSlice> = (
+ set
+) => ({
+ isRefreshing: false,
+ isRunningChecks: false,
+ lastRefreshTime: 0,
+ pollTimerId: undefined,
+ setRefreshing: (v) => set({ isRefreshing: v }),
+ setRunningChecks: (v) => set({ isRunningChecks: v }),
+ setLastRefreshTime: (t) => set({ lastRefreshTime: t }),
+ setPollTimerId: (id) => set({ pollTimerId: id }),
+});
diff --git a/frontend/src/react/pages/project/plan-detail/shared/stores/selectionSlice.ts b/frontend/src/react/pages/project/plan-detail/shared/stores/selectionSlice.ts
new file mode 100644
index 0000000000..d0f3bc049f
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shared/stores/selectionSlice.ts
@@ -0,0 +1,17 @@
+import type { PlanDetailSliceCreator, SelectionSlice } from "./types";
+
+export const createSelectionSlice: PlanDetailSliceCreator<SelectionSlice> = (
+ set
+) => ({
+ routePhase: undefined,
+ selectedSpecId: undefined,
+ selectedStageId: undefined,
+ selectedTaskName: undefined,
+ setRouteSelection: (selection) =>
+ set({
+ routePhase: selection.phase,
+ selectedSpecId: selection.specId,
+ selectedStageId: selection.stageId,
+ selectedTaskName: selection.taskName,
+ }),
+});
diff --git a/frontend/src/react/pages/project/plan-detail/shared/stores/snapshotSlice.ts b/frontend/src/react/pages/project/plan-detail/shared/stores/snapshotSlice.ts
new file mode 100644
index 0000000000..e437579e18
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shared/stores/snapshotSlice.ts
@@ -0,0 +1,22 @@
+import type {
+ PlanDetailPageSnapshot,
+ PlanDetailSliceCreator,
+ SnapshotSlice,
+} from "./types";
+
+const buildDefaultSnapshot = (): PlanDetailPageSnapshot => ({
+ taskRuns: [],
+ planCheckRuns: [],
+ isInitializing: true,
+ isNotFound: false,
+ isPermissionDenied: false,
+});
+
+export const createSnapshotSlice: PlanDetailSliceCreator<SnapshotSlice> = (
+ set
+) => ({
+ snapshot: buildDefaultSnapshot(),
+ setSnapshot: (snapshot) => set({ snapshot }),
+ patchSnapshot: (patch) =>
+ set((state) => ({ snapshot: { ...state.snapshot, ...patch } })),
+});
diff --git a/frontend/src/react/pages/project/plan-detail/shared/stores/types.ts b/frontend/src/react/pages/project/plan-detail/shared/stores/types.ts
new file mode 100644
index 0000000000..9fc343dd8c
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shared/stores/types.ts
@@ -0,0 +1,78 @@
+import type { StateCreator } from "zustand";
+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
+import type { Plan, PlanCheckRun } from "@/types/proto-es/v1/plan_service_pb";
+import type { Rollout, TaskRun } from "@/types/proto-es/v1/rollout_service_pb";
+
+export type PlanDetailPhase = "changes" | "review" | "deploy";
+
+export interface PlanDetailPageSnapshot {
+ plan?: Plan;
+ issue?: Issue;
+ rollout?: Rollout;
+ taskRuns: TaskRun[];
+ planCheckRuns: PlanCheckRun[];
+ isInitializing: boolean;
+ isNotFound: boolean;
+ isPermissionDenied: boolean;
+}
+
+export type SnapshotSlice = {
+ snapshot: PlanDetailPageSnapshot;
+ setSnapshot: (snapshot: PlanDetailPageSnapshot) => void;
+ patchSnapshot: (patch: Partial<PlanDetailPageSnapshot>) => void;
+};
+
+export type PhaseSlice = {
+ activePhases: Set<PlanDetailPhase>;
+ togglePhase: (phase: PlanDetailPhase) => void;
+ expandPhase: (phase: PlanDetailPhase) => void;
+ collapsePhase: (phase: PlanDetailPhase) => void;
+};
+
+export type EditingSlice = {
+ editingScopes: Record<string, true>;
+ setEditing: (scope: string, editing: boolean) => void;
+ bypassLeaveGuardOnce: () => void;
+ isLeaveGuardBypassed: () => boolean;
+ pendingLeaveTarget: string | null;
+ setPendingLeaveTarget: (target: string | null) => void;
+ pendingLeaveConfirm: boolean;
+ setPendingLeaveConfirm: (open: boolean) => void;
+};
+
+export type SelectionSlice = {
+ routePhase: PlanDetailPhase | undefined;
+ selectedSpecId: string | undefined;
+ selectedStageId: string | undefined;
+ selectedTaskName: string | undefined;
+ setRouteSelection: (selection: {
+ phase?: PlanDetailPhase;
+ specId?: string;
+ stageId?: string;
+ taskName?: string;
+ }) => void;
+};
+
+export type PollingSlice = {
+ isRefreshing: boolean;
+ isRunningChecks: boolean;
+ lastRefreshTime: number;
+ pollTimerId: number | undefined;
+ setRefreshing: (v: boolean) => void;
+ setRunningChecks: (v: boolean) => void;
+ setLastRefreshTime: (t: number) => void;
+ setPollTimerId: (id: number | undefined) => void;
+};
+
+export type PlanDetailStore = SnapshotSlice &
+ PhaseSlice &
+ EditingSlice &
+ SelectionSlice &
+ PollingSlice;
+
+export type PlanDetailSliceCreator<Slice> = StateCreator<
+ PlanDetailStore,
+ [],
+ [],
+ Slice
+>;
diff --git a/frontend/src/react/pages/project/plan-detail/shared/stores/usePlanDetailStore.ts b/frontend/src/react/pages/project/plan-detail/shared/stores/usePlanDetailStore.ts
new file mode 100644
index 0000000000..29e325b442
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shared/stores/usePlanDetailStore.ts
@@ -0,0 +1,35 @@
+import { createContext, useContext } from "react";
+import { create, useStore } from "zustand";
+import { createEditingSlice } from "./editingSlice";
+import { createPhaseSlice } from "./phaseSlice";
+import { createPollingSlice } from "./pollingSlice";
+import { createSelectionSlice } from "./selectionSlice";
+import { createSnapshotSlice } from "./snapshotSlice";
+import type { PlanDetailStore } from "./types";
+
+export const createPlanDetailStore = () =>
+ create<PlanDetailStore>()((...args) => ({
+ ...createSnapshotSlice(...args),
+ ...createPhaseSlice(...args),
+ ...createEditingSlice(...args),
+ ...createSelectionSlice(...args),
+ ...createPollingSlice(...args),
+ }));
+
+export type PlanDetailStoreApi = ReturnType<typeof createPlanDetailStore>;
+
+export const PlanDetailStoreContext = createContext<PlanDetailStoreApi | null>(
+ null
+);
+
+export function usePlanDetailStore<T>(selector: (s: PlanDetailStore) => T): T {
+ const store = useContext(PlanDetailStoreContext);
+ if (!store) throw new Error("PlanDetailStoreProvider missing");
+ return useStore(store, selector);
+}
+
+export function usePlanDetailStoreApi(): PlanDetailStoreApi {
+ const store = useContext(PlanDetailStoreContext);
+ if (!store) throw new Error("PlanDetailStoreProvider missing");
+ return store;
+}
diff --git a/frontend/src/react/pages/project/plan-detail/context/PlanDetailContext.tsx b/frontend/src/react/pages/project/plan-detail/shell/PlanDetailContext.tsx
similarity index 89%
rename from frontend/src/react/pages/project/plan-detail/context/PlanDetailContext.tsx
rename to frontend/src/react/pages/project/plan-detail/shell/PlanDetailContext.tsx
index b4ee4c6f59..f37f07ee88 100644
--- a/frontend/src/react/pages/project/plan-detail/context/PlanDetailContext.tsx
+++ b/frontend/src/react/pages/project/plan-detail/shell/PlanDetailContext.tsx
@@ -1,5 +1,5 @@
import { createContext, type ReactNode, useContext } from "react";
-import type { PlanDetailPageState } from "../hooks/usePlanDetailPage";
+import type { PlanDetailPageState } from "./hooks/types";
const PlanDetailContext = createContext<PlanDetailPageState | null>(null);
diff --git a/frontend/src/react/pages/project/plan-detail/shell/__tests__/leaveGuard.test.ts b/frontend/src/react/pages/project/plan-detail/shell/__tests__/leaveGuard.test.ts
new file mode 100644
index 0000000000..3a31c5f446
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shell/__tests__/leaveGuard.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, test } from "vitest";
+import { decideLeaveAction } from "../leaveGuard";
+
+describe("decideLeaveAction", () => {
+ test("allows navigation when no scopes are editing", () => {
+ expect(
+ decideLeaveAction({
+ editingScopes: {},
+ isBypassed: false,
+ targetPath: "/x",
+ })
+ ).toEqual({ action: "allow" });
+ });
+
+ test("allows navigation when bypass flag is set", () => {
+ expect(
+ decideLeaveAction({
+ editingScopes: { title: true },
+ isBypassed: true,
+ targetPath: "/x",
+ })
+ ).toEqual({ action: "allow" });
+ });
+
+ test("intercepts when an edit scope is open", () => {
+ expect(
+ decideLeaveAction({
+ editingScopes: { title: true },
+ isBypassed: false,
+ targetPath: "/x",
+ })
+ ).toEqual({ action: "intercept", pendingTarget: "/x" });
+ });
+
+ test("intercepts when multiple scopes are open", () => {
+ expect(
+ decideLeaveAction({
+ editingScopes: { title: true, description: true },
+ isBypassed: false,
+ targetPath: "/y",
+ })
+ ).toEqual({ action: "intercept", pendingTarget: "/y" });
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/shell/constants.ts b/frontend/src/react/pages/project/plan-detail/shell/constants.ts
new file mode 100644
index 0000000000..89b1512762
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shell/constants.ts
@@ -0,0 +1,15 @@
+export const POLLER_INTERVAL = {
+ min: 1000,
+ max: 30000,
+ growth: 2,
+ jitter: 250,
+} as const;
+
+export const PROJECT_NAME_PREFIX = "projects/";
+
+// Width below which the sidebar collapses into a mobile drawer.
+export const MOBILE_BREAKPOINT_PX = 780;
+// Width at or above which the sidebar widens.
+export const WIDE_SIDEBAR_BREAKPOINT_PX = 1280;
+export const SIDEBAR_WIDTH_NARROW_PX = 240;
+export const SIDEBAR_WIDTH_WIDE_PX = 336;
diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/fetchPlanSnapshot.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/fetchPlanSnapshot.ts
new file mode 100644
index 0000000000..eceae8c999
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/fetchPlanSnapshot.ts
@@ -0,0 +1,154 @@
+import { create } from "@bufbuild/protobuf";
+import {
+ issueServiceClientConnect,
+ planServiceClientConnect,
+ projectServiceClientConnect,
+ rolloutServiceClientConnect,
+ userServiceClientConnect,
+} from "@/connect";
+import {
+ GetIssueRequestSchema,
+ type Issue,
+} from "@/types/proto-es/v1/issue_service_pb";
+import {
+ GetPlanCheckRunRequestSchema,
+ GetPlanRequestSchema,
+ type Plan,
+ type PlanCheckRun,
+} from "@/types/proto-es/v1/plan_service_pb";
+import {
+ GetProjectRequestSchema,
+ type Project,
+} from "@/types/proto-es/v1/project_service_pb";
+import {
+ GetRolloutRequestSchema,
+ ListTaskRunsRequestSchema,
+ type Rollout,
+ type TaskRun,
+} from "@/types/proto-es/v1/rollout_service_pb";
+import type { User } from "@/types/proto-es/v1/user_service_pb";
+import { getRolloutFromPlan, hasProjectPermissionV2 } from "@/utils";
+import { createPlanSkeleton } from "../../utils/createPlan";
+import { PROJECT_NAME_PREFIX } from "../constants";
+
+export interface PlanDetailFetchPatch {
+ currentUser: User;
+ plan: Plan;
+ project: Project;
+ projectTitle: string;
+ projectCanCreateRollout: boolean;
+ projectRequireIssueApproval: boolean;
+ projectRequirePlanCheckNoError: boolean;
+ issue: Issue | undefined;
+ rollout: Rollout | undefined;
+ planCheckRuns: PlanCheckRun[];
+ taskRuns: TaskRun[];
+}
+
+const convertRouteQuery = (query: Record<string, unknown>) => {
+ const kv: Record<string, string> = {};
+ for (const [key, value] of Object.entries(query)) {
+ if (typeof value === "string") {
+ kv[key] = value;
+ }
+ }
+ return kv;
+};
+
+export const fetchPlanSnapshot = async (
+ projectId: string,
+ planId: string,
+ routeQuery: Record<string, unknown> = {}
+): Promise<PlanDetailFetchPatch> => {
+ const [project, currentUser] = await Promise.all([
+ projectServiceClientConnect.getProject(
+ create(GetProjectRequestSchema, {
+ name: `${PROJECT_NAME_PREFIX}${projectId}`,
+ })
+ ),
+ userServiceClientConnect.getCurrentUser({}),
+ ]);
+
+ if (planId.toLowerCase() === "create") {
+ const plan = await createPlanSkeleton(
+ project,
+ convertRouteQuery(routeQuery)
+ );
+ return {
+ currentUser,
+ plan,
+ project,
+ projectTitle: project.title,
+ projectCanCreateRollout: hasProjectPermissionV2(
+ project,
+ "bb.rollouts.create"
+ ),
+ projectRequireIssueApproval: project.requireIssueApproval,
+ projectRequirePlanCheckNoError: project.requirePlanCheckNoError,
+ issue: undefined,
+ rollout: undefined,
+ planCheckRuns: [],
+ taskRuns: [],
+ };
+ }
+
+ const plan = await planServiceClientConnect.getPlan(
+ create(GetPlanRequestSchema, {
+ name: `${PROJECT_NAME_PREFIX}${projectId}/plans/${planId}`,
+ })
+ );
+
+ const [issue, planCheckRuns, rollout] = await Promise.all([
+ plan.issue
+ ? issueServiceClientConnect
+ .getIssue(create(GetIssueRequestSchema, { name: plan.issue }))
+ .catch(() => undefined)
+ : Promise.resolve(undefined),
+ planServiceClientConnect
+ .getPlanCheckRun(
+ create(GetPlanCheckRunRequestSchema, {
+ name: `${plan.name}/planCheckRun`,
+ })
+ )
+ .then((run) => [run] as PlanCheckRun[])
+ .catch(() => []),
+ plan.hasRollout
+ ? rolloutServiceClientConnect
+ .getRollout(
+ create(GetRolloutRequestSchema, {
+ name: getRolloutFromPlan(plan.name),
+ })
+ )
+ .catch(() => undefined)
+ : Promise.resolve(undefined),
+ ]);
+
+ const taskRuns =
+ rollout !== undefined
+ ? await rolloutServiceClientConnect
+ .listTaskRuns(
+ create(ListTaskRunsRequestSchema, {
+ parent: `${rollout.name}/stages/-/tasks/-`,
+ })
+ )
+ .then((response) => response.taskRuns)
+ .catch(() => [])
+ : [];
+
+ return {
+ currentUser,
+ plan,
+ project,
+ projectTitle: project.title,
+ projectCanCreateRollout: hasProjectPermissionV2(
+ project,
+ "bb.rollouts.create"
+ ),
+ projectRequireIssueApproval: project.requireIssueApproval,
+ projectRequirePlanCheckNoError: project.requirePlanCheckNoError,
+ issue,
+ rollout,
+ planCheckRuns,
+ taskRuns,
+ };
+};
diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/types.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/types.ts
new file mode 100644
index 0000000000..7a7a5d6e4b
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/types.ts
@@ -0,0 +1,62 @@
+import { type Issue } from "@/types/proto-es/v1/issue_service_pb";
+import type { Plan, PlanCheckRun } from "@/types/proto-es/v1/plan_service_pb";
+import type { Project } from "@/types/proto-es/v1/project_service_pb";
+import {
+ type Rollout,
+ type TaskRun,
+} from "@/types/proto-es/v1/rollout_service_pb";
+import type { User } from "@/types/proto-es/v1/user_service_pb";
+import type { PlanDetailPhase } from "../../shared/stores/types";
+import type { PlanDetailSidebarMode } from "./useSidebarMode";
+
+export type { PlanDetailPhase } from "../../shared/stores/types";
+
+export interface PlanDetailPageSnapshot {
+ projectId: string;
+ planId: string;
+ specId?: string;
+ pageKey: string;
+ projectTitle: string;
+ projectRequireIssueApproval: boolean;
+ projectRequirePlanCheckNoError: boolean;
+ projectCanCreateRollout: boolean;
+ currentUser: User;
+ project: Project;
+ isCreating: boolean;
+ isInitializing: boolean;
+ ready: boolean;
+ readonly: boolean;
+ plan: Plan;
+ issue?: Issue;
+ rollout?: Rollout;
+ planCheckRuns: PlanCheckRun[];
+ taskRuns: TaskRun[];
+}
+
+export interface PlanDetailPageState extends PlanDetailPageSnapshot {
+ isEditing: boolean;
+ isRefreshing: boolean;
+ isRunningChecks: boolean;
+ setIsRunningChecks: (running: boolean) => void;
+ lastRefreshTime: number;
+ activePhases: Set<PlanDetailPhase>;
+ routeName?: string;
+ routePhase?: string;
+ routeStageId?: string;
+ routeTaskId?: string;
+ selectedTaskName?: string;
+ pendingLeaveConfirm: boolean;
+ sidebarMode: PlanDetailSidebarMode;
+ containerWidth: number;
+ desktopSidebarWidth: number;
+ mobileSidebarOpen: boolean;
+ patchState: (patch: Partial<PlanDetailPageSnapshot>) => void;
+ refreshState: () => Promise<void>;
+ bypassLeaveGuardOnce: () => void;
+ setEditing: (scope: string, editing: boolean) => void;
+ setMobileSidebarOpen: (open: boolean) => void;
+ togglePhase: (phase: PlanDetailPhase) => void;
+ expandPhase: (phase: PlanDetailPhase) => void;
+ closeTaskPanel: () => void;
+ resolveLeaveConfirm: (confirmed: boolean) => void;
+}
diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/useDerivedPlanState.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/useDerivedPlanState.ts
new file mode 100644
index 0000000000..bd6129d475
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/useDerivedPlanState.ts
@@ -0,0 +1,118 @@
+import { useMemo } from "react";
+import type {
+ PlanDetailPageSnapshot,
+ PlanDetailPageState,
+ PlanDetailPhase,
+} from "./types";
+import type { useEditingScopes } from "./useEditingScopes";
+import type { usePhaseState } from "./usePhaseState";
+import type { useSidebarMode } from "./useSidebarMode";
+
+type EditingScopes = ReturnType<typeof useEditingScopes>;
+type PhaseState = ReturnType<typeof usePhaseState>;
+type Sidebar = ReturnType<typeof useSidebarMode>;
+
+export function useDerivedPlanState(params: {
+ snapshot: PlanDetailPageSnapshot;
+ isEditing: boolean;
+ isRefreshing: boolean;
+ isRunningChecks: boolean;
+ setIsRunningChecks: (running: boolean) => void;
+ lastRefreshTime: number;
+ phase: PhaseState;
+ editing: EditingScopes;
+ sidebar: Sidebar;
+ routeName?: string;
+ routePhase?: PlanDetailPhase;
+ routeStageId?: string;
+ routeTaskId?: string;
+ patchState: (patch: Partial<PlanDetailPageSnapshot>) => void;
+ refreshState: () => Promise<void>;
+ closeTaskPanel: () => void;
+ resolveLeaveConfirm: (confirmed: boolean) => void;
+}): PlanDetailPageState {
+ const {
+ snapshot,
+ isEditing,
+ isRefreshing,
+ isRunningChecks,
+ setIsRunningChecks,
+ lastRefreshTime,
+ phase,
+ editing,
+ sidebar,
+ routeName,
+ routePhase,
+ routeStageId,
+ routeTaskId,
+ patchState,
+ refreshState,
+ closeTaskPanel,
+ resolveLeaveConfirm,
+ } = params;
+
+ const selectedTaskName = useMemo(() => {
+ if (!routeTaskId || !snapshot.rollout) {
+ return undefined;
+ }
+ for (const stage of snapshot.rollout.stages) {
+ const task = stage.tasks.find((item) =>
+ item.name.endsWith(`/${routeTaskId}`)
+ );
+ if (task) {
+ return task.name;
+ }
+ }
+ return undefined;
+ }, [routeTaskId, snapshot.rollout]);
+
+ return useMemo(
+ () => ({
+ ...snapshot,
+ isEditing,
+ isRefreshing,
+ isRunningChecks,
+ setIsRunningChecks,
+ lastRefreshTime,
+ activePhases: phase.activePhases,
+ routeName,
+ routePhase,
+ routeStageId,
+ routeTaskId,
+ selectedTaskName,
+ pendingLeaveConfirm: editing.pendingLeaveConfirm,
+ sidebarMode: sidebar.sidebarMode,
+ containerWidth: sidebar.containerWidth,
+ desktopSidebarWidth: sidebar.sidebarWidth,
+ mobileSidebarOpen: sidebar.isMobileSidebarOpen,
+ bypassLeaveGuardOnce: editing.bypassLeaveGuardOnce,
+ patchState,
+ refreshState,
+ setEditing: editing.setEditing,
+ setMobileSidebarOpen: sidebar.setMobileSidebarOpen,
+ togglePhase: phase.togglePhase,
+ expandPhase: phase.expandPhase,
+ closeTaskPanel,
+ resolveLeaveConfirm,
+ }),
+ [
+ closeTaskPanel,
+ editing,
+ isEditing,
+ isRefreshing,
+ isRunningChecks,
+ lastRefreshTime,
+ patchState,
+ phase,
+ refreshState,
+ resolveLeaveConfirm,
+ routeName,
+ routePhase,
+ routeStageId,
+ routeTaskId,
+ selectedTaskName,
+ sidebar,
+ snapshot,
+ ]
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/useEditingScopes.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/useEditingScopes.ts
new file mode 100644
index 0000000000..8edd99533e
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/useEditingScopes.ts
@@ -0,0 +1,33 @@
+import { useCallback, useMemo } from "react";
+import { usePlanDetailStore } from "../../shared/stores/usePlanDetailStore";
+
+export function useEditingScopes() {
+ const editingScopes = usePlanDetailStore((s) => s.editingScopes);
+ const setEditing = usePlanDetailStore((s) => s.setEditing);
+ const bypassLeaveGuardOnce = usePlanDetailStore(
+ (s) => s.bypassLeaveGuardOnce
+ );
+ const pendingLeaveConfirm = usePlanDetailStore((s) => s.pendingLeaveConfirm);
+ const setPendingLeaveConfirm = usePlanDetailStore(
+ (s) => s.setPendingLeaveConfirm
+ );
+
+ const isEditing = useMemo(
+ () => Object.keys(editingScopes).length > 0,
+ [editingScopes]
+ );
+
+ const setScopeEditing = useCallback(
+ (scope: string, editing: boolean) => setEditing(scope, editing),
+ [setEditing]
+ );
+
+ return {
+ editingScopes,
+ isEditing,
+ setEditing: setScopeEditing,
+ bypassLeaveGuardOnce,
+ pendingLeaveConfirm,
+ setPendingLeaveConfirm,
+ };
+}
diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/useInitialFetch.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/useInitialFetch.ts
new file mode 100644
index 0000000000..09d5e778c1
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/useInitialFetch.ts
@@ -0,0 +1,90 @@
+import { Code, ConnectError } from "@connectrpc/connect";
+import type { MutableRefObject } from "react";
+import { useEffect } from "react";
+import { router } from "@/router";
+import {
+ WORKSPACE_ROUTE_403,
+ WORKSPACE_ROUTE_404,
+} from "@/router/dashboard/workspaceRoutes";
+import { unknownPlan } from "@/types/v1/issue/plan";
+import type { PlanDetailStoreApi } from "../../shared/stores/usePlanDetailStore";
+import { fetchPlanSnapshot } from "./fetchPlanSnapshot";
+import type { PlanDetailPageSnapshot } from "./types";
+
+export interface UseInitialFetchParams {
+ projectId: string;
+ planId: string;
+ specId?: string;
+ routeQueryRef: MutableRefObject<Record<string, unknown>>;
+ storeApi: PlanDetailStoreApi;
+ patchState: (patch: Partial<PlanDetailPageSnapshot>) => void;
+}
+
+export function useInitialFetch({
+ projectId,
+ planId,
+ specId,
+ routeQueryRef,
+ storeApi,
+ patchState,
+}: UseInitialFetchParams): void {
+ useEffect(() => {
+ storeApi.setState({ editingScopes: {} });
+ patchState({
+ projectId,
+ planId,
+ specId,
+ pageKey: `${projectId}/${planId}/${specId ?? ""}`,
+ projectTitle: "",
+ isCreating: planId.toLowerCase() === "create",
+ isInitializing: true,
+ plan: unknownPlan(),
+ issue: undefined,
+ rollout: undefined,
+ planCheckRuns: [],
+ taskRuns: [],
+ });
+
+ let canceled = false;
+
+ const load = async () => {
+ try {
+ const patch = await fetchPlanSnapshot(
+ projectId,
+ planId,
+ routeQueryRef.current
+ );
+ if (canceled) {
+ return;
+ }
+ patchState({
+ ...patch,
+ isInitializing: false,
+ specId,
+ });
+ } catch (error) {
+ if (canceled) {
+ return;
+ }
+ if (error instanceof ConnectError) {
+ if (error.code === Code.NotFound) {
+ void router.push({ name: WORKSPACE_ROUTE_404 });
+ } else if (error.code === Code.PermissionDenied) {
+ void router.push({ name: WORKSPACE_ROUTE_403 });
+ }
+ patchState({ isInitializing: false });
+ return;
+ }
+
+ patchState({ isInitializing: false });
+ throw error;
+ }
+ };
+
+ void load();
+
+ return () => {
+ canceled = true;
+ };
+ }, [patchState, planId, projectId, routeQueryRef, specId, storeApi]);
+}
diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/useLeaveGuard.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/useLeaveGuard.ts
new file mode 100644
index 0000000000..7254828506
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/useLeaveGuard.ts
@@ -0,0 +1,90 @@
+import { useCallback, useEffect } from "react";
+import { useTranslation } from "react-i18next";
+import { router } from "@/router";
+import {
+ usePlanDetailStore,
+ usePlanDetailStoreApi,
+} from "../../shared/stores/usePlanDetailStore";
+import { decideLeaveAction } from "../leaveGuard";
+
+export function useLeaveGuard() {
+ const { t } = useTranslation();
+ const storeApi = usePlanDetailStoreApi();
+ const editingScopes = usePlanDetailStore((s) => s.editingScopes);
+ const setPendingLeaveTarget = usePlanDetailStore(
+ (s) => s.setPendingLeaveTarget
+ );
+ const setPendingLeaveConfirm = usePlanDetailStore(
+ (s) => s.setPendingLeaveConfirm
+ );
+
+ const isEditing = Object.keys(editingScopes).length > 0;
+
+ const resolveLeaveConfirm = useCallback(
+ (confirmed: boolean) => {
+ const state = storeApi.getState();
+ const target = confirmed ? state.pendingLeaveTarget : null;
+ setPendingLeaveTarget(null);
+ setPendingLeaveConfirm(false);
+ if (target) {
+ state.bypassLeaveGuardOnce();
+ // Replace (not push) so a confirmed-discard navigation doesn't leave
+ // an extra entry that lets Back return to the discarded plan. Works
+ // correctly whether the original navigation was push, replace, or
+ // browser back/forward.
+ void router.replace(target);
+ }
+ },
+ [setPendingLeaveConfirm, setPendingLeaveTarget, storeApi]
+ );
+
+ useEffect(() => {
+ if (!isEditing) {
+ // Editing scope ended (e.g. async save completed) while a leave
+ // prompt is open — there's nothing unsaved anymore, so navigate to
+ // the captured target without further confirmation.
+ if (storeApi.getState().pendingLeaveTarget) {
+ resolveLeaveConfirm(true);
+ }
+ return;
+ }
+
+ const onBeforeUnload = (event: BeforeUnloadEvent) => {
+ event.returnValue = t("common.leave-without-saving");
+ event.preventDefault();
+ };
+ window.addEventListener("beforeunload", onBeforeUnload);
+ const removeGuard = router.beforeEach((to, _from, next) => {
+ const state = storeApi.getState();
+ const decision = decideLeaveAction({
+ editingScopes: state.editingScopes,
+ isBypassed: state.isLeaveGuardBypassed(),
+ targetPath: to.fullPath,
+ });
+ if (decision.action === "allow") {
+ next();
+ return;
+ }
+ // Cancel the navigation synchronously and remember the target so we
+ // can re-issue it from resolveLeaveConfirm after the user confirms.
+ // Always overwrite the pending target — the latest navigation wins.
+ setPendingLeaveTarget(decision.pendingTarget);
+ setPendingLeaveConfirm(true);
+ next(false);
+ });
+
+ return () => {
+ window.removeEventListener("beforeunload", onBeforeUnload);
+ removeGuard();
+ };
+ }, [
+ isEditing,
+ resolveLeaveConfirm,
+ setPendingLeaveConfirm,
+ setPendingLeaveTarget,
+ storeApi,
+ t,
+ ]);
+
+ return { resolveLeaveConfirm };
+}
diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePhaseState.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePhaseState.ts
new file mode 100644
index 0000000000..e9390887ae
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePhaseState.ts
@@ -0,0 +1,17 @@
+import { useCallback } from "react";
+import type { PlanDetailPhase } from "../../shared/stores/types";
+import { usePlanDetailStore } from "../../shared/stores/usePlanDetailStore";
+
+export function usePhaseState() {
+ const activePhases = usePlanDetailStore((s) => s.activePhases);
+ const togglePhase = usePlanDetailStore((s) => s.togglePhase);
+ const expandPhase = usePlanDetailStore((s) => s.expandPhase);
+ const collapsePhase = usePlanDetailStore((s) => s.collapsePhase);
+
+ const isActive = useCallback(
+ (phase: PlanDetailPhase) => activePhases.has(phase),
+ [activePhases]
+ );
+
+ return { activePhases, isActive, togglePhase, expandPhase, collapsePhase };
+}
diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.ts
new file mode 100644
index 0000000000..acbb98af67
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.ts
@@ -0,0 +1,228 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { router } from "@/router";
+import {
+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,
+} from "@/router/dashboard/projectV1";
+import { PLAN_DETAIL_PHASE_DEPLOY } from "@/router/dashboard/projectV1RouteHelpers";
+import { State } from "@/types/proto-es/v1/common_pb";
+import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";
+import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
+import { unknownPlan } from "@/types/v1/issue/plan";
+import { unknownProject } from "@/types/v1/project";
+import { unknownUser } from "@/types/v1/user";
+import { setDocumentTitle } from "@/utils";
+import { usePlanDetailStoreApi } from "../../shared/stores/usePlanDetailStore";
+import { fetchPlanSnapshot } from "./fetchPlanSnapshot";
+import type { PlanDetailPageSnapshot, PlanDetailPageState } from "./types";
+import { useDerivedPlanState } from "./useDerivedPlanState";
+import { useEditingScopes } from "./useEditingScopes";
+import { useInitialFetch } from "./useInitialFetch";
+import { useLeaveGuard } from "./useLeaveGuard";
+import { usePhaseState } from "./usePhaseState";
+import { usePolling } from "./usePolling";
+import { useRedirects } from "./useRedirects";
+import { useRouteSelection } from "./useRouteSelection";
+import { useSidebarMode } from "./useSidebarMode";
+
+const buildDefaultSnapshot = (
+ projectId: string,
+ planId: string,
+ specId?: string
+): PlanDetailPageSnapshot => ({
+ projectId,
+ planId,
+ specId,
+ pageKey: `${projectId}/${planId}/${specId ?? ""}`,
+ projectTitle: "",
+ projectRequireIssueApproval: true,
+ projectRequirePlanCheckNoError: true,
+ projectCanCreateRollout: false,
+ currentUser: unknownUser(),
+ project: unknownProject(),
+ isCreating: planId.toLowerCase() === "create",
+ isInitializing: true,
+ ready: false,
+ readonly: true,
+ plan: unknownPlan(),
+ issue: undefined,
+ rollout: undefined,
+ planCheckRuns: [],
+ taskRuns: [],
+});
+
+const applyDerivedState = (
+ snapshot: PlanDetailPageSnapshot
+): PlanDetailPageSnapshot => {
+ const readonly =
+ snapshot.plan.state === State.DELETED ||
+ (snapshot.issue ? snapshot.issue.status !== IssueStatus.OPEN : false);
+ return {
+ ...snapshot,
+ readonly,
+ ready: !snapshot.isInitializing && !!snapshot.plan.name,
+ };
+};
+
+export const usePlanDetailPage = ({
+ projectId,
+ planId,
+ routeName,
+ routeQuery = {},
+ specId,
+ pageHost,
+}: {
+ projectId: string;
+ planId: string;
+ routeName?: string;
+ routeQuery?: Record<string, unknown>;
+ specId?: string;
+ pageHost: HTMLDivElement | null;
+}): PlanDetailPageState => {
+ const { t } = useTranslation();
+ const [snapshot, setSnapshot] = useState<PlanDetailPageSnapshot>(() =>
+ buildDefaultSnapshot(projectId, planId, specId)
+ );
+ const phase = usePhaseState();
+ const editing = useEditingScopes();
+ const storeApi = usePlanDetailStoreApi();
+ const sidebar = useSidebarMode(pageHost);
+ const [isRefreshing, setIsRefreshing] = useState(false);
+ const [isRunningChecks, setIsRunningChecks] = useState(false);
+ const [lastRefreshTime, setLastRefreshTime] = useState(0);
+ const latestSnapshotRef = useRef(snapshot);
+ const { resolveLeaveConfirm } = useLeaveGuard();
+ const isEditing = editing.isEditing;
+
+ // 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.
+ const routeQueryRef = useRef(routeQuery);
+ routeQueryRef.current = routeQuery;
+ const route = useRouteSelection({ routeQuery, specId });
+ const routePhase = route.phase;
+ const routeStageId = route.stageId;
+ const routeTaskId = route.taskId;
+
+ useEffect(() => {
+ latestSnapshotRef.current = snapshot;
+ }, [snapshot]);
+
+ const patchState = useCallback((patch: Partial<PlanDetailPageSnapshot>) => {
+ setSnapshot((prev) => applyDerivedState({ ...prev, ...patch }));
+ }, []);
+
+ const refreshState = useCallback(async () => {
+ try {
+ setIsRefreshing(true);
+ const current = latestSnapshotRef.current;
+ const patch = await fetchPlanSnapshot(
+ current.projectId,
+ current.planId,
+ routeQueryRef.current
+ );
+ patchState(patch);
+ setLastRefreshTime(Date.now());
+ } finally {
+ setIsRefreshing(false);
+ }
+ }, [patchState]);
+
+ const closeTaskPanel = useCallback(() => {
+ void router.replace({
+ query: {
+ ...(routePhase ? { phase: routePhase } : {}),
+ ...(routeStageId ? { stageId: routeStageId } : {}),
+ },
+ });
+ }, [routePhase, routeStageId]);
+
+ useInitialFetch({
+ projectId,
+ planId,
+ specId,
+ routeQueryRef,
+ storeApi,
+ patchState,
+ });
+
+ useEffect(() => {
+ if (snapshot.isCreating) {
+ setDocumentTitle(t("plan.new-plan"), snapshot.projectTitle);
+ return;
+ }
+ if (snapshot.ready && snapshot.plan.title) {
+ setDocumentTitle(snapshot.plan.title, snapshot.projectTitle);
+ }
+ }, [
+ snapshot.isCreating,
+ snapshot.plan.title,
+ snapshot.projectTitle,
+ snapshot.ready,
+ t,
+ ]);
+
+ useRedirects({
+ ready: snapshot.ready,
+ plan: snapshot.plan,
+ issue: snapshot.issue,
+ });
+
+ useEffect(() => {
+ if (
+ routeName === PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS ||
+ routeName === PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL
+ ) {
+ phase.expandPhase("changes");
+ }
+ if (
+ routePhase === PLAN_DETAIL_PHASE_DEPLOY ||
+ routeStageId ||
+ routeTaskId
+ ) {
+ phase.expandPhase("deploy");
+ }
+ }, [phase, routeName, routePhase, routeStageId, routeTaskId]);
+
+ const isPlanDone = useMemo(() => {
+ if (!snapshot.rollout) {
+ return false;
+ }
+ const allTasks = snapshot.rollout.stages.flatMap((stage) => stage.tasks);
+ return (
+ allTasks.length > 0 &&
+ allTasks.every(
+ (task) =>
+ task.status === Task_Status.DONE ||
+ task.status === Task_Status.SKIPPED
+ )
+ );
+ }, [snapshot.rollout]);
+
+ usePolling({
+ enabled: snapshot.ready && !snapshot.isCreating && !isPlanDone,
+ refreshState,
+ });
+
+ return useDerivedPlanState({
+ snapshot,
+ isEditing,
+ isRefreshing,
+ isRunningChecks,
+ setIsRunningChecks,
+ lastRefreshTime,
+ phase,
+ editing,
+ sidebar,
+ routeName,
+ routePhase,
+ routeStageId,
+ routeTaskId,
+ patchState,
+ refreshState,
+ closeTaskPanel,
+ resolveLeaveConfirm,
+ });
+};
diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePolling.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePolling.ts
new file mode 100644
index 0000000000..e28710d907
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePolling.ts
@@ -0,0 +1,60 @@
+import { useCallback, useEffect, useRef } from "react";
+import { minmax } from "@/utils";
+import { POLLER_INTERVAL } from "../constants";
+
+export interface UsePollingParams {
+ enabled: boolean;
+ refreshState: () => Promise<void>;
+}
+
+export function usePolling({ enabled, refreshState }: UsePollingParams): void {
+ const pollTimerRef = useRef<number | undefined>(undefined);
+
+ const stopPolling = useCallback(() => {
+ if (!pollTimerRef.current) {
+ return;
+ }
+ window.clearTimeout(pollTimerRef.current);
+ pollTimerRef.current = undefined;
+ }, []);
+
+ useEffect(() => {
+ if (!enabled) {
+ stopPolling();
+ return;
+ }
+
+ let canceled = false;
+
+ const poll = (interval: number) => {
+ stopPolling();
+ const nextInterval = minmax(
+ interval +
+ Math.floor(Math.random() * (POLLER_INTERVAL.jitter * 2 + 1)) -
+ POLLER_INTERVAL.jitter,
+ POLLER_INTERVAL.min,
+ POLLER_INTERVAL.max
+ );
+
+ pollTimerRef.current = window.setTimeout(async () => {
+ if (canceled) {
+ return;
+ }
+ await refreshState().catch(() => undefined);
+ if (canceled) {
+ return;
+ }
+ poll(
+ Math.min(nextInterval * POLLER_INTERVAL.growth, POLLER_INTERVAL.max)
+ );
+ }, nextInterval);
+ };
+
+ poll(POLLER_INTERVAL.min);
+
+ return () => {
+ canceled = true;
+ stopPolling();
+ };
+ }, [enabled, refreshState, stopPolling]);
+}
diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/useRedirects.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/useRedirects.ts
new file mode 100644
index 0000000000..0a3664bc64
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/useRedirects.ts
@@ -0,0 +1,34 @@
+import { useEffect } from "react";
+import { router } from "@/router";
+import { type Issue } from "@/types/proto-es/v1/issue_service_pb";
+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
+import { getIssueRoute } from "@/utils";
+
+const shouldRedirectToIssueDetail = (plan: Plan, issue?: Issue) => {
+ if (!issue?.name) {
+ return false;
+ }
+ if (plan.specs.length === 0) {
+ return false;
+ }
+ return plan.specs.every((spec) => {
+ return (
+ spec.config?.case === "createDatabaseConfig" ||
+ spec.config?.case === "exportDataConfig"
+ );
+ });
+};
+
+export function useRedirects(params: {
+ ready: boolean;
+ plan: Plan;
+ issue?: Issue;
+}) {
+ const { ready, plan, issue } = params;
+
+ useEffect(() => {
+ if (ready && shouldRedirectToIssueDetail(plan, issue)) {
+ void router.replace(getIssueRoute({ name: issue?.name ?? "" }));
+ }
+ }, [issue, plan, ready]);
+}
diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/useRouteSelection.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/useRouteSelection.ts
new file mode 100644
index 0000000000..bf17ef0f07
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/useRouteSelection.ts
@@ -0,0 +1,28 @@
+import { useEffect } from "react";
+import { getRouteQueryString } from "@/router/dashboard/projectV1RouteHelpers";
+import type { PlanDetailPhase } from "../../shared/stores/types";
+import { usePlanDetailStore } from "../../shared/stores/usePlanDetailStore";
+
+export function useRouteSelection(params: {
+ routeQuery: Record<string, unknown>;
+ specId?: 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);
+
+ useEffect(() => {
+ setRouteSelection({
+ phase,
+ stageId,
+ taskName: taskId,
+ specId: params.specId,
+ });
+ }, [setRouteSelection, phase, stageId, taskId, params.specId]);
+
+ return { phase, stageId, taskId };
+}
diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/useSidebarMode.ts b/frontend/src/react/pages/project/plan-detail/shell/hooks/useSidebarMode.ts
new file mode 100644
index 0000000000..60ddcf6397
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/useSidebarMode.ts
@@ -0,0 +1,62 @@
+import { useEffect, useRef, useState } from "react";
+import {
+ MOBILE_BREAKPOINT_PX,
+ SIDEBAR_WIDTH_NARROW_PX,
+ SIDEBAR_WIDTH_WIDE_PX,
+ WIDE_SIDEBAR_BREAKPOINT_PX,
+} from "../constants";
+
+export type PlanDetailSidebarMode = "NONE" | "DESKTOP" | "MOBILE";
+
+export function useSidebarMode(pageHost: HTMLElement | null) {
+ const [sidebarMode, setSidebarMode] = useState<PlanDetailSidebarMode>("NONE");
+ const [containerWidth, setContainerWidth] = useState(0);
+ const [sidebarWidth, setSidebarWidth] = useState(0);
+ const [isMobileSidebarOpen, setMobileSidebarOpen] = useState(false);
+ const isMobileSidebarOpenRef = useRef(isMobileSidebarOpen);
+ isMobileSidebarOpenRef.current = isMobileSidebarOpen;
+
+ useEffect(() => {
+ if (!pageHost) {
+ setSidebarMode("NONE");
+ setContainerWidth(0);
+ setSidebarWidth(0);
+ setMobileSidebarOpen(false);
+ return;
+ }
+
+ const updateSidebar = () => {
+ const width = pageHost.getBoundingClientRect().width;
+ const mode: PlanDetailSidebarMode =
+ width === 0
+ ? "NONE"
+ : width < MOBILE_BREAKPOINT_PX
+ ? "MOBILE"
+ : "DESKTOP";
+ setContainerWidth(width);
+ setSidebarWidth(
+ width < WIDE_SIDEBAR_BREAKPOINT_PX
+ ? SIDEBAR_WIDTH_NARROW_PX
+ : SIDEBAR_WIDTH_WIDE_PX
+ );
+ setSidebarMode(mode);
+ if (mode !== "MOBILE") {
+ setMobileSidebarOpen(false);
+ }
+ };
+
+ updateSidebar();
+ const observer = new ResizeObserver(() => updateSidebar());
+ observer.observe(pageHost);
+
+ return () => observer.disconnect();
+ }, [pageHost]);
+
+ return {
+ sidebarMode,
+ containerWidth,
+ sidebarWidth,
+ isMobileSidebarOpen,
+ setMobileSidebarOpen,
+ };
+}
diff --git a/frontend/src/react/pages/project/plan-detail/shell/leaveGuard.ts b/frontend/src/react/pages/project/plan-detail/shell/leaveGuard.ts
new file mode 100644
index 0000000000..448db450eb
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shell/leaveGuard.ts
@@ -0,0 +1,14 @@
+export type LeaveAction =
+ | { action: "allow" }
+ | { action: "intercept"; pendingTarget: string };
+
+export function decideLeaveAction(input: {
+ editingScopes: Record<string, true>;
+ isBypassed: boolean;
+ targetPath: string;
+}): LeaveAction {
+ if (input.isBypassed) return { action: "allow" };
+ const hasEditing = Object.keys(input.editingScopes).length > 0;
+ if (!hasEditing) return { action: "allow" };
+ return { action: "intercept", pendingTarget: input.targetPath };
+}
diff --git a/frontend/src/react/stores/app/database.ts b/frontend/src/react/stores/app/database.ts
new file mode 100644
index 0000000000..2544032b03
--- /dev/null
+++ b/frontend/src/react/stores/app/database.ts
@@ -0,0 +1,110 @@
+import { create as createProto } from "@bufbuild/protobuf";
+import { databaseServiceClientConnect } from "@/connect";
+import {
+ BatchGetDatabasesRequestSchema,
+ type Database,
+ GetDatabaseRequestSchema,
+ ListDatabasesRequestSchema,
+} from "@/types/proto-es/v1/database_service_pb";
+import { isValidDatabaseName } from "@/types/v1/database";
+import type { AppSliceCreator, DatabaseSlice } from "./types";
+
+function toError(error: unknown): Error {
+ if (error instanceof Error) return error;
+ return new Error(String(error));
+}
+
+export const createDatabaseSlice: AppSliceCreator<DatabaseSlice> = (
+ set,
+ get
+) => ({
+ databasesByName: {},
+ databaseRequests: {},
+ databaseErrorsByName: {},
+
+ fetchDatabase: async (name) => {
+ if (!isValidDatabaseName(name)) return undefined;
+ const existing = get().databasesByName[name];
+ if (existing) return existing;
+ const pending = get().databaseRequests[name];
+ if (pending) return pending;
+
+ const request = databaseServiceClientConnect
+ .getDatabase(createProto(GetDatabaseRequestSchema, { name }))
+ .then((database: Database) => {
+ set((state) => {
+ const { [name]: _, ...databaseRequests } = state.databaseRequests;
+ return {
+ databasesByName: {
+ ...state.databasesByName,
+ [database.name]: database,
+ },
+ databaseErrorsByName: {
+ ...state.databaseErrorsByName,
+ [name]: undefined,
+ },
+ databaseRequests,
+ };
+ });
+ return database;
+ })
+ .catch((error) => {
+ set((state) => {
+ const { [name]: _, ...databaseRequests } = state.databaseRequests;
+ return {
+ databaseErrorsByName: {
+ ...state.databaseErrorsByName,
+ [name]: toError(error),
+ },
+ databaseRequests,
+ };
+ });
+ return undefined;
+ });
+ set((state) => ({
+ databaseRequests: {
+ ...state.databaseRequests,
+ [name]: request,
+ },
+ }));
+ return request;
+ },
+
+ batchFetchDatabases: async (names) => {
+ if (!names.length) return [];
+ const response = await databaseServiceClientConnect.batchGetDatabases(
+ createProto(BatchGetDatabasesRequestSchema, { parent: "-", names })
+ );
+ set((state) => {
+ const next = { ...state.databasesByName };
+ for (const db of response.databases) {
+ next[db.name] = db;
+ }
+ return { databasesByName: next };
+ });
+ return response.databases;
+ },
+
+ fetchDatabases: async ({ parent, pageSize, pageToken, filter, orderBy }) => {
+ const response = await databaseServiceClientConnect.listDatabases(
+ createProto(ListDatabasesRequestSchema, {
+ parent,
+ pageSize,
+ pageToken: pageToken ?? "",
+ filter: filter ?? "",
+ orderBy: orderBy ?? "",
+ })
+ );
+ set((state) => {
+ const next = { ...state.databasesByName };
+ for (const db of response.databases) {
+ next[db.name] = db;
+ }
+ return { databasesByName: next };
+ });
+ return {
+ databases: response.databases,
+ nextPageToken: response.nextPageToken,
+ };
+ },
+});
diff --git a/frontend/src/react/stores/app/dbGroup.ts b/frontend/src/react/stores/app/dbGroup.ts
new file mode 100644
index 0000000000..a11dc3e7d4
--- /dev/null
+++ b/frontend/src/react/stores/app/dbGroup.ts
@@ -0,0 +1,85 @@
+import { create as createProto } from "@bufbuild/protobuf";
+import { databaseGroupServiceClientConnect } from "@/connect";
+import { isValidDatabaseGroupName } from "@/types/dbGroup";
+import {
+ type DatabaseGroup,
+ GetDatabaseGroupRequestSchema,
+ ListDatabaseGroupsRequestSchema,
+} from "@/types/proto-es/v1/database_group_service_pb";
+import type { AppSliceCreator, DBGroupSlice } from "./types";
+
+function toError(error: unknown): Error {
+ if (error instanceof Error) return error;
+ return new Error(String(error));
+}
+
+export const createDBGroupSlice: AppSliceCreator<DBGroupSlice> = (
+ set,
+ get
+) => ({
+ dbGroupsByName: {},
+ dbGroupRequests: {},
+ dbGroupErrorsByName: {},
+
+ fetchDBGroup: async (name) => {
+ if (!isValidDatabaseGroupName(name)) return undefined;
+ const existing = get().dbGroupsByName[name];
+ if (existing) return existing;
+ const pending = get().dbGroupRequests[name];
+ if (pending) return pending;
+
+ const request = databaseGroupServiceClientConnect
+ .getDatabaseGroup(createProto(GetDatabaseGroupRequestSchema, { name }))
+ .then((group: DatabaseGroup) => {
+ set((state) => {
+ const { [name]: _, ...dbGroupRequests } = state.dbGroupRequests;
+ return {
+ dbGroupsByName: {
+ ...state.dbGroupsByName,
+ [group.name]: group,
+ },
+ dbGroupErrorsByName: {
+ ...state.dbGroupErrorsByName,
+ [name]: undefined,
+ },
+ dbGroupRequests,
+ };
+ });
+ return group;
+ })
+ .catch((error) => {
+ set((state) => {
+ const { [name]: _, ...dbGroupRequests } = state.dbGroupRequests;
+ return {
+ dbGroupErrorsByName: {
+ ...state.dbGroupErrorsByName,
+ [name]: toError(error),
+ },
+ dbGroupRequests,
+ };
+ });
+ return undefined;
+ });
+ set((state) => ({
+ dbGroupRequests: {
+ ...state.dbGroupRequests,
+ [name]: request,
+ },
+ }));
+ return request;
+ },
+
+ listDBGroupsForProject: async (project) => {
+ const response = await databaseGroupServiceClientConnect.listDatabaseGroups(
+ createProto(ListDatabaseGroupsRequestSchema, { parent: project })
+ );
+ set((state) => {
+ const next = { ...state.dbGroupsByName };
+ for (const group of response.databaseGroups) {
+ next[group.name] = group;
+ }
+ return { dbGroupsByName: next };
+ });
+ return response.databaseGroups;
+ },
+});
diff --git a/frontend/src/react/stores/app/index.test.ts b/frontend/src/react/stores/app/index.test.ts
index ab992d2628..323dbbe793 100644
--- a/frontend/src/react/stores/app/index.test.ts
+++ b/frontend/src/react/stores/app/index.test.ts
@@ -4,10 +4,13 @@ import { ReactShellBridgeEvent } from "@/react/shell-bridge";
import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";
import { ActuatorInfoSchema } from "@/types/proto-es/v1/actuator_service_pb";
import { State } from "@/types/proto-es/v1/common_pb";
+import { DatabaseGroupSchema } from "@/types/proto-es/v1/database_group_service_pb";
+import { DatabaseSchema$ } from "@/types/proto-es/v1/database_service_pb";
import {
BindingSchema,
IamPolicySchema,
} from "@/types/proto-es/v1/iam_policy_pb";
+import { InstanceRoleSchema } from "@/types/proto-es/v1/instance_role_service_pb";
import { InstanceSchema } from "@/types/proto-es/v1/instance_service_pb";
import { ProjectSchema } from "@/types/proto-es/v1/project_service_pb";
import { RoleSchema } from "@/types/proto-es/v1/role_service_pb";
@@ -19,6 +22,7 @@ import {
SettingValueSchema,
WorkspaceProfileSettingSchema,
} from "@/types/proto-es/v1/setting_service_pb";
+import { SheetSchema } from "@/types/proto-es/v1/sheet_service_pb";
import {
PlanFeature,
PlanType,
@@ -61,6 +65,14 @@ const mocks = vi.hoisted(() => ({
searchProjects: vi.fn(),
createProject: vi.fn(),
getInstance: vi.fn(),
+ getDatabase: vi.fn(),
+ batchGetDatabases: vi.fn(),
+ listDatabases: vi.fn(),
+ getDatabaseGroup: vi.fn(),
+ listDatabaseGroups: vi.fn(),
+ getSheet: vi.fn(),
+ createSheet: vi.fn(),
+ listInstanceRoles: vi.fn(),
}));
vi.mock("@/connect", () => ({
@@ -80,6 +92,22 @@ vi.mock("@/connect", () => ({
instanceServiceClientConnect: {
getInstance: mocks.getInstance,
},
+ databaseServiceClientConnect: {
+ getDatabase: mocks.getDatabase,
+ batchGetDatabases: mocks.batchGetDatabases,
+ listDatabases: mocks.listDatabases,
+ },
+ databaseGroupServiceClientConnect: {
+ getDatabaseGroup: mocks.getDatabaseGroup,
+ listDatabaseGroups: mocks.listDatabaseGroups,
+ },
+ sheetServiceClientConnect: {
+ getSheet: mocks.getSheet,
+ createSheet: mocks.createSheet,
+ },
+ instanceRoleServiceClientConnect: {
+ listInstanceRoles: mocks.listInstanceRoles,
+ },
roleServiceClientConnect: {
listRoles: mocks.listRoles,
},
@@ -566,6 +594,104 @@ describe("useAppStore", () => {
expect(store.getState().instancesByName[instance.name]).toBe(instance);
});
+ test("deduplicates database fetches and caches the result", async () => {
+ const dbName = "instances/i1/databases/db1";
+ const database = createProto(DatabaseSchema$, { name: dbName });
+ mocks.getDatabase.mockResolvedValueOnce(database);
+ const store = createAppStore();
+
+ const [first, second, third] = await Promise.all([
+ store.getState().fetchDatabase(dbName),
+ store.getState().fetchDatabase(dbName),
+ store.getState().fetchDatabase(dbName),
+ ]);
+
+ expect(first).toEqual(database);
+ expect(second).toEqual(database);
+ expect(third).toEqual(database);
+ expect(mocks.getDatabase).toHaveBeenCalledTimes(1);
+ expect(store.getState().databasesByName[dbName]).toEqual(database);
+ });
+
+ test("fetchDatabases populates databasesByName from the list response", async () => {
+ const dbA = createProto(DatabaseSchema$, {
+ name: "instances/i1/databases/db1",
+ });
+ const dbB = createProto(DatabaseSchema$, {
+ name: "instances/i1/databases/db2",
+ });
+ mocks.listDatabases.mockResolvedValue({
+ databases: [dbA, dbB],
+ nextPageToken: "next",
+ });
+ const store = createAppStore();
+
+ const result = await store.getState().fetchDatabases({
+ parent: "projects/a",
+ pageSize: 50,
+ filter: 'project == "projects/a"',
+ });
+
+ expect(result.databases).toEqual([dbA, dbB]);
+ expect(result.nextPageToken).toBe("next");
+ expect(store.getState().databasesByName[dbA.name]).toEqual(dbA);
+ expect(store.getState().databasesByName[dbB.name]).toEqual(dbB);
+ expect(mocks.listDatabases).toHaveBeenCalledTimes(1);
+ });
+
+ test("deduplicates db group fetches and caches the result", async () => {
+ const name = "projects/p1/databaseGroups/g1";
+ const group = createProto(DatabaseGroupSchema, { name });
+ mocks.getDatabaseGroup.mockResolvedValueOnce(group);
+ const store = createAppStore();
+
+ const [first, second] = await Promise.all([
+ store.getState().fetchDBGroup(name),
+ store.getState().fetchDBGroup(name),
+ ]);
+
+ expect(first).toEqual(group);
+ expect(second).toEqual(group);
+ expect(mocks.getDatabaseGroup).toHaveBeenCalledTimes(1);
+ });
+
+ test("deduplicates sheet fetches and caches the result", async () => {
+ const name = "projects/p1/sheets/s1";
+ const sheet = createProto(SheetSchema, {
+ name,
+ content: new Uint8Array(),
+ });
+ mocks.getSheet.mockResolvedValueOnce(sheet);
+ const store = createAppStore();
+
+ const [first, second] = await Promise.all([
+ store.getState().fetchSheet(name),
+ store.getState().fetchSheet(name),
+ ]);
+
+ expect(first).toEqual(sheet);
+ expect(second).toEqual(sheet);
+ expect(mocks.getSheet).toHaveBeenCalledTimes(1);
+ });
+
+ test("deduplicates instance role fetches per instance", async () => {
+ const instance = "instances/i1";
+ const roles = [
+ createProto(InstanceRoleSchema, { name: `${instance}/roles/admin` }),
+ ];
+ mocks.listInstanceRoles.mockResolvedValueOnce({ roles });
+ const store = createAppStore();
+
+ const [first, second] = await Promise.all([
+ store.getState().fetchInstanceRoles(instance),
+ store.getState().fetchInstanceRoles(instance),
+ ]);
+
+ expect(first).toEqual(roles);
+ expect(second).toEqual(roles);
+ expect(mocks.listInstanceRoles).toHaveBeenCalledTimes(1);
+ });
+
test("notify() routes to the React toast manager", async () => {
const { toastManager } = await import("@/react/lib/toast");
const addSpy = vi.spyOn(toastManager, "add");
diff --git a/frontend/src/react/stores/app/index.ts b/frontend/src/react/stores/app/index.ts
index d1dae61776..b17367c0ea 100644
--- a/frontend/src/react/stores/app/index.ts
+++ b/frontend/src/react/stores/app/index.ts
@@ -1,10 +1,14 @@
import { create } from "zustand";
import { createAuthSlice } from "./auth";
+import { createDatabaseSlice } from "./database";
+import { createDBGroupSlice } from "./dbGroup";
import { createIamSlice } from "./iam";
import { createInstanceSlice } from "./instance";
+import { createInstanceRoleSlice } from "./instanceRole";
import { createNotificationSlice } from "./notification";
import { createPreferencesSlice } from "./preferences";
import { createProjectSlice } from "./project";
+import { createSheetSlice } from "./sheet";
import { createWorkspaceSlice } from "./workspace";
export type { AppStoreState } from "./types";
@@ -23,6 +27,10 @@ export const createAppStore = () =>
...createIamSlice(...args),
...createProjectSlice(...args),
...createInstanceSlice(...args),
+ ...createDatabaseSlice(...args),
+ ...createDBGroupSlice(...args),
+ ...createSheetSlice(...args),
+ ...createInstanceRoleSlice(...args),
...createNotificationSlice(...args),
...createPreferencesSlice(...args),
}));
diff --git a/frontend/src/react/stores/app/instanceRole.ts b/frontend/src/react/stores/app/instanceRole.ts
new file mode 100644
index 0000000000..1d30a4ff62
--- /dev/null
+++ b/frontend/src/react/stores/app/instanceRole.ts
@@ -0,0 +1,52 @@
+import { create as createProto } from "@bufbuild/protobuf";
+import { instanceRoleServiceClientConnect } from "@/connect";
+import { ListInstanceRolesRequestSchema } from "@/types/proto-es/v1/instance_role_service_pb";
+import type { AppSliceCreator, InstanceRoleSlice } from "./types";
+
+export const createInstanceRoleSlice: AppSliceCreator<InstanceRoleSlice> = (
+ set,
+ get
+) => ({
+ rolesByInstance: {},
+ roleRequests: {},
+
+ fetchInstanceRoles: async (instance) => {
+ const existing = get().rolesByInstance[instance];
+ if (existing) return existing;
+ const pending = get().roleRequests[instance];
+ if (pending) return pending;
+
+ const request = instanceRoleServiceClientConnect
+ .listInstanceRoles(
+ createProto(ListInstanceRolesRequestSchema, { parent: instance })
+ )
+ .then((response) => {
+ const roles = response.roles;
+ set((state) => {
+ const { [instance]: _, ...roleRequests } = state.roleRequests;
+ return {
+ rolesByInstance: {
+ ...state.rolesByInstance,
+ [instance]: roles,
+ },
+ roleRequests,
+ };
+ });
+ return roles;
+ })
+ .catch(() => {
+ set((state) => {
+ const { [instance]: _, ...roleRequests } = state.roleRequests;
+ return { roleRequests };
+ });
+ return [];
+ });
+ set((state) => ({
+ roleRequests: {
+ ...state.roleRequests,
+ [instance]: request,
+ },
+ }));
+ return request;
+ },
+});
diff --git a/frontend/src/react/stores/app/sheet.ts b/frontend/src/react/stores/app/sheet.ts
new file mode 100644
index 0000000000..f55255dbf7
--- /dev/null
+++ b/frontend/src/react/stores/app/sheet.ts
@@ -0,0 +1,89 @@
+import { create as createProto } from "@bufbuild/protobuf";
+import { sheetServiceClientConnect } from "@/connect";
+import {
+ CreateSheetRequestSchema,
+ GetSheetRequestSchema,
+ type Sheet,
+} from "@/types/proto-es/v1/sheet_service_pb";
+import { extractSheetUID } from "@/utils/v1/sheet";
+import type { AppSliceCreator, SheetSlice } from "./types";
+
+function toError(error: unknown): Error {
+ if (error instanceof Error) return error;
+ return new Error(String(error));
+}
+
+function isValidSheetName(name: string): boolean {
+ if (typeof name !== "string") return false;
+ const uid = extractSheetUID(name);
+ return Boolean(uid) && uid !== "-1" && !uid.startsWith("-");
+}
+
+export const createSheetSlice: AppSliceCreator<SheetSlice> = (set, get) => ({
+ sheetsByName: {},
+ sheetRequests: {},
+ sheetErrorsByName: {},
+
+ fetchSheet: async (name, raw = false) => {
+ if (!isValidSheetName(name)) return undefined;
+ if (!raw) {
+ const existing = get().sheetsByName[name];
+ if (existing) return existing;
+ }
+ const pending = get().sheetRequests[name];
+ if (pending) return pending;
+
+ const request = sheetServiceClientConnect
+ .getSheet(createProto(GetSheetRequestSchema, { name, raw }))
+ .then((sheet: Sheet) => {
+ set((state) => {
+ const { [name]: _, ...sheetRequests } = state.sheetRequests;
+ return {
+ sheetsByName: {
+ ...state.sheetsByName,
+ [sheet.name]: sheet,
+ },
+ sheetErrorsByName: {
+ ...state.sheetErrorsByName,
+ [name]: undefined,
+ },
+ sheetRequests,
+ };
+ });
+ return sheet;
+ })
+ .catch((error) => {
+ set((state) => {
+ const { [name]: _, ...sheetRequests } = state.sheetRequests;
+ return {
+ sheetErrorsByName: {
+ ...state.sheetErrorsByName,
+ [name]: toError(error),
+ },
+ sheetRequests,
+ };
+ });
+ return undefined;
+ });
+ set((state) => ({
+ sheetRequests: {
+ ...state.sheetRequests,
+ [name]: request,
+ },
+ }));
+ return request;
+ },
+
+ createSheet: async (parent, sheet) => {
+ const response = await sheetServiceClientConnect.createSheet(
+ createProto(CreateSheetRequestSchema, { parent, sheet })
+ );
+ set((state) => ({
+ sheetsByName: {
+ ...state.sheetsByName,
+ [response.name]: response,
+ },
+ }));
+ return response;
+ },
+});
diff --git a/frontend/src/react/stores/app/types.ts b/frontend/src/react/stores/app/types.ts
index 803a63067a..4c91916d78 100644
--- a/frontend/src/react/stores/app/types.ts
+++ b/frontend/src/react/stores/app/types.ts
@@ -3,7 +3,10 @@ import type { AppFeatures } from "@/types/appProfile";
import type { Permission } from "@/types/iam/permission";
import type { NotificationCreate } from "@/types/notification";
import type { ActuatorInfo } from "@/types/proto-es/v1/actuator_service_pb";
+import type { DatabaseGroup } from "@/types/proto-es/v1/database_group_service_pb";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
import type { IamPolicy } from "@/types/proto-es/v1/iam_policy_pb";
+import type { InstanceRole } from "@/types/proto-es/v1/instance_role_service_pb";
import type {
Instance,
InstanceResource,
@@ -11,6 +14,7 @@ import type {
import type { Project } from "@/types/proto-es/v1/project_service_pb";
import type { Role } from "@/types/proto-es/v1/role_service_pb";
import type { WorkspaceProfileSetting } from "@/types/proto-es/v1/setting_service_pb";
+import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";
import type {
PlanFeature,
PlanType,
@@ -124,6 +128,48 @@ export type InstanceSlice = {
fetchInstance: (name: string) => Promise<Instance | undefined>;
};
+export type DatabaseListParams = {
+ parent: string;
+ pageSize: number;
+ pageToken?: string;
+ filter?: string;
+ orderBy?: string;
+};
+
+export type DatabaseSlice = {
+ databasesByName: Record<string, Database>;
+ databaseRequests: Record<string, Promise<Database | undefined>>;
+ databaseErrorsByName: Record<string, Error | undefined>;
+ fetchDatabase: (name: string) => Promise<Database | undefined>;
+ batchFetchDatabases: (names: string[]) => Promise<Database[]>;
+ fetchDatabases: (params: DatabaseListParams) => Promise<{
+ databases: Database[];
+ nextPageToken: string;
+ }>;
+};
+
+export type DBGroupSlice = {
+ dbGroupsByName: Record<string, DatabaseGroup>;
+ dbGroupRequests: Record<string, Promise<DatabaseGroup | undefined>>;
+ dbGroupErrorsByName: Record<string, Error | undefined>;
+ fetchDBGroup: (name: string) => Promise<DatabaseGroup | undefined>;
+ listDBGroupsForProject: (project: string) => Promise<DatabaseGroup[]>;
+};
+
+export type SheetSlice = {
+ sheetsByName: Record<string, Sheet>;
+ sheetRequests: Record<string, Promise<Sheet | undefined>>;
+ sheetErrorsByName: Record<string, Error | undefined>;
+ fetchSheet: (name: string, raw?: boolean) => Promise<Sheet | undefined>;
+ createSheet: (parent: string, sheet: Sheet) => Promise<Sheet>;
+};
+
+export type InstanceRoleSlice = {
+ rolesByInstance: Record<string, InstanceRole[]>;
+ roleRequests: Record<string, Promise<InstanceRole[]>>;
+ fetchInstanceRoles: (instance: string) => Promise<InstanceRole[]>;
+};
+
export type NotificationSlice = {
notify: (notification: NotificationCreate) => void;
};
@@ -140,6 +186,10 @@ export type AppStoreState = AuthSlice &
IamSlice &
ProjectSlice &
InstanceSlice &
+ DatabaseSlice &
+ DBGroupSlice &
+ SheetSlice &
+ InstanceRoleSlice &
NotificationSlice &
PreferencesSlice;
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-smoke.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-smoke.spec.ts
new file mode 100644
index 0000000000..49fa8c0415
--- /dev/null
+++ b/frontend/tests/e2e/plan-detail/plan-detail-smoke.spec.ts
@@ -0,0 +1,34 @@
+import { test, expect } from "@playwright/test";
+import { loadTestEnv } from "../framework/env";
+import { PlanDetailPage } from "./plan-detail.page";
+
+test.setTimeout(60_000);
+
+test("plan-detail page loads with title, changes section, and a spec tab", async ({
+ browser,
+}) => {
+ const env = loadTestEnv();
+ const projectId = env.project.split("/").pop()!;
+ await env.api.login(env.adminEmail, env.adminPassword);
+
+ const planTitle = `smoke-${Date.now()}`;
+ const sheetName = await env.api.createSheet(env.project, "SELECT 1;");
+ const specId = `spec-${Date.now()}`;
+ const plan = await env.api.createPlan(env.project, planTitle, [
+ { id: specId, targets: [env.database], sheet: sheetName },
+ ]);
+ const planId = plan.name.split("/").pop()!;
+
+ const context = await browser.newContext({ storageState: ".auth/state.json" });
+ const page = await context.newPage();
+ const planPage = new PlanDetailPage(page, env.baseURL);
+
+ await planPage.goto(projectId, planId);
+ await planPage.dismissModals();
+
+ await expect(planPage.headerTitle).toHaveValue(planTitle);
+ await expect(planPage.changesSection).toBeVisible();
+ await expect(planPage.specTab(1)).toBeVisible();
+
+ await context.close();
+});
diff --git a/frontend/tests/e2e/plan-detail/plan-detail.page.ts b/frontend/tests/e2e/plan-detail/plan-detail.page.ts
index c46e0884d5..8b3ddda011 100644
--- a/frontend/tests/e2e/plan-detail/plan-detail.page.ts
+++ b/frontend/tests/e2e/plan-detail/plan-detail.page.ts
@@ -11,6 +11,9 @@ export class PlanDetailPage {
readonly bypassWarningsCheckbox: Locator;
readonly confirmRolloutButton: Locator;
readonly retryButton: Locator;
+ // The plan/issue title input rendered in PlanDetailHeader. It is an
+ // <input> bound to the plan or issue title — first textbox on the page.
+ readonly headerTitle: Locator;
constructor(page: Page, baseURL: string) {
this.page = page;
@@ -23,6 +26,7 @@ export class PlanDetailPage {
this.bypassWarningsCheckbox = page.getByRole("checkbox", { name: "Bypass warnings" });
this.confirmRolloutButton = page.getByRole("dialog").getByRole("button", { name: "Confirm" });
this.retryButton = page.getByRole("button", { name: "Retry" });
+ this.headerTitle = page.getByRole("textbox").first();
}
async goto(projectId: string, planId: string) {
diff --git a/frontend/tsconfig.app.json b/frontend/tsconfig.app.json
index f3bd8fd72a..497b30e378 100644
--- a/frontend/tsconfig.app.json
+++ b/frontend/tsconfig.app.json
@@ -31,7 +31,8 @@
"src/react/components/SchemaEditorLite/Panels/IndexesEditor/index.ts",
"src/react/components/SchemaEditorLite/Panels/PartitionsEditor/index.ts",
"src/react/components/SchemaEditorLite/Panels/TableList/index.ts",
- "src/react/components/sql-editor/ResultView/index.ts"
+ "src/react/components/sql-editor/ResultView/index.ts",
+ "src/react/pages/project/plan-detail/index.ts"
],
"compilerOptions": {
"composite": true,
diff --git a/frontend/tsconfig.vitest.json b/frontend/tsconfig.vitest.json
index fe0cd8e922..a515400df9 100644
--- a/frontend/tsconfig.vitest.json
+++ b/frontend/tsconfig.vitest.json
@@ -28,7 +28,8 @@
"src/react/components/SchemaEditorLite/Panels/IndexesEditor/index.ts",
"src/react/components/SchemaEditorLite/Panels/PartitionsEditor/index.ts",
"src/react/components/SchemaEditorLite/Panels/TableList/index.ts",
- "src/react/components/sql-editor/ResultView/index.ts"
+ "src/react/components/sql-editor/ResultView/index.ts",
+ "src/react/pages/project/plan-detail/index.ts"
],
"compilerOptions": {
"composite": true,