Skip to content

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

refactor(frontend): remove vue-router, Pinia & vue-i18n — React-only routing/shell/auth/state/i18n (#20500)

boojackf75589919e5f
diff --git a/.gitignore b/.gitignore
index 94af06fa1e..d077ad7c54 100644
--- a/.gitignore
+++ b/.gitignore
@@ -28,6 +28,7 @@ bytebase-build
# Claude Code user-specific configuration
.claude/settings.local.json
+.claude/scheduled_tasks.lock
# Git worktrees
.worktrees/
diff --git a/docs/superpowers/plans/2026-06-03-vue-to-react-routing-shell-auth-migration.md b/docs/superpowers/plans/2026-06-03-vue-to-react-routing-shell-auth-migration.md
new file mode 100644
index 0000000000..6018499a07
--- /dev/null
+++ b/docs/superpowers/plans/2026-06-03-vue-to-react-routing-shell-auth-migration.md
@@ -0,0 +1,190 @@
+# Vue → React routing + shell + auth migration — 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:** Replace the Vue host (vue-router + `App.vue` + `AuthContext.vue` + 3 layouts + 5 mount bridges + `ReactPageMount` + glob registry + Pinia auth store + guard + interceptor) with a single React root on react-router-dom v7, app store as the single session source of truth — fully deleting Vue.
+
+**Architecture:** One `ReactDOM.createRoot` → `<RouterProvider router={createBrowserRouter(routes)}>` → `<RootLayout>` (providers + overlays) → `<AuthGate>` → `<Outlet/>`. Routes translate ~1:1 from vue-router; the guard is a verbatim port of `beforeEach` as a root-route `loader`; pages (already React) load via `lazy`.
+
+**Tech Stack:** react-router-dom v7, the existing Zustand app store, react-i18next, esbuild react-tsx-transform.
+
+**Reference:** `docs/superpowers/specs/2026-06-03-vue-to-react-routing-shell-auth-migration-design.md`. All commands run from repo root unless noted; frontend gates: `pnpm --dir frontend type-check`, `pnpm --dir frontend check`, `pnpm --dir frontend test`.
+
+**Working branch:** `react-delete-vue-routing-shell-auth` (already created; spec committed).
+
+**Verification gate after every task:** `pnpm --dir frontend type-check` exits 0 (ignore IDE `Cannot find module '@/...'` noise — only real `error TS` count). Run `pnpm --dir frontend test` after any task touching component/store/guard logic. Commit after each task.
+
+---
+
+## Phase 0 — Inventory & guardrails (read-only)
+
+### Task 0.1: Capture the route table + guard as the porting source of truth
+**Files (read):** `src/router/index.ts` (guard, 293 lines), `src/router/auth.ts`, `src/router/setup.ts`, `src/router/sqlEditor.ts`, `src/router/dashboard/{index,workspace,workspaceRoutes,workspaceSetting,projectV1,projectV1RouteHelpers,instance,environmentV1}.ts`.
+
+- [ ] **Step 1:** Produce a flat table `routes.inventory.md` (scratch, not committed) listing every route: path, route-name constant, layout, the `page:"X"` string (or nested children), and any `meta`/`props`. Source: `grep -rnE "path:|name:|component:|page:|props:" src/router`.
+- [ ] **Step 2:** Produce `bridges.inventory.md` (scratch): the 79 `useVueState` files (`grep -rln useVueState src/react --include=*.tsx --include=*.ts | grep -v .test.`), each tagged by what its getter reads (vue-router `useRoute`/`router`/`currentRoute`, Pinia auth, app-shell Pinia bridge, or other). This drives Phase 5.
+
+No code change. No commit (scratch artifacts only).
+
+---
+
+## Phase 1 — React Router + route table (not yet wired to root)
+
+### Task 1.1: Add react-router-dom
+**Files:** `frontend/package.json`
+
+- [ ] **Step 1:** `pnpm --dir frontend add react-router-dom@^7`
+- [ ] **Step 2:** Verify it resolves: `pnpm --dir frontend type-check` → exit 0.
+- [ ] **Step 3:** Commit: `chore(frontend): add react-router-dom v7`
+
+### Task 1.2: Route-name handles module
+**Files:** Create `src/react/router/handles.ts`
+
+- [ ] **Step 1:** Re-export every route-name constant currently in `src/router/**` (92 constants: `*_MODULE`, `*_ROUTE_*`) from `@/react/router/handles` so React routes can attach `handle: { name }` without importing the Vue router files. For each, `export { AUTH_SIGNIN_MODULE } from "@/router/auth"` etc. (These constant modules are plain `.ts` with no Vue imports — verify with `grep -l "from \"vue\"" src/router/auth.ts` → empty.)
+- [ ] **Step 2:** `type-check` → 0. Commit: `feat(frontend): re-export route-name handles for react router`
+
+### Task 1.3: Translate the route table
+**Files:** Create `src/react/router/routes.tsx` (+ split per-area files `routes/auth.tsx`, `routes/dashboard.tsx`, `routes/sqlEditor.tsx`, `routes/setup.tsx` if `routes.tsx` exceeds ~300 lines).
+
+- [ ] **Step 1:** For each vue-router route, emit a react-router `RouteObject`:
+ - `path` unchanged (vue `:param` → react `:param` is identical syntax).
+ - layout route → `{ path, element: <SplashLayout/> | <BodyLayout/> | <DashboardLayout/>, children: [...] }` (React layouts built in Phase 3; for now import placeholders that render `<Outlet/>`).
+ - leaf route `component: ReactPageMount, props:{page:"SigninPage"}` → `{ path, handle: { name: AUTH_SIGNIN_MODULE }, lazy: async () => ({ Component: (await import("@/react/pages/auth/SigninPage")).SigninPage }) }`. Map each of the 73 `page:"X"` strings to its `@/react/pages/.../X` import (the `import.meta.glob` patterns in `src/react/mount.ts` give the exact directories: `pages/settings`, `pages/project`, `pages/workspace`, `pages/auth`, `components/auth`, `components/sql-editor`, `components/*`).
+ - named view `<router-view name="body">` → the child routes render into the layout's `<Outlet/>` (single outlet; drop the name).
+- [ ] **Step 2:** Export `export const routes: RouteObject[]`. Do NOT call `createBrowserRouter` yet (wired in Phase 4).
+- [ ] **Step 3:** `type-check` → 0 (placeholders compile). Commit: `feat(frontend): react-router route table translated from vue-router`
+
+---
+
+## Phase 2 — Auth slice + guard + interceptor
+
+### Task 2.1: Port the Pinia auth store onto the app-store AuthSlice
+**Files:** Modify `src/react/stores/app/auth.ts`, `src/react/stores/app/types.ts`. Source to port verbatim: `src/store/modules/v1/auth.ts` (281 lines).
+
+- [ ] **Step 1:** Extend `AuthSlice` in `types.ts` with: `unauthenticatedOccurred: boolean`, `requireResetPassword: boolean` (getter via method `getRequireResetPassword()` OR derived), `authSessionKey: string`, `isSelfEmailUpdate: boolean`, `isLoggedIn: () => boolean`, `login`, `signup`, `logout`, `fetchCurrentUser`, `setRequireResetPassword`, `sendEmailLoginCode`, `updateCurrentUserNameForEmailChange`, `setUnauthenticatedOccurred: (v: boolean) => void`. Copy each method's exact signature from the Pinia store's return block.
+- [ ] **Step 2:** Port each method body **verbatim** from `src/store/modules/v1/auth.ts`, with only these swaps: Vue `ref`/`computed` → slice state + `get()`/`set()`; `router.push(x)` / `router.replace(x)` → `appRouter.navigate(x)` (the react-router instance, imported from `@/react/router/instance` created in Phase 4 — until then, import lazily inside the method: `const { appRouter } = await import("@/react/router/instance")`). Keep the imported route-name constants and redirect targets identical.
+- [ ] **Step 3:** `type-check` → 0; `pnpm --dir frontend test src/react/stores/app/index.test.ts` → passes (store constructs).
+- [ ] **Step 4:** Commit: `feat(frontend): port the auth lifecycle onto the app-store AuthSlice`
+
+### Task 2.2: Guard loader (verbatim port of beforeEach)
+**Files:** Create `src/react/router/guard.ts`. Source: `src/router/index.ts:84-278` (the `beforeEach`).
+
+- [ ] **Step 1:** Write `export async function rootGuard({ request, matches }: LoaderFunctionArgs)`. Reproduce the 13 checks **in the same order** (see spec §2). Read the target route name from `matches.at(-1)?.handle?.name`. Read session from `useAppStore.getState()` (`isLoggedIn()`, `unauthenticatedOccurred`, `requireResetPassword`). Where the old guard called `next({ name, query, replace })`, `throw redirect(pathFor(name, query))`; where it called `next()`, `return null`; where `next(false)`, `throw redirect(currentPath)` (no-op equivalent). Port the relay_state/redirect param logic and `stripSigninQueryParams`/`SIGNIN_QUERY_PARAMS` verbatim. Port the auth-route store resets (`resetDatabases/resetInstances/resetProjects` + the AI conversation reset).
+- [ ] **Step 2:** Unit test `src/react/router/guard.test.ts` covering each branch: not-logged-in→signin (with `redirect` query); logged-in-on-auth-route→`/`; 2FA enforce; password-reset enforce; 403/404 passthrough; OAuth/OIDC callback passthrough; OAuth2 consent passthrough. Mock `useAppStore.getState()` session + a fake `matches`.
+- [ ] **Step 3:** `pnpm --dir frontend test src/react/router/guard.test.ts` → all pass.
+- [ ] **Step 4:** Commit: `feat(frontend): port the router guard as a react-router root loader`
+
+### Task 2.3: Repoint the auth interceptor to the app store
+**Files:** Modify `src/connect/middlewares/authInterceptorMiddleware.ts`.
+
+- [ ] **Step 1:** Replace `useAuthStore().unauthenticatedOccurred = true` with `useAppStore.getState().setUnauthenticatedOccurred(true)`, and `authStore.isLoggedIn` reads with `useAppStore.getState().isLoggedIn()`. Keep the silent/notification logic identical.
+- [ ] **Step 2:** `type-check` → 0; `pnpm --dir frontend test` → green. Commit: `refactor(frontend): auth interceptor reads session from the app store`
+
+### Task 2.4: AuthGate (replaces AuthContext.vue)
+**Files:** Create `src/react/app/AuthGate.tsx`. Source behavior: `src/AuthContext.vue` (139 lines).
+
+- [ ] **Step 1:** A component that: subscribes to `isLoggedIn`/`unauthenticatedOccurred` via `useAppStore`; on mount, if not logged in and not on an auth route, `void useAppStore.getState().fetchCurrentUser()`; reproduces `AuthContext.vue`'s render gating + the `currentUserName` watch + `isSelfEmailUpdate` reset. Renders `{children}` (the `<Outlet/>`).
+- [ ] **Step 2:** Test `AuthGate.test.tsx`: renders children when logged in; triggers `fetchCurrentUser` when not loaded.
+- [ ] **Step 3:** `type-check` + test → pass. Commit: `feat(frontend): AuthGate replaces AuthContext.vue`
+
+---
+
+## Phase 3 — React layouts + RootLayout
+
+### Task 3.1: React layout route components
+**Files:** Create `src/react/app/layouts/{SplashLayout,BodyLayout,DashboardLayout}.tsx`. Source: `src/layouts/*.vue`.
+
+- [ ] **Step 1:** Each renders its chrome + `<Outlet/>` for children. `DashboardLayout` mounts the React sidebar (today `ReactSidebarMount.vue` → use the existing `src/react/mountSidebar.ts` React tree directly) + `<Outlet/>` for the body. `BodyLayout` (152 lines) and `SplashLayout` port their wrapper markup. Port any `useEnsureWorkspaceCommonData()` call that lived in the Vue layout into `DashboardLayout`.
+- [ ] **Step 2:** Wire the real layouts into `routes.tsx` (replace Phase-1 placeholders).
+- [ ] **Step 3:** `type-check` → 0. Commit: `feat(frontend): react layout routes (Splash/Body/Dashboard)`
+
+### Task 3.2: RootLayout
+**Files:** Create `src/react/app/RootLayout.tsx`.
+
+- [ ] **Step 1:** Renders the global overlays from today's `ReactApp` (`Watermark`, `Toaster`, `AgentWindow`, `SessionExpiredSurfaceGate`) + `<AuthGate><Outlet/></AuthGate>`. This is the root route's `element`, with `loader: rootGuard`.
+- [ ] **Step 2:** `type-check` → 0. Commit: `feat(frontend): RootLayout (providers + overlays + guard + AuthGate)`
+
+---
+
+## Phase 4 — Flip main.ts to the single React root
+
+### Task 4.1: Router instance + RouterProvider entry
+**Files:** Create `src/react/router/instance.ts` (exports `appRouter = createBrowserRouter([{ element: <RootLayout/>, loader: rootGuard, children: routes }])`) and `src/react/app/AppRoot.tsx` (`<RouterProvider router={appRouter}/>`).
+
+- [ ] **Step 1:** Create both. Resolve the Phase-2 lazy `appRouter` import in the auth slice to the static `@/react/router/instance`.
+- [ ] **Step 2:** `type-check` → 0. Commit: `feat(frontend): react-router browser router instance + AppRoot`
+
+### Task 4.2: Rewrite main.ts
+**Files:** Modify `src/main.ts` (76 lines).
+
+- [ ] **Step 1:** Remove `createApp(App)`, `app.use(pinia/router/highlight/i18n)`, `app.mount("#app")`, and the separate `mountReactApp("#react-app")` block. Keep the side-effect imports (`./init`, `regenerator-runtime`, css, `./react/lib/toast`, `migrateStorageKeys`). Replace the bootstrap with: `const currentUser = await useAppStore.getState().fetchCurrentUser();` then the same `fetchServerInfo`/`fetchSubscription`/`fetchWorkspaceList` init (now via app store), then `ReactDOM.createRoot(document.getElementById("app")!).render(<AppRoot/>)`. Keep `highlight`/`i18n`/`dayjs` plugin init where still needed (highlight is non-Vue; i18n → react-i18next is already initialized in `@/react/i18n`).
+- [ ] **Step 2:** `index.html`: ensure a single `#app` root div (remove `#react-app` if present).
+- [ ] **Step 3:** `pnpm --dir frontend build` (or `pnpm --dir frontend dev` smoke) compiles; `type-check` → 0; `test` → green.
+- [ ] **Step 4:** Commit: `feat(frontend): boot a single React root via RouterProvider`
+
+> ⚠️ After Task 4.2 the app runs on React Router. **Manual QA checkpoint** (spec verification): login, logout, deep-link to a protected route (→signin→back), 404, OAuth callback. Fix regressions before proceeding.
+
+---
+
+## Phase 5 — Sweep the 79 useVueState bridges
+
+### Task 5.1..5.N: per-area bridge sweeps
+**Files:** the 79 `useVueState` files (Phase 0.1 inventory). Batches: `pages/project` (47), `pages/settings` (16), `pages/auth` (4) + `hooks`/`components` (8).
+
+- [ ] For each file, apply the transformation rule by the getter's source:
+ - vue-router (`useRoute()`, `router`, `currentRoute`) → `useParams()` / `useLocation()` / `useNavigate()`.
+ - Pinia auth read → `useAppStore((s) => s.<field>)` / `s.isLoggedIn()`.
+ - app-shell Pinia-bridge read (`useAppFeature`, the `DashboardFrameShell` legacy bootstrap, `syncSubscriptionToPinia`) → direct app-store selector; delete the now-orphan bridge.
+ - Replace `useVueState(() => X)` with the equivalent React hook/selector; remove the `useVueState` import.
+- [ ] After each batch: `type-check` → 0; `test` → green; commit `refactor(frontend): drop useVueState bridges in <area> (<n>/79)`.
+
+### Task 5.last: delete the bridge infra
+**Files:** Delete `src/react/hooks/useVueState.ts`; remove `effectScope` usage in `src/react/components/ProjectSidebar.tsx`; delete `src/react/ReactPageMount.vue`, `ReactRouteShellBridge.vue`, `ReactSidebarMount.vue`, `ReactProjectSidebarMount.vue`, `LandingPageMount.vue`, `src/react/mount.ts`, `src/react/app/mount.ts` glob registry.
+
+- [ ] `grep -rn useVueState src/react --include=*.tsx --include=*.ts | grep -v .test.` → empty. `type-check` + `test` → green. Commit.
+
+---
+
+## Phase 6 — Replace pev2 with a React plan visualizer
+
+### Task 6.1: React Postgres plan view
+**Files:** Rewrite `src/react/explain-visualizer/PostgresPlanView.tsx` (currently `createApp(pev2)`); siblings `MSSQLPlanView.tsx` + `SpannerQueryPlan.tsx` are already React for parity.
+
+- [ ] **Step 1:** Replace the `createApp(pev2)` Vue mount with a React plan-tree component rendering the same parsed-plan data (`@/utils/pev2` `readExplainFromToken` output): node tree with per-node cost/rows/time, expand/collapse, and the cost heat coloring pev2 provided. Reuse `MSSQLPlanView`/`SpannerQueryPlan` patterns for the tree UI.
+- [ ] **Step 2:** Remove `import "pev2/dist/pev2.css"` and the pev2 Font-Awesome shim in `main.tsx`; drop the `pev2` dep from `package.json`.
+- [ ] **Step 3:** Test `PostgresPlanView.test.tsx` (render a sample plan, assert node rows). `type-check` + `test` → green. **Screenshot-compare** against the old pev2 output.
+- [ ] **Step 4:** Commit: `feat(frontend): react postgres query-plan visualizer (replaces pev2)`
+
+---
+
+## Phase 7 — Delete Vue + dependency teardown
+
+### Task 7.1: Delete the Vue shell + vue-router + Pinia auth
+**Files:** Delete `src/App.vue`, `src/AuthContext.vue`, `src/layouts/*.vue`, `src/router/index.ts` (guard — superseded), `src/store/modules/v1/auth.ts` + its barrel export, `src/react/app/ReactApp.tsx` (folded into RootLayout). Keep the route-name constant modules under `src/router/**` (re-exported by `handles.ts`) OR relocate them into `src/react/router/` and delete `src/router/**`.
+
+- [ ] `grep -rln "useAuthStore\|from \"vue-router\"\|\.vue\"" src --include=*.ts --include=*.tsx` → only the constant modules / none. `type-check` + `test` → green. Commit.
+
+### Task 7.2: vue-i18n → react-i18next
+**Files:** the 5 `vue-i18n` importers (`grep -rln vue-i18n src`).
+
+- [ ] Replace each with `react-i18next` `useTranslation()` / the `@/react/i18n` instance. `type-check` + `test` → green. Commit.
+
+### Task 7.3: Remove Vue dependencies + build config
+**Files:** `frontend/package.json`, `frontend/vite.config.ts`, `frontend/tsconfig*.json`, `frontend/scripts/`.
+
+- [ ] **Step 1:** `pnpm --dir frontend remove vue vue-router pinia vue-i18n @vueuse/core @vitejs/plugin-vue @vue/compiler-sfc @vue/test-utils @vue/tsconfig vue-tsc`.
+- [ ] **Step 2:** Remove the Vue plugin from `vite.config.ts`; drop `vue-tsc` from the type-check script (esbuild react-tsx-transform + `tsconfig.react.json` remain).
+- [ ] **Step 3:** Add `frontend/scripts/check-react-no-pinia.mjs` (fails CI if `src/react/**` imports `@/store` Pinia hooks) and wire into `pnpm check`.
+- [ ] **Step 4:** `pnpm --dir frontend i` clean; `type-check` + `check` + `test` + `build` → all green. Commit: `chore(frontend): remove Vue, vue-router, pinia, vue-i18n; add no-pinia guard`
+
+### Task 7.4: Final verification + PR
+- [ ] `find src -name '*.vue'` → empty. `grep -rn "from \"vue\"" src --include=*.ts --include=*.tsx` → empty.
+- [ ] Full manual QA pass (spec §Verification): login, logout, session-expiry (401→surface), OAuth/OIDC callback, 2FA setup, password reset, deep-link redirect, workspace switch, SQL-editor entry, Postgres EXPLAIN viz.
+- [ ] Open the PR with the spec + this plan linked.
+
+---
+
+## Self-review notes
+- **Spec coverage:** §1 architecture → Phases 3,4; §2 auth/guard → Phase 2; §3 routes/bridges/pev2 → Phases 1,5,6; §4 build order → phase numbering matches the spec's 7 steps; verification → per-task gates + the two manual-QA checkpoints (after Phase 4 and Task 7.4).
+- **Risk ordering:** the app runs end-to-end after Phase 4 (root flip), so Phases 5–7 are incremental cleanups each behind green gates.
+- **Verbatim ports** (auth slice, guard) cite exact source files + the only allowed transformations (no behavior change) — precise, not placeholder.
diff --git a/docs/superpowers/specs/2026-06-03-vue-to-react-routing-shell-auth-migration-design.md b/docs/superpowers/specs/2026-06-03-vue-to-react-routing-shell-auth-migration-design.md
new file mode 100644
index 0000000000..9a01a84aa3
--- /dev/null
+++ b/docs/superpowers/specs/2026-06-03-vue-to-react-routing-shell-auth-migration-design.md
@@ -0,0 +1,141 @@
+# Vue → React: routing + app-shell + auth migration
+
+**Goal:** Replace the Vue *host* (vue-router, `App.vue`, `AuthContext.vue`, the 3
+layouts, the 5 React-mount bridge `.vue` files, `ReactPageMount` + the glob page
+registry, the Pinia auth store, the router guard, the auth interceptor) with a
+single React root running **react-router-dom v7**, with the app store as the
+single source of truth for session state. This is the critical-path track to
+**fully deleting Vue** from `frontend/`.
+
+**Delivery:** one **big-bang PR** (decision). The pages are already React, so the
+bulk is mechanical route-table translation + deleting Vue files. The PR is built
+in an internal order (below) so the tree stays buildable/reviewable per commit.
+
+**Hard constraints:**
+- **No breaking changes.** Purely swapping the host; nothing user-visible changes.
+- **The guard is a faithful, line-by-line port** of the existing `router/index.ts`
+ `beforeEach` — same checks, same order, same redirects.
+
+## Decisions (locked)
+1. Strategy: **big-bang single PR** (no two-router coexistence).
+2. Router: **react-router-dom v7** (`createBrowserRouter`, nested route objects,
+ `lazy`, loaders) — closest 1:1 translation of the nested vue-router config.
+3. Guard: **faithful port** of `beforeEach` as a root-route `loader`.
+4. pev2: **replace the third-party Vue query-plan visualizer with React** in this
+ PR, so the `vue` core dep is removed entirely (clean, complete deletion).
+
+## §1 Target architecture (end state)
+One React root owns everything. `main.ts` drops `createApp(App)` and the separate
+`#react-app` overlay mount, and mounts a single tree:
+
+```
+ReactDOM.createRoot(#app).render(
+ <RouterProvider router={createBrowserRouter(routes)} />
+)
+ └─ <RootLayout> // replaces App.vue: providers + global overlays
+ (Toaster, AgentWindow, Watermark, SessionExpiredSurfaceGate — today's ReactApp)
+ └─ <AuthGate> // replaces AuthContext.vue: gates render on app-store session
+ └─ <Outlet/> // matched layout + page
+```
+
+- **Routes:** `createBrowserRouter` with a nested route-object array translated
+ ~1:1 from the vue-router config (~102 routes, 73 page names). The 3 Vue layouts
+ (`Splash`/`Body`/`Dashboard`) become React **layout routes** with `<Outlet/>`;
+ `DashboardLayout`'s named `<router-view name="body">` → a nested `<Outlet/>`.
+ Each leaf swaps `component: ReactPageMount, props:{page:"X"}` for
+ `lazy: () => import("@/react/pages/.../X")` — replacing the island mount + the
+ `import.meta.glob` registry. One React root; pages render in-place.
+- **Navigation:** `useNavigate` / `useParams` / `useLocation` / `<Navigate>`
+ replace `router.push` / `useRoute`.
+- **Route names:** existing name constants (`AUTH_SIGNIN_MODULE`, …) are kept and
+ attached as `handle: { name }` so the guard, `useRecentVisit`, and module
+ back-path tracking keep working unchanged.
+
+## §2 Auth / session model + guard
+**Session source of truth → app-store `AuthSlice`.** Port the Pinia auth store
+1:1 onto the slice:
+- State: `currentUser`, `unauthenticatedOccurred`, `requireResetPassword`,
+ `authSessionKey`, `isSelfEmailUpdate`. Getter: `isLoggedIn`.
+- Methods: `login`, `signup`, `logout`, `fetchCurrentUser`,
+ `setRequireResetPassword`, `sendEmailLoginCode`,
+ `updateCurrentUserNameForEmailChange` — bodies copied verbatim; only the
+ navigation calls swapped (`router.push` → the React Router instance's
+ `router.navigate(...)`; data routers expose `.navigate()`).
+
+**Auth interceptor:** `authInterceptorMiddleware.ts` flips `unauthenticatedOccurred`
+on a 401 — repointed from `useAuthStore()` to `useAppStore.getState()`.
+`SessionExpiredSurface` already reacts to that flag (now reads the app store).
+
+**`<AuthGate>` (replaces `AuthContext.vue`):** reads `isLoggedIn` /
+`unauthenticatedOccurred` from the app store, calls `fetchCurrentUser()` on mount
+when not loaded, and gates render exactly like `AuthContext.vue` (watch on
+`currentUserName`, `isSelfEmailUpdate` handling).
+
+**The guard (replaces `beforeEach`):** a single **root-route `loader`** that runs
+on every navigation and reproduces the existing guard step-for-step:
+1. same-route loop guard → 2. 403/404 direct access → 3. OAuth/OIDC callbacks
+direct → 4. OAuth2 consent → 5. allow 2FA-setup / password-reset / profile-setup
+when logged in → 6. module back-path tracking → 7. logged-in-on-auth-route
+redirect (relay_state/redirect) → 8. auth-route store resets
+(resetDatabases/instances/projects) → 9. not-logged-in → signin redirect (with
+`redirect` query) → 10. enforce 2FA → 11. enforce password reset → 12.
+allowed-route-patterns → 13. 404 fallback. It reads the matched route's
+`handle.name` (mirroring vue route names), reads session from the app store, and
+`throw redirect()` where the old guard called `next({name})`.
+
+## §3 Route table, the 79 bridges, reverse islands
+- **Route table:** mechanical translation of the ~102 routes; layouts → layout
+ routes; leaf routes → `lazy` imports; name constants → `handle.name`. The
+ SQL-editor "layout as a page" island collapses into a normal layout route.
+- **The 79 `useVueState` bridges:** each reads a Vue-reactive source that is being
+ deleted, so each is rewritten — vue-router reads (`useRoute`/`router`/
+ `currentRoute`) → `useParams`/`useLocation`/`useNavigate`; Pinia-auth reads →
+ app-store auth selectors; app-shell Pinia-bridge reads (the `DashboardFrameShell`
+ legacy bootstrap + `syncSubscriptionToPinia`) → those bridges are *deleted* once
+ the Vue shell that needed them is gone, so they become direct app-store
+ selectors. Then `useVueState.ts`, the Vue reactivity primitives (`effectScope`
+ in `ProjectSidebar`), and the page-mount/glob registry are removed. This ~79-file
+ sweep is the single largest mechanical part and the main reason the PR is big.
+- **vue-i18n (5 importers) → react-i18next** (React already uses it); the
+ `ReactPageMount` locale-sync watcher goes away.
+- **pev2 reverse island:** re-implement the Postgres query-plan visualizer
+ (`PostgresPlanView.tsx`, currently `createApp(pev2)`) in React so `vue` is fully
+ removed. The one piece of genuinely net-new UI; isolated in its own commit.
+
+## §4 Internal build order (within the one PR)
+1. Add `react-router-dom`; author the nested route table + `handle.name` + `lazy`
+ imports (not wired to the root yet).
+2. Port the auth slice (verbatim bodies) + the guard loader + `<AuthGate>` +
+ repoint the interceptor.
+3. Build `<RootLayout>` + the 3 React layout routes.
+4. Flip `main.ts` to the single React root (`RouterProvider`); drop
+ `createApp(App)` + `#react-app`.
+5. Sweep the 79 `useVueState` bridges → React Router hooks / app-store selectors;
+ delete `useVueState` + Vue reactivity primitives + glob registry.
+6. Replace pev2 with a React plan visualizer.
+7. Delete the Vue shell (`App.vue`, `AuthContext.vue`, 3 layouts, 5 mount bridges,
+ `ReactPageMount`, Pinia auth store, old guard) + remove `vue`/`vue-router`/
+ `pinia`/`vue-i18n`/`@vueuse`/`@vitejs/plugin-vue`/`vue-tsc` + clean the Vite
+ config + add `check-react-no-pinia.mjs`.
+
+## Verification ("no breaking changes" gate)
+- **Guard unit tests** mirroring every `beforeEach` branch (not-logged-in→signin,
+ logged-in-on-auth-route→home, 2FA enforce, password-reset enforce, 403/404,
+ OAuth callback passthrough, consent).
+- Full `type-check` / `check` / `test` (the existing 2308-test suite; pages are
+ unchanged React, so their tests stand).
+- **Manual QA of critical flows:** login, logout, session-expiry (401→surface),
+ OAuth/OIDC callback, 2FA setup, password reset, deep-link to a protected route
+ (→signin→back), workspace switch, SQL-editor entry.
+- History/back-button parity: `createBrowserRouter` ↔ the old `createWebHistory`.
+
+## Risks & mitigations
+- **Guard** (highest risk): verbatim port + unit tests + auth-flow QA.
+- **pev2 React rebuild:** the only net-new UI; isolated commit, screenshot-compare.
+- **79-file sweep:** mechanical; caught by type-check + existing page tests.
+- **Two-stage rollback safety:** built in internal order so each commit type-checks.
+
+## Out of scope
+- `projectIamPolicy` Pinia store: its bridge stays until the permission/workspace
+ layer migrates (separate, pre-existing).
+- Any page-level UI/behavior change — this is a host swap only.
diff --git a/frontend/index.html b/frontend/index.html
index b41146d27a..6dc887c722 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -12,11 +12,6 @@
</head>
<body class="text-base bg-white!">
- <div
- id="capture-container"
- class="absolute -z-50 overflow-visible"
- ></div>
-
<div id="app"></div>
<!-- React app root for globally-portaled surfaces (AgentWindow,
SessionExpiredSurface, Toaster). Visually empty; children portal
diff --git a/frontend/package.json b/frontend/package.json
index 03285cbf17..316891efec 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -66,13 +66,11 @@
"lossless-json": "^4.3.0",
"lucide-react": "^1.14.0",
"lucide-static": "^1.14.0",
- "lucide-vue-next": "^1.0.0",
"markdown-it": "^14.1.0",
"monaco-editor": "npm:@codingame/[email protected]",
"monaco-languageclient": "10.7.0",
"normalize-wheel": "^1.0.1",
"pev2": "1.21.0",
- "pinia": "3.0.4",
"pouchdb": "^9.0.0",
"pouchdb-find": "^9.0.0",
"qrcode.react": "^4.2.0",
@@ -83,6 +81,7 @@
"react-i18next": "^17.0.0",
"react-markdown": "^10.1.0",
"react-resizable-panels": "^4.11.0",
+ "react-router-dom": "^7.16.0",
"regenerator-runtime": "^0.14.1",
"rxjs": "^7.8.2",
"scroll-into-view-if-needed": "^3.1.0",
@@ -96,7 +95,6 @@
"vscode-languageclient": "9.0.1",
"vscode-ws-jsonrpc": "3.5.0",
"vue": "3.5.34",
- "vue-draggable-plus": "^0.6.0",
"zustand": "^5.0.13"
},
"devDependencies": {
@@ -162,8 +160,6 @@
"vscode-oniguruma": "^2.0.1",
"vscode-textmate": "^9.3.2",
"vue-component-type-helpers": "^3.2.8",
- "vue-i18n": "11.4.2",
- "vue-router": "4.6.4",
"vue-tsc": "3.2.8",
"ws": "^8.20.0"
},
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 471d45f6d8..9ee7b97315 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -136,9 +136,6 @@ importers:
lucide-static:
specifier: ^1.14.0
version: 1.14.0
- lucide-vue-next:
- specifier: ^1.0.0
markdown-it:
specifier: ^14.1.0
version: 14.1.1
@@ -154,9 +151,6 @@ importers:
pev2:
specifier: 1.21.0
- pinia:
- specifier: 3.0.4
pouchdb:
specifier: ^9.0.0
version: 9.0.0
@@ -187,6 +181,9 @@ importers:
react-resizable-panels:
specifier: ^4.11.0
+ react-router-dom:
+ specifier: ^7.16.0
regenerator-runtime:
specifier: ^0.14.1
version: 0.14.1
@@ -226,9 +223,6 @@ importers:
vue:
specifier: 3.5.34
version: 3.5.34([email protected])
- vue-draggable-plus:
- specifier: ^0.6.0
- version: 0.6.1(@types/[email protected])
zustand:
specifier: ^5.0.13
@@ -241,7 +235,7 @@ importers:
'@intlify/unplugin-vue-i18n':
specifier: 11.1.2
'@playwright/test':
specifier: ^1.59.1
version: 1.59.1
@@ -419,12 +413,6 @@ importers:
vue-component-type-helpers:
specifier: ^3.2.8
version: 3.2.8
- vue-i18n:
- specifier: 11.4.2
- vue-router:
- specifier: 4.6.4
vue-tsc:
specifier: 3.2.8
version: 3.2.8([email protected])
@@ -2456,9 +2444,6 @@ packages:
resolution: {integrity: sha512-6Yp8BSplP35Esa/wOG1wLNKiqXevpQTEF/RcL/NV6BBQaMmZh4YlDwCgrrFSoUE4xAGvnKd5c+lkQJmPrBAzfQ==}
- '@types/[email protected]':
- resolution: {integrity: sha512-7HP+rZGE2p886PKV9c9OJzLBI6BBJu1O7lJGYnPyG3fS4/duUCcngkNCjsLwIMV+WMqANe3tt4irrXHSIe68OQ==}
-
resolution: {integrity: sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==}
@@ -2627,18 +2612,6 @@ packages:
resolution: {integrity: sha512-cDtTHKibkThKGHH1SP+WdccquNRYQDFH6rRjQCqT9G2ltFAfoR5pUftpab/z+aM5mW9HLLVQW7hfKKQe/1GBeQ==}
- resolution: {integrity: sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==}
-
- resolution: {integrity: sha512-kIE8wvwlcZ6TJTbNeU2HQNtaxLx3a84aotTITUuL/4bzfPxzajGBOoqjMhwZJ8L9qFYDU/lAYMEEm11dnZOD6g==}
-
- resolution: {integrity: sha512-PyQ6odHSgiDVd4hnTP+aDk2X4gl2HmLDfiyEnn3/oV+ckFDuswRs4IbBT7vacMuGdwY/XemxBoh302ctbsptuA==}
-
- resolution: {integrity: sha512-iWAb0v2WYf0QWmxCGy0seZNDPdO3Sp5+u78ORnyeonS6MT4PC7VPrryX2BpMJrwlDeaZ6BD4vP4XKjK0SZqaeA==}
-
resolution: {integrity: sha512-iegbMINVc+seZ/QxtzWiOBozctrHiF2WvGedruu2EbLujg9VuU0FQiNcN2z1ycuaoKKpF4m2qzB5HDEMKbxtIg==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
@@ -2830,9 +2803,6 @@ packages:
resolution: {integrity: sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==}
- resolution: {integrity: sha512-KrayHS5pBi69Xi9JmvoqrIgYGDkD6mcSe/i6YKi3w5kekCLzrX4+nawcXqrj2tIp50Kw/mT/s3p+GVK0A0sKxw==}
-
resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==}
@@ -2982,8 +2952,8 @@ packages:
resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
- resolution: {integrity: sha512-7Vv6asjS4gMOuILabD3l739tsaxFQmC+a7pLZm02zyvs8p977bL3zEgq3yDk5rn9B0PbYgIv++jmHcuUab4RhA==}
+ resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==}
engines: {node: '>=18'}
@@ -3603,9 +3573,6 @@ packages:
resolution: {integrity: sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==}
- resolution: {integrity: sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==}
-
resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==}
engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
@@ -3751,10 +3718,6 @@ packages:
resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==}
- resolution: {integrity: sha512-oG7cgbmg5kLYae2N5IVd3jm2s+vldjxJzK1pcu9LfpGuQ93MQSzo0okvRna+7y5ifrD+20FE8FvjusyGaz14fw==}
- engines: {node: '>=18'}
-
resolution: {integrity: sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==}
engines: {node: '>=8'}
@@ -4032,12 +3995,6 @@ packages:
resolution: {integrity: sha512-QnAHXC1nk8IXRBmO5ee9JcPiKEVeqf06tKF0bZipxlV++bwUVqvvliC3KA+beDg2lod+WXYIhHde5pQRHkUmqA==}
- resolution: {integrity: sha512-V6SPvx1IHTj/UY+FrIYWV5faISsPSb8BnWSFDxAtezWKvWc9ZZ40PDrdu1/Qb5vg4lHWr1hs1BAMGVGm6V1Xdg==}
- deprecated: Package deprecated. Please use @lucide/vue instead.
- peerDependencies:
- vue: '>=3.0.1'
-
resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}
hasBin: true
@@ -4245,9 +4202,6 @@ packages:
resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==}
engines: {node: '>=16 || 14 >=14.17'}
- resolution: {integrity: sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==}
-
resolution: {integrity: sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==}
@@ -4393,9 +4347,6 @@ packages:
resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
- resolution: {integrity: sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==}
-
resolution: {integrity: sha512-FZ3dLNh8L4nycV5VRSunlD1EL5vgFEABssFIvQ89xQNkzEUq13r9RK7haEgazioOCttmvddSpwdiko8quldtFQ==}
@@ -4410,15 +4361,6 @@ packages:
resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==}
engines: {node: '>=12'}
- resolution: {integrity: sha512-l7pqLUFTI/+ESXn6k3nu30ZIzW5E2WZF/LaHJEpoq6ElcLD+wduZoB2kBN19du6K/4FDpPMazY2wJr+IndBtQw==}
- peerDependencies:
- typescript: '>=4.5.0'
- vue: ^3.5.11
- peerDependenciesMeta:
- typescript:
- optional: true
-
resolution: {integrity: sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==}
@@ -4609,6 +4551,23 @@ packages:
react: ^18.0.0 || ^19.0.0
react-dom: ^18.0.0 || ^19.0.0
+ resolution: {integrity: sha512-kMUAbimWB5FVbF4Bce4bJsiKJWLIUHq/mEG8+CFDnCSgltptBiG5nguducmsJeGKytlCvQud9Qhzpn49iduTlA==}
+ engines: {node: '>=20.0.0'}
+ peerDependencies:
+ react: '>=18'
+ react-dom: '>=18'
+
+ resolution: {integrity: sha512-wArC8lVyJb3+jM9OpDyW6hLCizACWkvQR/sSGqSs+o5uEXEtGlqdZ4v8hENR3Jad6i+LRkK93q/+bQAcvl6V1A==}
+ engines: {node: '>=20.0.0'}
+ peerDependencies:
+ react: '>=18'
+ react-dom: '>=18'
+ peerDependenciesMeta:
+ react-dom:
+ optional: true
+
resolution: {integrity: sha512-+SRbUVT2scadgFSWx+R1P754xHPEqvcfSfVX10QYg6POOz+WNgkN48pS+BtZNIMGiL1HYrSEiCkwsMS15QogEQ==}
engines: {node: '>8.0.0'}
@@ -4711,9 +4670,6 @@ packages:
resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==}
engines: {iojs: '>=1.0.0', node: '>=0.10.0'}
- resolution: {integrity: sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==}
-
resolution: {integrity: sha512-IXgzBWvWQwE6PrDI05OvmXUIruQTcoMDzRsOd5CDvHCVLcLHMTSYvOK5Cm46kWqlV3yAbuSpBZdJ5oP5OUoStg==}
@@ -4845,10 +4801,6 @@ packages:
resolution: {integrity: sha512-wcFzz9cDfbuqe0FZzfi2or1sgyIrsDwmPwfZC4hiNidPdPINjeUwNfv5kldczoEAcjl9Y1L3SM7Uz2PUEQzxQw==}
- resolution: {integrity: sha512-1POYv7uv2gXoyGFpBCmpDVSNV74IfsWlDW216UPjbWufNf+bSU6GdbDsxdcxtfwb4xlI3yxzOTKClUosxARYrQ==}
- engines: {node: '>=0.10.0'}
-
resolution: {integrity: sha512-K+WKxWdqtKShV33gPjQl769wHxB3glypTOReCvYu/AJd38J+abHlpiF8rK6uBNPMrgw5thHZCI5JkEwsAqa9XA==}
peerDependencies:
@@ -4906,10 +4858,6 @@ packages:
resolution: {integrity: sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==}
- resolution: {integrity: sha512-H+ue8Zo4vJmV2nRjpx86P35lzwDT3nItnIsocgumgr0hHMQ+ZGq5vrERg9kJBo5AWGmxZDhzDo+WVIJqkB0cGA==}
- engines: {node: '>=16'}
-
resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==}
engines: {node: '>=8'}
@@ -5279,32 +5227,12 @@ packages:
resolution: {integrity: sha512-9689efAXhN/EV86plgkL/XFiJSXhGtWPG6JDboZ+QnjlUWUUQrQ0ILKQtw4iQsuwIwu5k6Aw+JnehDe7161e7A==}
- resolution: {integrity: sha512-FbtQ/fuoixiOfTZzG3yoPl4JAo9HJXRHmBQZFB9x2NYCh6pq0TomHf7g5MUmpaDYv+LU2n6BPq2YN9sBO+FbIg==}
- peerDependencies:
- '@types/sortablejs': ^1.15.0
- '@vue/composition-api': '*'
- peerDependenciesMeta:
- '@vue/composition-api':
- optional: true
-
resolution: {integrity: sha512-Vxi9pJdbN3ZnVGLODVtZ7y4Y2kzAAE2Cm0CZ3ZDRvydVYxZ6VrnBhLikBsRS+dpwj4Jv4UCv21PTEwF5rQ9WXg==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
peerDependencies:
eslint: ^8.57.0 || ^9.0.0 || ^10.0.0
- resolution: {integrity: sha512-sADDeKXqAGsPX6tK3t3y2ZiMpbVWN12tG+MhTiJ06rVoh58eGtM4wFyw3uWGbVkXByVp9Ne/AP+nSSzI+J9OAQ==}
- engines: {node: '>= 16'}
- peerDependencies:
- vue: ^3.0.0
-
- resolution: {integrity: sha512-Hz9q5sa33Yhduglwz6g9skT8OBPii+4bFn88w6J+J4MfEo4KRRpmiNG/hHHkdbRFlLBOqxN8y8gf2Fb0MTUgVg==}
- peerDependencies:
- vue: ^3.5.0
-
resolution: {integrity: sha512-gdHbBV5/Vc8gH87hQHLA7TN1K4BlLco3MAPrTb70ZYGXxx+55rAU4a4mt0fIoP+gB3etu1khUZ6c29Br1n0CiA==}
peerDependencies:
@@ -6861,7 +6789,7 @@ snapshots:
'@humanwhocodes/[email protected]': {}
+ '@intlify/[email protected]':
dependencies:
'@intlify/message-compiler': 11.4.2
'@intlify/shared': 11.4.2
@@ -6872,8 +6800,6 @@ snapshots:
jsonc-eslint-parser: 2.4.0
source-map-js: 1.2.1
yaml-eslint-parser: 1.3.0
- optionalDependencies:
'@intlify/[email protected]':
dependencies:
@@ -6918,12 +6844,12 @@ snapshots:
'@intlify/[email protected]': {}
dependencies:
'@eslint-community/eslint-utils': 4.9.1([email protected]([email protected]))
- '@intlify/bundle-utils': 11.1.2([email protected]([email protected]([email protected])))
+ '@intlify/bundle-utils': 11.1.2
'@intlify/shared': 11.4.2
+ '@intlify/vue-i18n-extensions': 8.0.0(@intlify/[email protected])(@vue/[email protected])([email protected]([email protected]))
'@rollup/pluginutils': 5.1.4([email protected])
'@typescript-eslint/scope-manager': 8.59.2
'@typescript-eslint/typescript-estree': 8.59.2([email protected])
@@ -6935,7 +6861,6 @@ snapshots:
vue: 3.5.34([email protected])
optionalDependencies:
transitivePeerDependencies:
- '@vue/compiler-dom'
- eslint
@@ -6943,14 +6868,13 @@ snapshots:
- supports-color
- typescript
dependencies:
'@babel/parser': 7.29.3
optionalDependencies:
'@intlify/shared': 11.4.2
'@vue/compiler-dom': 3.5.34
vue: 3.5.34([email protected])
'@isaacs/[email protected]':
dependencies:
@@ -7508,8 +7432,6 @@ snapshots:
'@types/[email protected]': {}
- '@types/[email protected]': {}
-
'@types/[email protected]': {}
@@ -7765,26 +7687,6 @@ snapshots:
'@vue/compiler-dom': 3.5.34
'@vue/shared': 3.5.34
- '@vue/[email protected]': {}
-
- dependencies:
- '@vue/devtools-kit': 7.7.9
-
- dependencies:
- '@vue/devtools-shared': 7.7.9
- birpc: 2.9.0
- hookable: 5.5.3
- mitt: 3.0.1
- perfect-debounce: 1.0.0
- speakingurl: 14.0.1
- superjson: 2.2.6
-
- dependencies:
- rfdc: 1.4.1
-
dependencies:
'@typescript-eslint/utils': 8.59.2([email protected]([email protected]))([email protected])
@@ -7980,8 +7882,6 @@ snapshots:
dependencies:
require-from-string: 2.0.2
-
@@ -8128,9 +8028,7 @@ snapshots:
- dependencies:
- is-what: 5.5.0
dependencies:
@@ -8811,8 +8709,6 @@ snapshots:
dependencies:
react-is: 16.13.1
-
dependencies:
'@exodus/bytes': 1.9.0
@@ -8930,8 +8826,6 @@ snapshots:
-
dependencies:
is-docker: 2.2.1
@@ -9197,10 +9091,6 @@ snapshots:
- dependencies:
- vue: 3.5.34([email protected])
-
@@ -9609,8 +9499,6 @@ snapshots:
-
dependencies:
acorn: 8.16.0
@@ -9776,8 +9664,6 @@ snapshots:
-
dependencies:
'@fortawesome/fontawesome-svg-core': 6.7.2
@@ -9808,13 +9694,6 @@ snapshots:
- dependencies:
- '@vue/devtools-api': 7.7.9
- vue: 3.5.34([email protected])
- optionalDependencies:
- typescript: 6.0.3
-
dependencies:
confbox: 0.1.8
@@ -10056,6 +9935,20 @@ snapshots:
react: 19.2.6
react-dom: 19.2.6([email protected])
+ dependencies:
+ react: 19.2.6
+ react-dom: 19.2.6([email protected])
+
+ dependencies:
+ cookie: 1.1.1
+ react: 19.2.6
+ set-cookie-parser: 2.7.1
+ optionalDependencies:
+ react-dom: 19.2.6([email protected])
+
dependencies:
'@babel/runtime': 7.29.2
@@ -10180,8 +10073,6 @@ snapshots:
-
@@ -10338,8 +10229,6 @@ snapshots:
-
dependencies:
vue: 3.5.34([email protected])
@@ -10402,10 +10291,6 @@ snapshots:
dependencies:
inline-style-parser: 0.2.7
- dependencies:
- copy-anything: 4.0.5
-
dependencies:
has-flag: 4.0.0
@@ -10734,10 +10619,6 @@ snapshots:
- dependencies:
- '@types/sortablejs': 1.15.9
-
dependencies:
debug: 4.4.3
@@ -10750,19 +10631,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
- dependencies:
- '@intlify/core-base': 11.4.2
- '@intlify/devtools-types': 11.4.2
- '@intlify/shared': 11.4.2
- '@vue/devtools-api': 6.6.4
- vue: 3.5.34([email protected])
-
- dependencies:
- '@vue/devtools-api': 6.6.4
- vue: 3.5.34([email protected])
-
dependencies:
tippy.js: 6.3.7
diff --git a/frontend/scripts/check-react-i18n.mjs b/frontend/scripts/check-react-i18n.mjs
index 8afbfb21d1..cfb39c9bab 100644
--- a/frontend/scripts/check-react-i18n.mjs
+++ b/frontend/scripts/check-react-i18n.mjs
@@ -43,6 +43,43 @@ const DYNAMIC_PREFIXES = [
// Role-grant expiration presets, rendered via t(preset.labelKey) in
// MembersPage.tsx (EXPIRATION_PRESETS), not as literal t("…") calls.
"project.members.expiration-presets.",
+ // Keys consumed by SHARED non-React `.ts` modules that translate via
+ // `@/plugins/i18n` (the same react-i18next instance — vue-i18n is gone), but
+ // live OUTSIDE this checker's React-only scan, so they read as unused. They
+ // must stay in the React locale files (statically loaded; the runtime legacy
+ // merge does not resolve them reliably at first render — e.g. /roles). Listed
+ // with the shared caller that uses them:
+ // - role.*.self / .description — displayRoleTitle / displayRoleTitleFromList
+ // (src/utils/role.ts, src/react/lib/role.ts)
+ "role.",
+ // - project.webhook.activity-item.* — projectWebhookV1ActivityItemList
+ // (src/types/v1/projectWebhook.ts)
+ "project.webhook.activity-item.",
+ // - webhook / IM type names — projectWebhookV1TypeItemList (same file)
+ "common.dingtalk",
+ "common.discord",
+ "common.feishu",
+ "common.google-chat",
+ "common.lark",
+ "common.slack",
+ "common.teams",
+ "common.wecom",
+ // - common.canceled — src/utils/accessGrant.ts
+ "common.canceled",
+ // - common.no-license — src/utils/v1/instance.ts (instance display name)
+ "common.no-license",
+ // - data-source.{admin,read-only} — dataSourceType (src/utils/v1/instance.ts)
+ "data-source.admin",
+ "data-source.read-only",
+ // - sheet.{mine,shared} — src/views/sql-editor/Sheet/context.ts
+ "sheet.mine",
+ "sheet.shared",
+ // - task.status.available — src/utils/v1/issue/rollout.ts
+ "task.status.available",
+ // - auth.token-expired-description — src/connect/middlewares/authInterceptorMiddleware.ts
+ "auth.token-expired-description",
+ // - issue.title.export-data — src/utils/v1/issue/issue.ts
+ "issue.title.export-data",
];
const __dirname = dirname(fileURLToPath(import.meta.url));
diff --git a/frontend/src/App.vue b/frontend/src/App.vue
deleted file mode 100644
index fdb16f73c6..0000000000
--- a/frontend/src/App.vue
+++ /dev/null
@@ -1,139 +0,0 @@
-<template>
- <AuthContext>
- <router-view />
- </AuthContext>
-</template>
-
-<script lang="ts" setup>
-import { Code, ConnectError } from "@connectrpc/connect";
-import { cloneDeep, isEqual } from "lodash-es";
-import {
- onErrorCaptured,
- onMounted,
- onUnmounted,
- watch,
- watchEffect,
-} from "vue";
-import { useRoute, useRouter } from "vue-router";
-import AuthContext from "./AuthContext.vue";
-import { overrideAppProfile } from "./customAppProfile";
-import { locale, t } from "./plugins/i18n";
-import {
- type ReactQuickstartResetDetail,
- ReactShellBridgeEvent,
-} from "./react/shell-bridge";
-import { useNotificationStore, useUIStateStore } from "./store";
-import { isDev, setDocumentTitle } from "./utils";
-
-const route = useRoute();
-const router = useRouter();
-const notificationStore = useNotificationStore();
-const uiStateStore = useUIStateStore();
-
-const handleReactLocaleChange = (event: Event) => {
- const lang = (event as CustomEvent<unknown>).detail;
- if (typeof lang === "string") {
- locale.value = lang;
- if (route.meta.title) {
- setDocumentTitle(route.meta.title(route));
- }
- }
-};
-
-const handleReactQuickstartReset = (event: Event) => {
- const keys = (event as CustomEvent<ReactQuickstartResetDetail>).detail?.keys;
- if (!Array.isArray(keys)) {
- return;
- }
- void Promise.all(
- keys
- .filter((key): key is string => typeof key === "string")
- .map((key) =>
- uiStateStore.saveIntroStateByKey({
- key,
- newState: false,
- })
- )
- );
-};
-
-onMounted(() => {
- window.addEventListener(
- ReactShellBridgeEvent.localeChange,
- handleReactLocaleChange
- );
- window.addEventListener(
- ReactShellBridgeEvent.quickstartReset,
- handleReactQuickstartReset
- );
-});
-
-onUnmounted(() => {
- window.removeEventListener(
- ReactShellBridgeEvent.localeChange,
- handleReactLocaleChange
- );
- window.removeEventListener(
- ReactShellBridgeEvent.quickstartReset,
- handleReactQuickstartReset
- );
-});
-
-watchEffect(async () => {
- // Override app profile.
- overrideAppProfile();
-});
-
-onErrorCaptured((error: unknown /* , _, info */) => {
- if (
- error instanceof ConnectError &&
- Object.values(Code).includes(error.code)
- ) {
- return;
- }
-
- const err = error as { response?: unknown; stack?: string };
- if (!err.response) {
- notificationStore.pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: `Internal error captured`,
- description: isDev() ? err.stack : undefined,
- });
- }
- return true;
-});
-
-// event listener for "bb.oauth.event.unknown"
-// this event would be posted when an unknown state is returned by OAuth provider.
-// Add it here so the notification is displayed on the main window. The OAuth callback window is short lived
-// and would close before the notification has a chance to be displayed.
-window.addEventListener("bb.oauth.unknown", () => {
- notificationStore.pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("oauth.unknown-event"),
- });
-});
-
-// Preserve specific query fields when navigating between pages.
-watch(route, (current, prev) => {
- // fields is the list of query fields that we want to preserve.
- const fields = ["mode", "customTheme", "lang", "project", "filter"];
- const preservedQuery = cloneDeep(current.query);
- for (const key of fields) {
- if (preservedQuery[key] === undefined) {
- preservedQuery[key] = prev.query[key];
- }
- }
- // If the query is the same, we don't need to update the route.
- if (isEqual(current.query, preservedQuery)) {
- return;
- }
- // Otherwise, replace current route with the preserved query.
- router.replace({
- ...current,
- query: preservedQuery,
- });
-});
-</script>
diff --git a/frontend/src/AuthContext.vue b/frontend/src/AuthContext.vue
deleted file mode 100644
index 2d731b6d3b..0000000000
--- a/frontend/src/AuthContext.vue
+++ /dev/null
@@ -1,139 +0,0 @@
-<template>
- <slot v-if="ready"></slot>
- <div v-else class="flex items-center justify-center h-screen">
- <Loader2
- class="size-5 text-accent animate-spin"
- aria-label="Loading"
- role="status"
- />
- </div>
- <template v-if="!isAuthRoute && authStore.isLoggedIn">
- <!-- Session-expired surface lives in the React app
- (src/react/app/SessionExpiredSurfaceGate.tsx).
- InactiveRemindModal stays mounted here because it reads Vue router
- state via the bridged provide/inject context, which the sibling
- React app doesn't carry. -->
- <ReactPageMount
- v-if="!authStore.unauthenticatedOccurred"
- page="InactiveRemindModal"
- />
- </template>
-</template>
-
-<script setup lang="ts">
-import { Loader2 } from "lucide-vue-next";
-import { computed, onMounted, onUnmounted, ref, watch } from "vue";
-import { useRouter } from "vue-router";
-import ReactPageMount from "@/react/ReactPageMount.vue";
-import { isAuthRelatedRoute } from "@/utils/auth";
-import { t } from "./plugins/i18n";
-import { WORKSPACE_ROOT_MODULE } from "./router/dashboard/workspaceRoutes";
-import {
- pushNotification,
- useAuthStore,
- useCurrentUserV1,
- useGroupStore,
- useRoleStore,
- useSubscriptionV1Store,
- useWorkspaceV1Store,
-} from "./store";
-import { isDev } from "./utils";
-
-// This interval is used to check if the user's session is still valid.
-// In development, it checks every minute, while in production, it checks every 5 minutes.
-const CHECK_AUTHORIZATION_INTERVAL = isDev() ? 60 * 1000 : 60 * 1000 * 5;
-
-const router = useRouter();
-const authStore = useAuthStore();
-const currentUser = useCurrentUserV1();
-const workspaceStore = useWorkspaceV1Store();
-const roleStore = useRoleStore();
-const groupStore = useGroupStore();
-const subscriptionStore = useSubscriptionV1Store();
-
-const ready = ref(false);
-
-const authCheckIntervalId = ref<ReturnType<typeof setInterval>>();
-
-const isAuthRoute = computed(() => {
- return (
- router.currentRoute.value.name &&
- isAuthRelatedRoute(router.currentRoute.value.name.toString())
- );
-});
-
-onMounted(() => {
- // Periodically checks if the user's session is still valid.
- // Skips check if user is not logged in or on an auth-related route.
- authCheckIntervalId.value = setInterval(async () => {
- if (!authStore.isLoggedIn || authStore.unauthenticatedOccurred) {
- return;
- }
- if (isAuthRoute.value) {
- return;
- }
-
- await authStore.fetchCurrentUser();
- }, CHECK_AUTHORIZATION_INTERVAL);
-});
-
-onUnmounted(() => {
- // Clean up the interval when component is unmounted.
- if (authCheckIntervalId.value) {
- clearInterval(authCheckIntervalId.value);
- }
-});
-
-// When current user changed (e.g., another user logged in from different tab),
-// redirect to workspace root with notification.
-// Skip if this is a self email update (name changes from users/old@email to users/new@email).
-watch(
- () => authStore.currentUserName,
- (curr, prev) => {
- if (!curr || !prev || curr === prev) return;
-
- if (authStore.isSelfEmailUpdate) {
- authStore.isSelfEmailUpdate = false;
- return;
- }
-
- router.push({
- name: WORKSPACE_ROOT_MODULE,
- query: { _r: Date.now() },
- });
- pushNotification({
- module: "bytebase",
- style: "INFO",
- title: t("auth.login-as-another.title"),
- description: t("auth.login-as-another.content"),
- });
- }
-);
-
-watch(
- () => authStore.isLoggedIn,
- async () => {
- if (!authStore.isLoggedIn || !currentUser.value) {
- ready.value = true;
- return;
- }
-
- ready.value = false;
- try {
- await Promise.all([
- subscriptionStore.fetchSubscription(),
- workspaceStore.fetchIamPolicy(),
- workspaceStore.fetchWorkspaceList(),
- roleStore.fetchRoleList(),
- // we only care about the groups for the current user.
- groupStore.batchGetOrFetchGroups(currentUser.value.groups),
- ]);
- } finally {
- ready.value = true;
- }
- },
- {
- immediate: true,
- }
-);
-</script>
diff --git a/frontend/src/DummyRootView.ts b/frontend/src/DummyRootView.ts
deleted file mode 100644
index 0583c92e0b..0000000000
--- a/frontend/src/DummyRootView.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import { defineComponent, watch } from "vue";
-import { useRouter } from "vue-router";
-import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";
-import { WORKSPACE_ROUTE_LANDING } from "./router/dashboard/workspaceRoutes";
-import { SQL_EDITOR_HOME_MODULE } from "./router/sqlEditor";
-import { useRecentVisit } from "./router/useRecentVisit";
-import { useAppFeature } from "./store";
-
-export default defineComponent({
- name: "DummyRootView",
- setup() {
- const { lastVisit } = useRecentVisit();
- const router = useRouter();
- const databaseChangeMode = useAppFeature("bb.feature.database-change-mode");
-
- watch(
- databaseChangeMode,
- () => {
- if (databaseChangeMode.value === DatabaseChangeMode.EDITOR) {
- router.replace({
- name: SQL_EDITOR_HOME_MODULE,
- });
- return;
- }
-
- const fallback = () => {
- // If no last visit, always redirect to landing page.
- router.replace({
- name: WORKSPACE_ROUTE_LANDING,
- });
- };
-
- // Redirect to
- // - /sql-editor if defaultWorkspaceView == 'EDITOR'
- // - lastVisit.path if not empty
- // - /landing as fallback
- if (!lastVisit.value) {
- return fallback();
- }
- const path = lastVisit.value;
-
- // Ignore all possible root path records
- if (
- path === "" ||
- path === "/" ||
- path.startsWith("?") ||
- path.startsWith("#") ||
- path.startsWith("/?") ||
- path.startsWith("/#") ||
- path.startsWith("/403") ||
- path.startsWith("/404") ||
- path.startsWith("/sql-editor")
- ) {
- return fallback();
- }
- router.replace({
- path,
- });
- },
- {
- immediate: true,
- }
- );
- },
- render() {
- return null;
- },
-});
diff --git a/frontend/src/assets/css/tailwind.css b/frontend/src/assets/css/tailwind.css
index 36514c3edb..427eaa3974 100644
--- a/frontend/src/assets/css/tailwind.css
+++ b/frontend/src/assets/css/tailwind.css
@@ -316,11 +316,6 @@
}
}
-#capture-container {
- right: -99999px;
- bottom: -99999px;
-}
-
.fade-enter-active,
.fade-leave-active,
.fade-fast-enter-active,
diff --git a/frontend/src/connect/middlewares/authInterceptorMiddleware.test.ts b/frontend/src/connect/middlewares/authInterceptorMiddleware.test.ts
index 0f1dbdcee0..727b957ec6 100644
--- a/frontend/src/connect/middlewares/authInterceptorMiddleware.test.ts
+++ b/frontend/src/connect/middlewares/authInterceptorMiddleware.test.ts
@@ -24,20 +24,25 @@ vi.mock("@/plugins/i18n", () => ({
vi.mock("@/store", () => ({
pushNotification: mocks.pushNotification,
- useAuthStore: () => mocks.authStore,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/utils/app-store-bridge", () => ({
+ appStoreUtilBridge: () => ({
+ isLoggedIn: () => mocks.authStore.isLoggedIn,
+ setUnauthenticatedOccurred: (v: boolean) => {
+ mocks.authStore.unauthenticatedOccurred = v;
+ },
+ }),
+}));
+
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
currentRoute: mocks.currentRoute,
push: mocks.routerPush,
},
}));
-vi.mock("@/router/dashboard/workspaceRoutes", () => ({
- WORKSPACE_ROUTE_403: "workspace.403",
-}));
-
vi.mock("../refreshToken", () => ({
refreshTokens: mocks.refreshTokens,
}));
@@ -161,7 +166,7 @@ describe("authInterceptor", () => {
code: Code.PermissionDenied,
});
expect(mocks.routerPush).toHaveBeenCalledWith({
- name: "workspace.403",
+ name: "error.403",
query: undefined,
});
});
diff --git a/frontend/src/connect/middlewares/authInterceptorMiddleware.ts b/frontend/src/connect/middlewares/authInterceptorMiddleware.ts
index 5849a82703..dbc111fbbf 100644
--- a/frontend/src/connect/middlewares/authInterceptorMiddleware.ts
+++ b/frontend/src/connect/middlewares/authInterceptorMiddleware.ts
@@ -1,9 +1,10 @@
import { Code, ConnectError, type Interceptor } from "@connectrpc/connect";
import { t } from "@/plugins/i18n";
-import { router } from "@/router";
-import { WORKSPACE_ROUTE_403 } from "@/router/dashboard/workspaceRoutes";
-import { pushNotification, useAuthStore } from "@/store";
+import { router } from "@/react/router";
+import { WORKSPACE_ROUTE_403 } from "@/react/router/handles";
+import { pushNotification } from "@/store";
import { PermissionDeniedDetailSchema } from "@/types/proto-es/v1/common_pb";
+import { appStoreUtilBridge } from "@/utils/app-store-bridge";
import { ignoredCodesContextKey, silentContextKey } from "../context-key";
import { refreshTokens } from "../refreshToken";
@@ -24,8 +25,11 @@ const handleUnauthenticatedFailure = ({
silent: boolean;
isLoggedIn: boolean;
}) => {
- const authStore = useAuthStore();
- authStore.unauthenticatedOccurred = true;
+ // Flag the app store (the session source of truth) so React's
+ // SessionExpiredSurface fires. Routed through the util bridge (a leaf module)
+ // to avoid a load-time cycle — the app store imports the connect clients this
+ // interceptor wraps.
+ appStoreUtilBridge()?.setUnauthenticatedOccurred(true);
if (!silent && isLoggedIn) {
pushNotification({
module: "bytebase",
@@ -40,7 +44,6 @@ export const authInterceptor: Interceptor = (next) => async (req) => {
try {
return await next(req);
} catch (error) {
- const authStore = useAuthStore();
const silent = req.contextValues.get(silentContextKey);
const ignoredCodes = req.contextValues.get(ignoredCodesContextKey);
@@ -66,7 +69,7 @@ export const authInterceptor: Interceptor = (next) => async (req) => {
console.error(e);
handleUnauthenticatedFailure({
silent,
- isLoggedIn: authStore.isLoggedIn,
+ isLoggedIn: appStoreUtilBridge()?.isLoggedIn() ?? false,
});
throw error;
}
@@ -80,7 +83,7 @@ export const authInterceptor: Interceptor = (next) => async (req) => {
) {
handleUnauthenticatedFailure({
silent,
- isLoggedIn: authStore.isLoggedIn,
+ isLoggedIn: appStoreUtilBridge()?.isLoggedIn() ?? false,
});
}
throw retryError;
diff --git a/frontend/src/customAppProfile.ts b/frontend/src/customAppProfile.ts
deleted file mode 100644
index f3599f2476..0000000000
--- a/frontend/src/customAppProfile.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { computed } from "vue";
-import { locale } from "./plugins/i18n";
-import { useActuatorV1Store, useSettingV1Store } from "./store";
-import { defaultAppProfile } from "./types";
-import { DatabaseChangeMode } from "./types/proto-es/v1/setting_service_pb";
-
-export const overrideAppProfile = () => {
- overrideAppFeatures();
-
- // Override app language.
- const query = new URLSearchParams(window.location.search);
- const lang = query.get("lang");
- if (lang) {
- locale.value = lang;
- }
-};
-
-const overrideAppFeatures = () => {
- const actuatorStore = useActuatorV1Store();
- const settingV1Store = useSettingV1Store();
-
- const databaseChangeMode = computed(() => {
- const mode = settingV1Store.workspaceProfile.databaseChangeMode;
- if (mode === DatabaseChangeMode.EDITOR) return DatabaseChangeMode.EDITOR;
- return DatabaseChangeMode.PIPELINE;
- });
-
- actuatorStore.appProfile = defaultAppProfile();
- actuatorStore.overrideAppFeatures({
- "bb.feature.database-change-mode": databaseChangeMode.value,
- });
-
- if (databaseChangeMode.value === DatabaseChangeMode.EDITOR) {
- actuatorStore.overrideAppFeatures({
- "bb.feature.hide-quick-start": true,
- "bb.feature.hide-trial": true,
- });
- }
-};
diff --git a/frontend/src/layouts/BodyLayout.vue b/frontend/src/layouts/BodyLayout.vue
deleted file mode 100644
index 2429bbb217..0000000000
--- a/frontend/src/layouts/BodyLayout.vue
+++ /dev/null
@@ -1,152 +0,0 @@
-<template>
- <ReactPageMount
- page="DashboardBodyShell"
- :page-props="{
- variant: 'workspace',
- isRootPath,
- routeKey: route.fullPath,
- onReady: handleReady,
- }"
- />
-
- <teleport v-if="sidebarTarget && !isRootPath" :to="sidebarTarget">
- <router-view name="leftSidebar" />
- </teleport>
-
- <teleport v-if="contentTarget && isProjectRoute" :to="contentTarget">
- <router-view name="content" />
- </teleport>
-
- <teleport v-else-if="contentTarget" :to="contentTarget">
- <ReactPageMount
- page="RoutePermissionGuardShell"
- :page-props="{
- routeKey: route.fullPath,
- className: 'm-4',
- targetClassName: 'h-full min-h-0',
- onReady: handlePermissionReady,
- }"
- />
- </teleport>
-
- <teleport
- v-if="!isProjectRoute && routePermissionTarget"
- :to="routePermissionTarget"
- >
- <router-view name="content" />
- </teleport>
-
- <teleport v-if="quickstartTarget" :to="quickstartTarget">
- <ReactPageMount page="Quickstart" container-class="w-full" />
- </teleport>
-
-</template>
-
-<script lang="ts" setup>
-import { useWindowSize } from "@vueuse/core";
-import { computed, onMounted, onUnmounted, ref, shallowRef, watch } from "vue";
-import { useRoute, useRouter } from "vue-router";
-import { t } from "@/plugins/i18n";
-import type { DashboardShellTargets } from "@/react/dashboard-shell";
-import ReactPageMount from "@/react/ReactPageMount.vue";
-import { WORKSPACE_ROOT_MODULE } from "@/router/dashboard/workspaceRoutes";
-import { pushNotification, useActuatorV1Store } from "@/store";
-
-import { provideBodyLayoutContext } from "./common";
-
-const actuatorStore = useActuatorV1Store();
-const route = useRoute();
-const router = useRouter();
-const { width: windowWidth } = useWindowSize();
-
-const shellTargets = shallowRef<DashboardShellTargets>({
- desktopSidebar: null,
- mobileSidebar: null,
- content: null,
- quickstart: null,
- mainContainer: null,
-});
-const mainContainerRef = ref<HTMLDivElement>();
-const routePermissionTarget = shallowRef<HTMLDivElement | null>(null);
-
-const isRootPath = computed(() => {
- return router.currentRoute.value.name === WORKSPACE_ROOT_MODULE;
-});
-const isProjectRoute = computed(() => {
- return Boolean(route.params.projectId);
-});
-
-const contentTarget = computed(() => shellTargets.value.content);
-const quickstartTarget = computed(() => shellTargets.value.quickstart);
-const sidebarTarget = computed(() => {
- if (windowWidth.value >= 768) {
- return shellTargets.value.desktopSidebar;
- }
- return shellTargets.value.mobileSidebar;
-});
-
-const handleReady = (targets: DashboardShellTargets) => {
- shellTargets.value = targets;
- mainContainerRef.value = targets.mainContainer ?? undefined;
-};
-
-const handlePermissionReady = (target: HTMLDivElement | null) => {
- routePermissionTarget.value = target;
-};
-
-watch(
- () => route.fullPath,
- () => {
- routePermissionTarget.value = null;
- },
- { flush: "sync" }
-);
-
-const refreshRemindTimer = ref<ReturnType<typeof setTimeout>>();
-onMounted(async () => {
- const remind = await actuatorStore.tryToRemindRefresh();
- if (remind) {
- pushNotification({
- module: "bytebase",
- style: "WARN",
- title: t("refresh-remind.title"),
- description: t("refresh-remind.description"),
- manualHide: true,
- });
- }
- refreshRemindTimer.value = setInterval(
- async () => {
- const remind = await actuatorStore.tryToRemindRefresh();
- if (remind) {
- pushNotification({
- module: "bytebase",
- style: "WARN",
- title: t("refresh-remind.title"),
- description: t("refresh-remind.description"),
- manualHide: true,
- });
- }
- },
- 1000 * 60 * 30
- );
-});
-onUnmounted(() => {
- if (refreshRemindTimer.value) {
- clearInterval(refreshRemindTimer.value);
- }
-});
-
-const agentShortcutHandler = async (e: KeyboardEvent) => {
- if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === "A") {
- e.preventDefault();
- const { useAgentStore } = await import("@/react/plugins/agent/store/agent");
- useAgentStore.getState().toggle();
- }
-};
-onMounted(() => window.addEventListener("keydown", agentShortcutHandler));
-onUnmounted(() => window.removeEventListener("keydown", agentShortcutHandler));
-
-provideBodyLayoutContext({
- mainContainerRef,
-});
-</script>
diff --git a/frontend/src/layouts/DashboardLayout.vue b/frontend/src/layouts/DashboardLayout.vue
deleted file mode 100644
index 44fcb2f3f4..0000000000
--- a/frontend/src/layouts/DashboardLayout.vue
+++ /dev/null
@@ -1,25 +0,0 @@
-<template>
- <ReactPageMount
- page="DashboardFrameShell"
- :page-props="{ onReady: handleReady }"
- />
-
- <teleport v-if="targets.body" :to="targets.body">
- <router-view name="body" />
- </teleport>
-</template>
-
-<script lang="ts" setup>
-import { shallowRef } from "vue";
-import type { DashboardFrameShellTargets } from "@/react/dashboard-shell";
-import ReactPageMount from "@/react/ReactPageMount.vue";
-
-const targets = shallowRef<DashboardFrameShellTargets>({
- banner: null,
- body: null,
-});
-
-const handleReady = (nextTargets: DashboardFrameShellTargets) => {
- targets.value = nextTargets;
-};
-</script>
diff --git a/frontend/src/layouts/SplashLayout.vue b/frontend/src/layouts/SplashLayout.vue
deleted file mode 100644
index d2228e7edb..0000000000
--- a/frontend/src/layouts/SplashLayout.vue
+++ /dev/null
@@ -1,48 +0,0 @@
-<template>
- <div class="min-h-screen overflow-hidden flex">
- <div
- v-if="showBrandingImage"
- class="hidden bg-white lg:block relative w-0 flex-1"
- >
- <img
- v-if="route === AUTH_SIGNUP_MODULE"
- class="absolute inset-0 h-full w-full object-cover"
- src="@/assets/illustration/signup.webp"
- alt=""
- />
- <img
- v-else
- class="absolute inset-0 h-full w-full object-cover"
- src="@/assets/illustration/signin.webp"
- alt=""
- />
- </div>
- <div
- class="relative mx-auto flex-1 flex flex-col justify-center py-12 pb-24 px-4 sm:px-6 lg:flex-none lg:px-20 lg:w-1/2 xl:px-24"
- >
- <router-view />
- </div>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { computed } from "vue";
-import { useRouter } from "vue-router";
-import { AUTH_SIGNUP_MODULE } from "@/router/auth";
-import { useSubscriptionV1Store } from "@/store";
-import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";
-
-const router = useRouter();
-const subscriptionStore = useSubscriptionV1Store();
-
-const route = computed(() => {
- return router.currentRoute.value.name;
-});
-
-const showBrandingImage = computed(() => {
- return (
- subscriptionStore.currentPlan !== PlanType.ENTERPRISE ||
- subscriptionStore.isTrialing
- );
-});
-</script>
diff --git a/frontend/src/layouts/common.ts b/frontend/src/layouts/common.ts
deleted file mode 100644
index 933b5ad89e..0000000000
--- a/frontend/src/layouts/common.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { type InjectionKey, inject, provide, type Ref } from "vue";
-
-export type BodyLayoutContext = ReturnType<typeof provideBodyLayoutContext>;
-
-const BODY_LAYOUT_CONTEXT_KEY = Symbol(
- "bb.body-layout.context"
-) as InjectionKey<BodyLayoutContext>;
-
-export const provideBodyLayoutContext = (params: {
- mainContainerRef: Ref<HTMLDivElement | undefined>;
-}) => {
- const context = {
- ...params,
- };
- provide(BODY_LAYOUT_CONTEXT_KEY, context);
-
- return context;
-};
-
-export const useBodyLayoutContext = () => {
- return inject(BODY_LAYOUT_CONTEXT_KEY)!;
-};
diff --git a/frontend/src/layouts/layout-bridge.test.ts b/frontend/src/layouts/layout-bridge.test.ts
deleted file mode 100644
index 01b5ec12ea..0000000000
--- a/frontend/src/layouts/layout-bridge.test.ts
+++ /dev/null
@@ -1,325 +0,0 @@
-import { mount } from "@vue/test-utils";
-import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
-import { defineComponent, h, nextTick } from "vue";
-import { createMemoryHistory, createRouter, RouterView } from "vue-router";
-import { useBodyLayoutContext } from "./common";
-
-const mocks = vi.hoisted(() => ({
- width: { value: 1024 },
- pushNotification: vi.fn(),
- tryToRemindRelease: vi.fn(async () => false),
- tryToRemindRefresh: vi.fn(async () => false),
-}));
-
-vi.mock("@vueuse/core", () => ({
- useWindowSize: () => ({
- width: mocks.width,
- }),
-}));
-
-vi.mock("@/react/ReactPageMount.vue", async () => {
- const { defineComponent, h, onMounted, ref } = await import("vue");
-
- return {
- default: defineComponent({
- name: "MockReactPageMount",
- props: {
- page: {
- type: String,
- required: true,
- },
- pageProps: {
- type: Object,
- default: undefined,
- },
- },
- setup(props) {
- const desktopSidebar = ref<HTMLDivElement | null>(null);
- const mobileSidebar = ref<HTMLDivElement | null>(null);
- const content = ref<HTMLDivElement | null>(null);
- const quickstart = ref<HTMLDivElement | null>(null);
- const mainContainer = ref<HTMLDivElement | null>(null);
- const permissionTarget = ref<HTMLDivElement | null>(null);
-
- onMounted(() => {
- if (props.page === "DashboardFrameShell") {
- return;
- }
- if (props.page === "Quickstart") {
- return;
- }
- if (props.page === "RoutePermissionGuardShell") {
- props.pageProps?.onReady?.(permissionTarget.value);
- return;
- }
-
- props.pageProps?.onReady?.({
- desktopSidebar:
- props.pageProps.variant === "workspace"
- ? desktopSidebar.value
- : null,
- mobileSidebar:
- props.pageProps.variant === "workspace"
- ? mobileSidebar.value
- : null,
- content: content.value,
- quickstart: quickstart.value,
- mainContainer: mainContainer.value,
- });
- });
-
- if (props.page === "Quickstart") {
- // Match the marker the legacy `<Quickstart />` Vue mock emitted
- // — this lets the existing teleport assertions keep working
- // unchanged after the React port replaced the Vue component
- // with `<ReactPageMount page="Quickstart">` in BodyLayout.vue
- // and ReactRouteShellBridge.vue.
- return () => h("div", { "data-testid": "quickstart" }, "quickstart");
- }
- return () =>
- props.page === "RoutePermissionGuardShell"
- ? h("div", {
- ref: permissionTarget,
- "data-testid": "permission-guard",
- class: props.pageProps?.targetClassName,
- })
- : h("div", { "data-testid": "mock-shell" }, [
- h("div", {
- ref: desktopSidebar,
- "data-testid": "shell-desktop-sidebar",
- }),
- h("div", {
- ref: mobileSidebar,
- "data-testid": "shell-mobile-sidebar",
- }),
- h(
- "div",
- {
- id: "bb-layout-main",
- ref: mainContainer,
- },
- [
- h("div", {
- ref: content,
- "data-testid": "shell-content",
- }),
- ]
- ),
- h("div", {
- ref: quickstart,
- "data-testid": "shell-quickstart",
- }),
- ]);
- },
- }),
- };
-});
-
-vi.mock("@/plugins/i18n", () => ({
- t: (key: string) => key,
-}));
-
-vi.mock("@/router/dashboard/workspaceRoutes", () => ({
- WORKSPACE_ROOT_MODULE: "workspace.root",
-}));
-
-vi.mock("@/store", () => ({
- pushNotification: mocks.pushNotification,
- useActuatorV1Store: () => ({
- tryToRemindRelease: mocks.tryToRemindRelease,
- tryToRemindRefresh: mocks.tryToRemindRefresh,
- }),
- usePermissionStore: () => ({
- currentRolesInWorkspace: new Set<string>(),
- currentPermissions: new Set<string>(["bb.test"]),
- currentPermissionsInProjectV1: () => new Set<string>(["bb.test"]),
- }),
- useSubscriptionV1Store: () => ({
- currentPlan: 0,
- }),
-}));
-
-vi.mock("@/types", () => ({
- PresetRoleType: {
- WORKSPACE_ADMIN: "WORKSPACE_ADMIN",
- },
- BASIC_WORKSPACE_PERMISSIONS: [],
-}));
-
-vi.mock("@/types/proto-es/v1/subscription_service_pb", () => ({
- PlanType: {
- ENTERPRISE: 1,
- },
-}));
-
-import ReactRouteShellBridge from "@/react/ReactRouteShellBridge.vue";
-import BodyLayout from "./BodyLayout.vue";
-
-const SidebarView = defineComponent({
- name: "SidebarView",
- setup() {
- return () => h("div", { "data-testid": "sidebar-view" }, "sidebar");
- },
-});
-
-const ContentView = defineComponent({
- name: "ContentView",
- setup() {
- const context = useBodyLayoutContext();
- return () =>
- h("div", { "data-testid": "content-view" }, [
- "content:",
- context.mainContainerRef.value ===
- document.getElementById("bb-layout-main")
- ? "connected"
- : "missing",
- ]);
- },
-});
-
-async function mountRouteTree(
- routes: Parameters<typeof createRouter>[0]["routes"],
- target = "/target"
-) {
- const router = createRouter({
- history: createMemoryHistory(),
- routes,
- });
- await router.push(target);
- await router.isReady();
-
- const wrapper = mount(RouterView, {
- attachTo: document.body,
- global: {
- plugins: [router],
- },
- });
- await nextTick();
- return wrapper;
-}
-
-beforeEach(() => {
- mocks.width.value = 1024;
- mocks.pushNotification.mockClear();
- mocks.tryToRemindRefresh.mockClear();
- mocks.tryToRemindRelease.mockClear();
-});
-
-afterEach(() => {
- document.body.innerHTML = "";
-});
-
-describe("layout bridges", () => {
- test("BodyLayout teleports sidebar, content, and quickstart into the shell", async () => {
- const wrapper = await mountRouteTree([
- {
- path: "/",
- component: BodyLayout,
- children: [
- {
- path: "target",
- name: "workspace.projects",
- components: {
- leftSidebar: SidebarView,
- content: ContentView,
- },
- },
- ],
- },
- ]);
-
- expect(
- document.querySelector(
- '[data-testid="shell-desktop-sidebar"] [data-testid="sidebar-view"]'
- )
- ).not.toBeNull();
- expect(
- document.querySelector(
- '[data-testid="shell-content"] [data-testid="permission-guard"] [data-testid="content-view"]'
- )?.textContent
- ).toContain("connected");
- expect(
- document.querySelector(
- '[data-testid="shell-quickstart"] [data-testid="quickstart"]'
- )
- ).not.toBeNull();
-
- wrapper.unmount();
- });
-
- test("BodyLayout lets project routes reach their project permission shell", async () => {
- const wrapper = await mountRouteTree(
- [
- {
- path: "/",
- component: BodyLayout,
- children: [
- {
- path: "target/:projectId",
- name: "workspace.projects.detail",
- components: {
- leftSidebar: SidebarView,
- content: ContentView,
- },
- },
- ],
- },
- ],
- "/target/prod"
- );
-
- expect(
- document.querySelector(
- '[data-testid="shell-content"] > [data-testid="content-view"]'
- )?.textContent
- ).toContain("connected");
- expect(
- document.querySelector(
- '[data-testid="shell-content"] [data-testid="permission-guard"]'
- )
- ).toBeNull();
-
- wrapper.unmount();
- });
-
- test("ReactRouteShellBridge teleports named route content into React shell", async () => {
- const wrapper = await mountRouteTree([
- {
- path: "/",
- component: ReactRouteShellBridge,
- props: {
- page: "IssuesRouteShell",
- routerViewName: "content",
- },
- children: [
- {
- path: "target",
- name: "issues.target",
- components: {
- leftSidebar: SidebarView,
- content: ContentView,
- },
- },
- ],
- },
- ]);
-
- expect(
- document.querySelector(
- '[data-testid="shell-desktop-sidebar"] [data-testid="sidebar-view"]'
- )
- ).toBeNull();
- expect(
- document.querySelector(
- '[data-testid="shell-content"] [data-testid="content-view"]'
- )?.textContent
- ).toContain("connected");
- expect(
- document.querySelector(
- '[data-testid="shell-quickstart"] [data-testid="quickstart"]'
- )
- ).not.toBeNull();
-
- wrapper.unmount();
- });
-});
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 0fa6e3f932..2158f83c26 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -4,11 +4,9 @@
"content": "We will redirect you to the home page.",
"title": "You have logged in as another user"
},
- "password-forgot": "Forgot Password",
"password-reset": {
"title": "Reset your password"
},
- "profile-setup": "Profile Setup",
"token-expired-description": "Token has expired, please login again",
"token-expired-title": "Token expired"
},
@@ -72,12 +70,9 @@
}
},
"error-page": {
- "forbidden": "Forbidden",
"not-found": "Not Found"
},
- "export-center": {
- "self": "Export Center"
- },
+ "export-center": {},
"gitops": {
"self": "GitOps"
},
@@ -93,12 +88,8 @@
"export-data": "Export data"
}
},
- "multi-factor": {
- "self": "Multi-factor authentication"
- },
- "oauth": {
- "unknown-event": "Unexpected event type, OAuth failed."
- },
+ "multi-factor": {},
+ "oauth": {},
"oauth2": {
"consent": {
"title": "Authorization Request"
@@ -137,14 +128,10 @@
"label": "When pipeline tasks fail",
"title": "Pipeline failed"
}
- },
- "create-webhook": "Create webhook"
+ }
}
},
- "refresh-remind": {
- "description": "Detect outdated version. Please refresh the page.",
- "title": "Outdated version detected"
- },
+ "refresh-remind": {},
"release": {
"releases": "Releases"
},
@@ -256,7 +243,6 @@
"integration": "Integration",
"mcp": "MCP",
"members": "Members",
- "profile": "Profile",
"security-and-policy": "Security & Policy",
"sso": "SSO",
"subscription": "Subscription"
@@ -281,9 +267,7 @@
"self": "SQL Editor"
},
"sql-review": {
- "create": {
- "breadcrumb": "Create SQL review policy"
- },
+ "create": {},
"level": {
"error": "Error",
"name": "Level",
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index e940b41439..870acf4122 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -4,11 +4,9 @@
"content": "Lo redirigiremos a la página de inicio.",
"title": "Has iniciado sesión como otro usuario"
},
- "password-forgot": "Contraseña olvidada",
"password-reset": {
"title": "Restablecer su contraseña"
},
- "profile-setup": "Configurar perfil",
"token-expired-description": "El token ha expirado, por favor inicia sesión nuevamente",
"token-expired-title": "Token expirado"
},
@@ -72,12 +70,9 @@
}
},
"error-page": {
- "forbidden": "Prohibido",
"not-found": "No encontrado"
},
- "export-center": {
- "self": "centro de exportacion"
- },
+ "export-center": {},
"gitops": {
"self": "GitOps"
},
@@ -93,12 +88,8 @@
"export-data": "Exportar datos"
}
},
- "multi-factor": {
- "self": "Autenticación de múltiples factores"
- },
- "oauth": {
- "unknown-event": "Tipo de evento inesperado, OAuth falló."
- },
+ "multi-factor": {},
+ "oauth": {},
"oauth2": {
"consent": {
"title": "Solicitud de autorización"
@@ -137,14 +128,10 @@
"label": "Cuando las tareas del pipeline fallan",
"title": "Pipeline fallido"
}
- },
- "create-webhook": "Crear webhook"
+ }
}
},
- "refresh-remind": {
- "description": "Se ha detectado una versión obsoleta. Por favor, actualice la página.",
- "title": "Versión obsoleta detectada"
- },
+ "refresh-remind": {},
"release": {
"releases": "Lanzamientos"
},
@@ -256,7 +243,6 @@
"integration": "Integración",
"mcp": "MCP",
"members": "Miembros",
- "profile": "Perfil",
"security-and-policy": "Seguridad y Política",
"sso": "SSO",
"subscription": "Suscripción"
@@ -281,9 +267,7 @@
"self": "Editor de SQL"
},
"sql-review": {
- "create": {
- "breadcrumb": "Crear política de revisión SQL"
- },
+ "create": {},
"level": {
"error": "Error",
"name": "Nivel",
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 7860fe1723..9868104112 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -4,11 +4,9 @@
"content": "ホームページへリダイレクトさせていただきます。",
"title": "別のユーザーとしてログインしています"
},
- "password-forgot": "パスワードを忘れる",
"password-reset": {
"title": "あなたのパスワードをリセット"
},
- "profile-setup": "プロフィール設定",
"token-expired-description": "トークンの有効期限が切れています。再度ログインしてください。",
"token-expired-title": "トークンの有効期限が切れました"
},
@@ -72,12 +70,9 @@
}
},
"error-page": {
- "forbidden": "アクセス禁止",
"not-found": "ページが見つかりません"
},
- "export-center": {
- "self": "エクスポートセンター"
- },
+ "export-center": {},
"gitops": {
"self": "GitOps"
},
@@ -93,12 +88,8 @@
"export-data": "データをエクスポート"
}
},
- "multi-factor": {
- "self": "多要素認証"
- },
- "oauth": {
- "unknown-event": "不明なイベント タイプ、認証に失敗しました"
- },
+ "multi-factor": {},
+ "oauth": {},
"oauth2": {
"consent": {
"title": "認証リクエスト"
@@ -137,14 +128,10 @@
"label": "パイプラインタスクが失敗したとき",
"title": "パイプラインが失敗しました"
}
- },
- "create-webhook": "Webhook の作成"
+ }
}
},
- "refresh-remind": {
- "description": "古いバージョンが検出されました。ページを更新してください。",
- "title": "古いバージョンが検出されました"
- },
+ "refresh-remind": {},
"release": {
"releases": "リリース"
},
@@ -256,7 +243,6 @@
"integration": "連携",
"mcp": "MCP",
"members": "メンバー",
- "profile": "プロフィール",
"security-and-policy": "セキュリティポリシー",
"sso": "SSO",
"subscription": "サブスクリプション"
@@ -281,9 +267,7 @@
"self": "SQLエディタ"
},
"sql-review": {
- "create": {
- "breadcrumb": "SQL レビューポリシーを作成する"
- },
+ "create": {},
"level": {
"error": "エラー",
"name": "レベル",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 9d9b1e4b44..eecc8baba1 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -4,11 +4,9 @@
"content": "Chúng tôi sẽ chuyển hướng bạn đến trang chủ.",
"title": "Bạn đã đăng nhập với tư cách người dùng khác"
},
- "password-forgot": "Quên mật khẩu",
"password-reset": {
"title": "Đặt lại mật khẩu của bạn"
},
- "profile-setup": "Thiết lập hồ sơ",
"token-expired-description": "Mã thông báo đã hết hạn, vui lòng đăng nhập lại",
"token-expired-title": "Mã thông báo đã hết hạn"
},
@@ -72,12 +70,9 @@
}
},
"error-page": {
- "forbidden": "Bị cấm",
"not-found": "Không tìm thấy"
},
- "export-center": {
- "self": "Trung tâm xuất"
- },
+ "export-center": {},
"gitops": {
"self": "GitOps"
},
@@ -93,12 +88,8 @@
"export-data": "Xuất dữ liệu"
}
},
- "multi-factor": {
- "self": "Xác thực đa yếu tố"
- },
- "oauth": {
- "unknown-event": "Loại sự kiện không mong đợi, OAuth không thành công."
- },
+ "multi-factor": {},
+ "oauth": {},
"oauth2": {
"consent": {
"title": "Yêu cầu ủy quyền"
@@ -137,14 +128,10 @@
"label": "Khi các tác vụ pipeline thất bại",
"title": "Pipeline thất bại"
}
- },
- "create-webhook": "Tạo webhook"
+ }
}
},
- "refresh-remind": {
- "description": "Đã phát hiện phiên bản lỗi thời. Vui lòng làm mới trang.",
- "title": "Đã phát hiện phiên bản lỗi thời"
- },
+ "refresh-remind": {},
"release": {
"releases": "Bản phát hành"
},
@@ -256,7 +243,6 @@
"integration": "Tích hợp",
"mcp": "MCP",
"members": "Thành viên",
- "profile": "Hồ sơ",
"security-and-policy": "Bảo mật & Chính sách",
"sso": "SSO",
"subscription": "Gói đăng ký"
@@ -281,9 +267,7 @@
"self": "Trình soạn thảo SQL"
},
"sql-review": {
- "create": {
- "breadcrumb": "Tạo chính sách đánh giá SQL"
- },
+ "create": {},
"level": {
"error": "Lỗi",
"name": "Cấp độ",
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 88e7737c79..40fa7e69b0 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -4,11 +4,9 @@
"content": "我们将把您重定向到主页。",
"title": "您已以其他用户身份登录"
},
- "password-forgot": "忘记密码",
"password-reset": {
"title": "重置您的密码"
},
- "profile-setup": "设置个人资料",
"token-expired-description": "Token 已过期,请重新登录",
"token-expired-title": "Token 已过期"
},
@@ -72,12 +70,9 @@
}
},
"error-page": {
- "forbidden": "禁止访问",
"not-found": "页面未找到"
},
- "export-center": {
- "self": "导出中心"
- },
+ "export-center": {},
"gitops": {
"self": "GitOps"
},
@@ -93,12 +88,8 @@
"export-data": "导出数据"
}
},
- "multi-factor": {
- "self": "多重认证"
- },
- "oauth": {
- "unknown-event": "未知的事件类型,认证失败"
- },
+ "multi-factor": {},
+ "oauth": {},
"oauth2": {
"consent": {
"title": "授权请求"
@@ -137,14 +128,10 @@
"label": "当流水线任务失败",
"title": "流水线失败"
}
- },
- "create-webhook": "创建 webhook"
+ }
}
},
- "refresh-remind": {
- "description": "检测到过时版本。请刷新页面。",
- "title": "检测到过时版本"
- },
+ "refresh-remind": {},
"release": {
"releases": "发布包"
},
@@ -256,7 +243,6 @@
"integration": "集成",
"mcp": "MCP",
"members": "成员",
- "profile": "个人信息",
"security-and-policy": "安全 & 策略",
"sso": "SSO",
"subscription": "订阅"
@@ -281,9 +267,7 @@
"self": "SQL 编辑器"
},
"sql-review": {
- "create": {
- "breadcrumb": "创建审核策略"
- },
+ "create": {},
"level": {
"error": "错误",
"name": "级别",
diff --git a/frontend/src/main.ts b/frontend/src/main.ts
index 6cd63cd922..700db63101 100644
--- a/frontend/src/main.ts
+++ b/frontend/src/main.ts
@@ -1,33 +1,18 @@
// Must be first - initializes global compatibility shims
import "./init";
import "regenerator-runtime/runtime";
-import { createApp } from "vue";
-import App from "./App.vue";
import "./assets/css/github-markdown-style.css";
import "./assets/css/tailwind.css";
-import dayjs from "./plugins/dayjs";
-import highlight from "./plugins/highlight";
-import i18n from "./plugins/i18n";
-import "./polyfill";
+// Side-effect: configures the shared dayjs singleton (localizedFormat) and
+// registers the SQL highlight.js language + theme used across the app.
+import "./plugins/dayjs";
+import "./plugins/highlight";
// Side-effect: registers the bb.vue-notification window listener and
// constructs the toastManager singleton. Must load before any auth/error
// interceptor can fire pushNotification during bootstrap RPCs.
import "./react/lib/toast";
-import { router } from "./router";
-import {
- pinia,
- useActuatorV1Store,
- useAuthStore,
- useSubscriptionV1Store,
- useWorkspaceV1Store,
-} from "./store";
-import {
- humanizeDate,
- humanizeTs,
- isDev,
- isRelease,
- migrateStorageKeys,
-} from "./utils";
+import { useAppStore } from "./react/stores/app";
+import { isDev, isRelease, migrateStorageKeys } from "./utils";
console.debug("dev:", isDev());
console.debug("release:", isRelease());
@@ -36,41 +21,20 @@ console.debug("release:", isRelease());
migrateStorageKeys();
(async () => {
- const app = createApp(App);
+ const store = useAppStore.getState();
- // Allow template to access various function
- app.config.globalProperties.window = window;
- app.config.globalProperties.console = console;
- app.config.globalProperties.dayjs = dayjs;
- app.config.globalProperties.humanizeTs = humanizeTs;
- app.config.globalProperties.humanizeDate = humanizeDate;
- app.config.globalProperties.isDev = isDev();
- app.config.globalProperties.isRelease = isRelease();
-
- app.use(pinia);
-
- const currentUser = await useAuthStore().fetchCurrentUser();
- // Initialize stores.
- const initPromises: Promise<unknown>[] = [
- useActuatorV1Store().fetchServerInfo(currentUser?.workspace),
- ];
+ // Load the authenticated session BEFORE mounting so the route guard sees the
+ // correct auth state on the very first navigation (the Vue bootstrap awaited
+ // fetchCurrentUser + server info the same way before mounting the router).
+ const currentUser = await store.loadCurrentUser();
+ const initPromises: Promise<unknown>[] = [store.loadServerInfo()];
if (currentUser) {
- initPromises.push(useSubscriptionV1Store().fetchSubscription());
- initPromises.push(useWorkspaceV1Store().fetchWorkspaceList());
+ initPromises.push(store.loadSubscription());
+ initPromises.push(store.loadWorkspaceList());
+ initPromises.push(store.loadWorkspaceProfile());
}
await Promise.all(initPromises);
- app.use(router).use(highlight).use(i18n);
-
- app.mount("#app");
-
- // Mount the sibling React app hosting AgentWindow, SessionExpiredSurface,
- // and Toaster. The bb.vue-notification listener that routes pushNotification
- // into the React renderer is registered by the `./react/lib/toast`
- // side-effect import at the top of this file, so toasts queued before this
- // mount completes still render once it does.
- void (async () => {
- const { mountReactApp } = await import("./react/app/mount");
- await mountReactApp("#react-app");
- })();
+ const { mountReactRouterApp } = await import("./react/app/mountApp");
+ await mountReactRouterApp("#app");
})();
diff --git a/frontend/src/plugins/ai/logic/getChatByTab.ts b/frontend/src/plugins/ai/logic/getChatByTab.ts
deleted file mode 100644
index b8a7b8f2dd..0000000000
--- a/frontend/src/plugins/ai/logic/getChatByTab.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { last } from "lodash-es";
-import { computed, ref, watch } from "vue";
-import type { SQLEditorTab } from "@/types";
-import { useConversationStore } from "../store";
-import type { AIChatInfo, Conversation } from "../types";
-
-const chatsByTab = new Map<string, AIChatInfo>();
-
-const emptyChat: AIChatInfo = {
- list: ref([]),
- ready: ref(false),
- selected: ref(undefined),
-};
-
-const initializeChat = (tab: SQLEditorTab): AIChatInfo => {
- const store = useConversationStore();
- const ready = ref(false);
- store.fetchConversationListByConnection(tab.connection).then(() => {
- ready.value = true;
- });
- const list = computed(() => {
- const { instance, database } = tab.connection;
- return store.conversationList.filter(
- (c) => c.instance === instance && c.database === database
- );
- });
- const selected = ref<Conversation>();
- watch(
- [list, ready, selected],
- ([list, ready]) => {
- if (ready) {
- if (!selected.value) {
- selected.value = last(list);
- }
- }
- },
- { immediate: true }
- );
- return { list, ready, selected };
-};
-
-/**
- * Per-tab AI chat state, keyed by the tab's `(instance, database)`
- * connection. The returned `AIChatInfo` still holds Vue refs because the
- * conversation list is backed by a Pinia store — React consumers bridge
- * those refs (e.g. via `useVueState`). The tab itself is supplied by the
- * caller (sourced from the Zustand tab store) so this module no longer
- * depends on any Vue-reactive view of the current tab.
- */
-export const getChatByTab = (tab: SQLEditorTab | undefined): AIChatInfo => {
- if (!tab) return emptyChat;
- const key = JSON.stringify({
- instance: tab.connection.instance,
- database: tab.connection.database,
- });
- const existed = chatsByTab.get(key);
- if (existed) return existed;
- const chat = initializeChat(tab);
- chatsByTab.set(key, chat);
- return chat;
-};
diff --git a/frontend/src/plugins/ai/logic/index.ts b/frontend/src/plugins/ai/logic/index.ts
index 7f07e01e65..b0b3f6038f 100644
--- a/frontend/src/plugins/ai/logic/index.ts
+++ b/frontend/src/plugins/ai/logic/index.ts
@@ -1,4 +1,2 @@
export * from "./events";
-export * from "./getChatByTab";
-export * from "./useDynamicSuggestions";
export * from "./prompt";
diff --git a/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts b/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts
deleted file mode 100644
index 778ca1fb87..0000000000
--- a/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts
+++ /dev/null
@@ -1,197 +0,0 @@
-import { create as createProto } from "@bufbuild/protobuf";
-import { createContextValues } from "@connectrpc/connect";
-import { head, uniq, values } from "lodash-es";
-import { computed, type MaybeRefOrGetter, reactive, ref, toValue } from "vue";
-import { sqlServiceClientConnect } from "@/connect";
-import { silentContextKey } from "@/connect/context-key";
-import type { Engine } from "@/types/proto-es/v1/common_pb";
-import type { DatabaseMetadata } from "@/types/proto-es/v1/database_service_pb";
-import {
- type AICompletionRequest_Message,
- AICompletionRequest_MessageSchema,
- AICompletionRequestSchema,
-} from "@/types/proto-es/v1/sql_service_pb";
-import { storageKeyAiSuggestions } from "@/utils";
-import { hashCode } from "@/utils/string";
-import * as promptUtils from "./prompt";
-
-export type SuggestionContext = {
- metadata: string; // schema text
- key: string; // a hash key used by storage
- suggestions: string[];
- ready: boolean;
- state: "LOADING" | "IDLE" | "ENDED";
- used: Set<string>;
- current: () => string | undefined;
- consume: () => void;
- fetch: () => Promise<string[]>; // returns empty means reaches the end
- next: () => Promise<string | undefined>; // returns next suggestion or empty (ended)
-};
-
-function saveSuggestionCache(key: string, value: string[]) {
- try {
- localStorage.setItem(storageKeyAiSuggestions(key), JSON.stringify(value));
- } catch {
- // ignore
- }
-}
-
-function loadSuggestionCache(key: string): string[] {
- try {
- const raw = localStorage.getItem(storageKeyAiSuggestions(key));
- return raw ? JSON.parse(raw) : [];
- } catch {
- return [];
- }
-}
-
-const cache = ref(new Map<string, SuggestionContext>());
-const MAX_STORED_SUGGESTIONS = 10;
-
-const keyOf = (metadata: string) => String(hashCode(metadata));
-
-/**
- * Per-(database, engine, schema) cache of LLM-suggested prompt chips.
- *
- * Originally took its inputs via Vue's `useAIContext()` provide/inject.
- * After Stage 22 the AI plugin's components are React, and the React
- * provider doesn't set up a Vue inject chain — so callers pass
- * `databaseMetadata` / `engine` / `schema` directly (or via Vue refs /
- * getters, which makes this helper still usable from Vue surfaces that
- * outlive this migration).
- */
-export const useDynamicSuggestions = (params: {
- databaseMetadata: MaybeRefOrGetter<DatabaseMetadata | undefined>;
- engine: MaybeRefOrGetter<Engine | undefined>;
- schema: MaybeRefOrGetter<string | undefined>;
-}) => {
- const metadata = computed(() => {
- const meta = toValue(params.databaseMetadata);
- const engine = toValue(params.engine);
- const schema = toValue(params.schema);
- if (meta && engine) {
- return promptUtils.databaseMetadataToText(meta, engine, schema);
- }
- return "";
- });
-
- const requestAI = async (messages: AICompletionRequest_Message[]) => {
- await new Promise((resolve) => setTimeout(resolve, 1000));
- try {
- const request = createProto(AICompletionRequestSchema, { messages });
- // Use silent mode to avoid showing error notifications for AI completion failures
- const response = await sqlServiceClientConnect.aICompletion(request, {
- contextValues: createContextValues().set(silentContextKey, true),
- });
- const text =
- head(head(response.candidates)?.content?.parts)?.text?.trim() ?? "";
- const card = JSON.parse(text) as Record<string, string>;
- return values(card ?? {});
- } catch {
- return [];
- }
- };
-
- const createSuggestion = (metadata: string) => {
- const suggestion: SuggestionContext = reactive({
- metadata,
- key: keyOf(metadata),
- suggestions: [],
- index: 0,
- state: "IDLE",
- // Mark as ready without auto-fetching to avoid API calls on tab open.
- // We will trigger the fetch when DynamicSuggestions mounted.
- ready: true,
- used: new Set(),
- current() {
- const { suggestions } = suggestion;
- return head(suggestions);
- },
- consume() {
- const { suggestions, used } = suggestion;
- const sug = suggestion.current();
- if (!sug) return;
- suggestions.shift();
- used.add(sug);
- if (suggestions.length === 0) {
- suggestion.fetch();
- }
- },
- async fetch() {
- const { state, used, suggestions, key } = suggestion;
- if (state === "ENDED") return [];
-
- const { command, prompt } = promptUtils.dynamicSuggestions(
- metadata,
- new Set([...used.values(), ...suggestions])
- );
- const messages: AICompletionRequest_Message[] = [
- createProto(AICompletionRequest_MessageSchema, {
- role: "system",
- content: command,
- }),
- createProto(AICompletionRequest_MessageSchema, {
- role: "user",
- content: prompt,
- }),
- ];
- console.debug("[DynamicSuggestions]");
- console.debug(command);
- console.debug(prompt);
-
- suggestion.state = "LOADING";
- const response = await requestAI(messages);
- console.debug("[DynamicSuggestions] response", response);
- const more = uniq(
- response.filter((sug) => {
- if (used.has(sug)) return false;
- if (suggestions.includes(sug)) return false;
- return true;
- })
- );
- suggestions.push(...more);
- suggestion.state = more.length === 0 ? "ENDED" : "IDLE";
-
- const combined = uniq([...suggestions, ...used.values()]).slice(
- 0,
- MAX_STORED_SUGGESTIONS
- );
- if (combined.length > 0) {
- saveSuggestionCache(key, combined);
- }
-
- return more;
- },
- async next() {
- const originalState = suggestion.state;
- if (originalState === "ENDED") return;
- const curr = suggestion.current();
- if (curr) {
- suggestion.used.add(curr);
- }
- if (suggestion.suggestions.length === 1) {
- await suggestion.fetch();
- }
- suggestion.suggestions.shift();
- return suggestion.current();
- },
- });
- const stored = loadSuggestionCache(suggestion.key);
- if (stored && stored.length > 0) {
- suggestion.suggestions = stored;
- }
- cache.value.set(metadata, suggestion);
- return suggestion;
- };
-
- const getOrCreateSuggestion = (metadata: string) => {
- const cached = cache.value.get(metadata);
- if (cached) return cached;
- return createSuggestion(metadata);
- };
-
- return computed(() => {
- if (!metadata.value) return undefined;
- return getOrCreateSuggestion(metadata.value);
- });
-};
diff --git a/frontend/src/plugins/ai/react/DynamicSuggestions.tsx b/frontend/src/plugins/ai/react/DynamicSuggestions.tsx
index a38a940df6..ca2c668959 100644
--- a/frontend/src/plugins/ai/react/DynamicSuggestions.tsx
+++ b/frontend/src/plugins/ai/react/DynamicSuggestions.tsx
@@ -3,10 +3,9 @@ import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/react/components/ui/button";
import { useCurrentUser } from "@/react/hooks/useAppState";
-import { useVueState } from "@/react/hooks/useVueState";
import { storageKeySqlEditorAiSuggestion } from "@/utils";
-import { useDynamicSuggestions } from "../logic";
import { useAIContext } from "./context";
+import { useDynamicSuggestions } from "./useDynamicSuggestions";
type Props = {
readonly onEnter: (query: string) => void;
@@ -28,34 +27,25 @@ function loadShowSuggestion(key: string): boolean {
* / dismiss controls. Clicking the pill emits the suggestion to the
* parent (`ChatPanel`) which submits it via `requestAI(query)`.
*
- * `useDynamicSuggestions()` returns a Vue `ComputedRef<SuggestionContext>`
- * where the inner object is a Pinia/Vue `reactive(...)` — we read each
- * field via its own `useVueState` getter so React only re-renders when
- * the specific field changes.
+ * `useDynamicSuggestions()` is a React hook backed by a module store
+ * (subscribed via `useSyncExternalStore`); it returns the current
+ * `SuggestionContext` (or undefined) and re-renders when the suggestions
+ * or fetch state for the active metadata change.
*/
export function DynamicSuggestions({ onEnter }: Props) {
const { t } = useTranslation();
const { databaseMetadata, engine, schema } = useAIContext();
- // `useDynamicSuggestions` returns a Vue `ComputedRef<SuggestionContext>`
- // whose `metadata` getter reads our params. We pass them via
- // `MaybeRefOrGetter` getters so Vue's reactivity follows React's
- // useVueState-bridged values (the React `databaseMetadata` etc. are
- // already plain values that re-read on each call).
- const suggestionsRef = useDynamicSuggestions({
- databaseMetadata: () => databaseMetadata,
- engine: () => engine,
- schema: () => schema,
+ const suggestion = useDynamicSuggestions({
+ databaseMetadata,
+ engine,
+ schema,
});
const currentUserEmail = useCurrentUser().email;
- const ready = useVueState(() => suggestionsRef.value?.ready ?? false);
- const state = useVueState<"LOADING" | "IDLE" | "ENDED">(
- () => suggestionsRef.value?.state ?? "IDLE"
- );
- const suggestionsCount = useVueState(
- () => suggestionsRef.value?.suggestions.length ?? 0
- );
- const current = useVueState(() => suggestionsRef.value?.current());
+ const ready = suggestion?.ready ?? false;
+ const state = suggestion?.state ?? "IDLE";
+ const suggestionsCount = suggestion?.suggestions.length ?? 0;
+ const current = suggestion?.current();
// Kick off the initial fetch when the component mounts and the cache
// is empty — matches the Vue `onMounted` block. `useDynamicSuggestions`
@@ -63,7 +53,6 @@ export function DynamicSuggestions({ onEnter }: Props) {
// every render — gate by `state` so we don't pile concurrent `fetch()`s
// on top of an in-flight one (each fetch is a paid AI completion).
useEffect(() => {
- const suggestion = suggestionsRef.value;
if (
suggestion &&
suggestion.suggestions.length === 0 &&
@@ -71,7 +60,7 @@ export function DynamicSuggestions({ onEnter }: Props) {
) {
void suggestion.fetch();
}
- }, [suggestionsRef, state]);
+ }, [suggestion, state]);
// Per-user dismissable flag persisted to localStorage. Defaults to
// visible. Same storage key the Vue version used (`useDynamicLocalStorage`
@@ -109,7 +98,6 @@ export function DynamicSuggestions({ onEnter }: Props) {
if (!show) return null;
const handleConsume = () => {
- const suggestion = suggestionsRef.value;
if (!suggestion) return;
const curr = suggestion.current();
if (!curr) return;
@@ -118,7 +106,7 @@ export function DynamicSuggestions({ onEnter }: Props) {
};
const handleRefresh = () => {
- suggestionsRef.value?.consume();
+ suggestion?.consume();
};
return (
diff --git a/frontend/src/plugins/ai/react/context.tsx b/frontend/src/plugins/ai/react/context.tsx
index 009acba1c4..e4da4499ac 100644
--- a/frontend/src/plugins/ai/react/context.tsx
+++ b/frontend/src/plugins/ai/react/context.tsx
@@ -1,4 +1,5 @@
import { create as createProto } from "@bufbuild/protobuf";
+import { last } from "lodash-es";
import type { ReactNode } from "react";
import {
createContext,
@@ -11,7 +12,6 @@ import {
} from "react";
import { useAppDatabaseMetadata } from "@/react/hooks/useAppDatabaseMetadata";
import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";
-import { useVueState } from "@/react/hooks/useVueState";
import { useAppStore } from "@/react/stores/app";
import {
getCurrentSQLEditorTab,
@@ -24,9 +24,8 @@ import {
AISettingSchema,
Setting_SettingName,
} from "@/types/proto-es/v1/setting_service_pb";
-import { wrapRefAsPromise } from "@/utils";
-import { aiContextEvents, getChatByTab } from "../logic";
-import { useConversationStore } from "../store";
+import { aiContextEvents } from "../logic";
+import { conversationListByConnection, useConversationStore } from "../store";
import type { AIContextEvents, Conversation } from "../types";
/**
@@ -93,7 +92,7 @@ export function useAIContext(): ReactAIContext {
const EMPTY_AI_SETTING: AISetting = createProto(AISettingSchema, {});
export function AIContextProvider({ children }: { children: ReactNode }) {
- // ---- Vue-side state bridged via useVueState ----------------------------
+ // ---- AI setting --------------------------------------------------------
// The original Vue ProvideAIContext fetched the AI setting on mount.
// Mirror that here. `getOrFetchSettingByName` is idempotent; firing it
@@ -133,32 +132,55 @@ export function AIContextProvider({ children }: { children: ReactNode }) {
// ---- Per-tab chat info -------------------------------------------------
//
- // `getChatByTab(tab)` returns an `AIChatInfo` whose inner `list`,
- // `ready`, and `selected` are Vue refs (the conversation list is
- // backed by a Pinia store). We select the tab from Zustand, memoize
- // the per-tab chat, and bridge each inner ref via its own
- // `useVueState` getter — subscribing at the right dep granularity
- // (chat list mutations don't churn `ready`, and so on). `deps:
- // [chatInfo]` re-subscribes each watch when the tab's chat is
- // swapped, since the swap arrives through Zustand rather than Vue.
- const chatInfo = useMemo(() => getChatByTab(currentTab), [currentTab]);
-
- const chatList = useVueState<Conversation[]>(() => chatInfo.list.value, {
- deep: true,
- deps: [chatInfo],
- });
- const chatReady = useVueState<boolean>(() => chatInfo.ready.value, {
- deps: [chatInfo],
- });
- const chatSelected = useVueState<Conversation | undefined>(
- () => chatInfo.selected.value,
- { deps: [chatInfo] }
- );
+ // Conversations live in the Zustand `useConversationStore`. We subscribe to
+ // the conversation map + per-connection ready flags and derive the current
+ // tab's chat (list / ready / selected) with plain React state — no Vue refs.
+ const tabInstance = currentTab?.connection.instance;
+ const tabDatabase = currentTab?.connection.database;
+ const connKey =
+ tabInstance && tabDatabase ? `${tabInstance}/${tabDatabase}` : "";
+
+ const conversationsById = useConversationStore((s) => s.conversationsById);
+ const readyByConnection = useConversationStore((s) => s.readyByConnection);
+
+ // Fetch the tab's conversations on connection change; the store sets the
+ // ready flag and merges results.
+ useEffect(() => {
+ if (!tabInstance || !tabDatabase) return;
+ void useConversationStore.getState().fetchConversationListByConnection({
+ instance: tabInstance,
+ database: tabDatabase,
+ } as never);
+ }, [tabInstance, tabDatabase]);
+
+ const chatList = useMemo<Conversation[]>(() => {
+ if (!tabInstance || !tabDatabase) return [];
+ return Object.values(conversationsById)
+ .filter((c) => c.instance === tabInstance && c.database === tabDatabase)
+ .sort((a, b) => a.created_ts - b.created_ts);
+ }, [conversationsById, tabInstance, tabDatabase]);
+
+ const chatReady = connKey ? !!readyByConnection[connKey] : false;
+
+ // Explicit per-connection selection; falls back to the last conversation
+ // once the connection is ready (mirrors the Vue `watch` default).
+ const [selectedIdByConn, setSelectedIdByConn] = useState<
+ Record<string, string | undefined>
+ >({});
+ const selectedId = connKey ? selectedIdByConn[connKey] : undefined;
+ const chatSelected = useMemo<Conversation | undefined>(() => {
+ const explicit = selectedId
+ ? chatList.find((c) => c.id === selectedId)
+ : undefined;
+ if (explicit) return explicit;
+ return chatReady ? last(chatList) : undefined;
+ }, [selectedId, chatList, chatReady]);
const setChatSelected = useCallback(
(next: Conversation | undefined) => {
- chatInfo.selected.value = next;
+ if (!connKey) return;
+ setSelectedIdByConn((prev) => ({ ...prev, [connKey]: next?.id }));
},
- [chatInfo]
+ [connKey]
);
const chat = useMemo<ReactAIChatInfo>(
() => ({
@@ -170,11 +192,9 @@ export function AIContextProvider({ children }: { children: ReactNode }) {
[chatList, chatReady, chatSelected, setChatSelected]
);
- // Live handle to the current tab's chat for the event listeners
- // below — they fire outside React's render and must read the latest
- // refs without re-subscribing on every tab switch.
- const chatInfoRef = useRef(chatInfo);
- chatInfoRef.current = chatInfo;
+ // Latest selection map for the event listeners (which fire outside render).
+ const selectedIdByConnRef = useRef(selectedIdByConn);
+ selectedIdByConnRef.current = selectedIdByConn;
// ---- React-side state --------------------------------------------------
@@ -191,38 +211,46 @@ export function AIContextProvider({ children }: { children: ReactNode }) {
// ---- Event listeners (mirror ProvideAIContext.vue) ---------------------
- const conversationStore = useConversationStore();
-
- // We need the latest chat refs + tab from inside the listeners.
- // `chatInfoRef` always points at the current tab's chat, and
- // `getCurrentSQLEditorTab()` reads the live Zustand tab at fire time.
+ // The listeners fire outside render. They read the live tab via
+ // `getCurrentSQLEditorTab()`, await the store's per-connection fetch (so a
+ // brand-new tab doesn't create a duplicate empty conversation before its
+ // existing ones hydrate), then read/select through the store +
+ // `selectedIdByConnRef`.
useEffect(() => {
+ const selectFor = (conn: { instance: string; database: string }) => {
+ const ck = `${conn.instance}/${conn.database}`;
+ const list = conversationListByConnection(
+ useConversationStore.getState(),
+ conn
+ );
+ const selId = selectedIdByConnRef.current[ck];
+ const explicit = selId ? list.find((c) => c.id === selId) : undefined;
+ return { ck, list, selected: explicit ?? last(list) };
+ };
+
const offNewConversation = events.on(
"new-conversation",
async ({ input }) => {
const tab = getCurrentSQLEditorTab();
if (!tab) return;
- // Wait until the per-tab chat fetch has resolved before deciding
- // whether to reuse or create. Without this guard a brand-new tab
- // sees `selected === undefined` and creates a duplicate empty
- // conversation when one would have hydrated a beat later.
- await wrapRefAsPromise(chatInfoRef.current.ready, /* expected */ true);
+ const conn = tab.connection;
+ await useConversationStore
+ .getState()
+ .fetchConversationListByConnection(conn);
setShowHistoryDialog(false);
- const sel = chatInfoRef.current.selected.value;
- if (!sel || sel.messageList.length !== 0) {
+ const { ck, selected } = selectFor(conn);
+ if (!selected || selected.messageList.length !== 0) {
// Reuse if the current chat is empty, otherwise create a fresh one.
- const c = await conversationStore.createConversation({
- name: "",
- ...tab.connection,
- });
- chatInfoRef.current.selected.value = c;
+ const c = await useConversationStore
+ .getState()
+ .createConversation({ name: "", ...conn });
+ setSelectedIdByConn((prev) => ({ ...prev, [ck]: c.id }));
}
if (input) {
// rAF mirrors the Vue version — gives `PromptInput`'s
// pending-pre-input effect a frame to land after the conversation
- // creation settles. Without it the seed text can be dropped if
- // the effect fires before `selected` updates.
+ // creation settles.
requestAnimationFrame(() => {
setPendingPreInput(input);
});
@@ -233,14 +261,19 @@ export function AIContextProvider({ children }: { children: ReactNode }) {
const offSendChat = events.on("send-chat", async ({ content, newChat }) => {
const tab = getCurrentSQLEditorTab();
if (!tab) return;
- await wrapRefAsPromise(chatInfoRef.current.ready, /* expected */ true);
+ const conn = tab.connection;
+ await useConversationStore
+ .getState()
+ .fetchConversationListByConnection(conn);
if (newChat) {
setShowHistoryDialog(false);
- const c = await conversationStore.createConversation({
- name: "",
- ...tab.connection,
- });
- chatInfoRef.current.selected.value = c;
+ const c = await useConversationStore
+ .getState()
+ .createConversation({ name: "", ...conn });
+ setSelectedIdByConn((prev) => ({
+ ...prev,
+ [`${conn.instance}/${conn.database}`]: c.id,
+ }));
}
requestAnimationFrame(() => {
setPendingSendChat({ content });
@@ -251,10 +284,9 @@ export function AIContextProvider({ children }: { children: ReactNode }) {
offNewConversation();
offSendChat();
};
- // `events` and `conversationStore` are stable singletons;
- // `chatInfoRef` / `getCurrentSQLEditorTab` read the latest values
- // at fire time — no need to re-subscribe on tab change.
- }, [events, conversationStore]);
+ // `events` is a stable singleton; `getCurrentSQLEditorTab` /
+ // `selectedIdByConnRef` / the store read the latest values at fire time.
+ }, [events]);
// ---- Memoized value bundle --------------------------------------------
diff --git a/frontend/src/plugins/ai/react/useDynamicSuggestions.ts b/frontend/src/plugins/ai/react/useDynamicSuggestions.ts
new file mode 100644
index 0000000000..9bf7ae70bd
--- /dev/null
+++ b/frontend/src/plugins/ai/react/useDynamicSuggestions.ts
@@ -0,0 +1,223 @@
+import { create as createProto } from "@bufbuild/protobuf";
+import { createContextValues } from "@connectrpc/connect";
+import { head, uniq, values } from "lodash-es";
+import { useMemo, useSyncExternalStore } from "react";
+import { sqlServiceClientConnect } from "@/connect";
+import { silentContextKey } from "@/connect/context-key";
+import type { Engine } from "@/types/proto-es/v1/common_pb";
+import type { DatabaseMetadata } from "@/types/proto-es/v1/database_service_pb";
+import {
+ type AICompletionRequest_Message,
+ AICompletionRequest_MessageSchema,
+ AICompletionRequestSchema,
+} from "@/types/proto-es/v1/sql_service_pb";
+import { storageKeyAiSuggestions } from "@/utils";
+import { hashCode } from "@/utils/string";
+import * as promptUtils from "../logic/prompt";
+
+export type SuggestionState = "LOADING" | "IDLE" | "ENDED";
+
+export type SuggestionContext = {
+ metadata: string;
+ key: string;
+ suggestions: string[];
+ ready: boolean;
+ state: SuggestionState;
+ current: () => string | undefined;
+ consume: () => void;
+ fetch: () => Promise<string[]>;
+};
+
+const MAX_STORED_SUGGESTIONS = 10;
+
+function saveSuggestionCache(key: string, value: string[]) {
+ try {
+ localStorage.setItem(storageKeyAiSuggestions(key), JSON.stringify(value));
+ } catch {
+ // ignore
+ }
+}
+
+function loadSuggestionCache(key: string): string[] {
+ try {
+ const raw = localStorage.getItem(storageKeyAiSuggestions(key));
+ return raw ? JSON.parse(raw) : [];
+ } catch {
+ return [];
+ }
+}
+
+const keyOf = (metadata: string) => String(hashCode(metadata));
+
+// ---------------------------------------------------------------------------
+// Framework-agnostic module store (replaces the Vue `reactive` cache). Entries
+// are replaced IMMUTABLY on every mutation so React's `useSyncExternalStore`
+// snapshot comparison detects the change.
+// ---------------------------------------------------------------------------
+type Entry = {
+ metadata: string;
+ key: string;
+ suggestions: string[];
+ used: Set<string>;
+ state: SuggestionState;
+};
+
+const entries = new Map<string, Entry>();
+const listeners = new Set<() => void>();
+
+function emit() {
+ for (const listener of listeners) listener();
+}
+
+function ensureEntry(metadata: string): Entry {
+ const existing = entries.get(metadata);
+ if (existing) return existing;
+ const stored = loadSuggestionCache(keyOf(metadata));
+ const entry: Entry = {
+ metadata,
+ key: keyOf(metadata),
+ suggestions: stored.length > 0 ? stored : [],
+ used: new Set(),
+ state: "IDLE",
+ };
+ entries.set(metadata, entry);
+ return entry;
+}
+
+function patchEntry(metadata: string, patch: Partial<Entry>) {
+ const current = entries.get(metadata);
+ if (!current) return;
+ entries.set(metadata, { ...current, ...patch });
+ emit();
+}
+
+async function requestAI(messages: AICompletionRequest_Message[]) {
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ try {
+ const request = createProto(AICompletionRequestSchema, { messages });
+ // Silent mode avoids error notifications for AI completion failures.
+ const response = await sqlServiceClientConnect.aICompletion(request, {
+ contextValues: createContextValues().set(silentContextKey, true),
+ });
+ const text =
+ head(head(response.candidates)?.content?.parts)?.text?.trim() ?? "";
+ const card = JSON.parse(text) as Record<string, string>;
+ return values(card ?? {});
+ } catch {
+ return [];
+ }
+}
+
+async function fetchSuggestions(metadata: string): Promise<string[]> {
+ const entry = entries.get(metadata);
+ if (!entry || entry.state === "ENDED") return [];
+
+ const { command, prompt } = promptUtils.dynamicSuggestions(
+ metadata,
+ new Set([...entry.used.values(), ...entry.suggestions])
+ );
+ const messages: AICompletionRequest_Message[] = [
+ createProto(AICompletionRequest_MessageSchema, {
+ role: "system",
+ content: command,
+ }),
+ createProto(AICompletionRequest_MessageSchema, {
+ role: "user",
+ content: prompt,
+ }),
+ ];
+
+ patchEntry(metadata, { state: "LOADING" });
+
+ const response = await requestAI(messages);
+ const current = entries.get(metadata);
+ if (!current) return [];
+ const more = uniq(
+ response.filter(
+ (sug) => !current.used.has(sug) && !current.suggestions.includes(sug)
+ )
+ );
+ const suggestions = [...current.suggestions, ...more];
+ patchEntry(metadata, {
+ suggestions,
+ state: more.length === 0 ? "ENDED" : "IDLE",
+ });
+
+ const combined = uniq([...suggestions, ...current.used.values()]).slice(
+ 0,
+ MAX_STORED_SUGGESTIONS
+ );
+ if (combined.length > 0) {
+ saveSuggestionCache(current.key, combined);
+ }
+ return more;
+}
+
+function consumeSuggestion(metadata: string) {
+ const entry = entries.get(metadata);
+ if (!entry) return;
+ const sug = head(entry.suggestions);
+ if (!sug) return;
+ const suggestions = entry.suggestions.slice(1);
+ const used = new Set(entry.used);
+ used.add(sug);
+ patchEntry(metadata, { suggestions, used });
+ if (suggestions.length === 0) {
+ void fetchSuggestions(metadata);
+ }
+}
+
+const subscribe = (onChange: () => void) => {
+ listeners.add(onChange);
+ return () => {
+ listeners.delete(onChange);
+ };
+};
+
+/**
+ * React port of the former Vue `useDynamicSuggestions` composable.
+ *
+ * Per-(database, engine, schema) cache of LLM-suggested prompt chips. The
+ * suggestion state lives in a module store updated immutably; this hook
+ * subscribes via `useSyncExternalStore` so the consumer re-renders when the
+ * current metadata's suggestions/state change. Returns `undefined` until a
+ * database metadata + engine are available.
+ */
+export const useDynamicSuggestions = (params: {
+ databaseMetadata: DatabaseMetadata | undefined;
+ engine: Engine | undefined;
+ schema: string | undefined;
+}): SuggestionContext | undefined => {
+ const { databaseMetadata, engine, schema } = params;
+ const metadata = useMemo(() => {
+ if (databaseMetadata && engine) {
+ return promptUtils.databaseMetadataToText(
+ databaseMetadata,
+ engine,
+ schema
+ );
+ }
+ return "";
+ }, [databaseMetadata, engine, schema]);
+
+ // Lazily create the entry (idempotent, keyed by metadata) before reading the
+ // snapshot, so `getSnapshot` stays pure and returns a stable reference.
+ if (metadata) ensureEntry(metadata);
+ const snapshot = useSyncExternalStore(subscribe, () =>
+ metadata ? entries.get(metadata) : undefined
+ );
+
+ return useMemo<SuggestionContext | undefined>(() => {
+ if (!metadata || !snapshot) return undefined;
+ return {
+ metadata: snapshot.metadata,
+ key: snapshot.key,
+ suggestions: snapshot.suggestions,
+ ready: true,
+ state: snapshot.state,
+ current: () => head(snapshot.suggestions),
+ consume: () => consumeSuggestion(metadata),
+ fetch: () => fetchSuggestions(metadata),
+ };
+ }, [metadata, snapshot]);
+};
diff --git a/frontend/src/plugins/ai/store/conversation.ts b/frontend/src/plugins/ai/store/conversation.ts
index 73d41315d8..6b84377d02 100644
--- a/frontend/src/plugins/ai/store/conversation.ts
+++ b/frontend/src/plugins/ai/store/conversation.ts
@@ -1,10 +1,9 @@
import { groupBy, omit } from "lodash-es";
-import { defineStore } from "pinia";
import PouchDB from "pouchdb";
import PouchDBFind from "pouchdb-find";
import { v1 as uuidv1 } from "uuid";
-import { computed, reactive, ref, unref, watchEffect } from "vue";
-import type { MaybeRef, SQLEditorConnection } from "@/types";
+import { create } from "zustand";
+import type { SQLEditorConnection } from "@/types";
import type { Conversation, Message } from "../types";
type RowStatus = "NORMAL" | "ARCHIVED";
@@ -28,114 +27,146 @@ type EntityCreate<T> = Omit<T, "_id" | "created_ts" | "row_status">;
PouchDB.plugin(PouchDBFind);
-const convertConversationToEntity = (conversation: Conversation) => {
- const c: ConversationEntity = {
- ...omit(conversation, "id", "messageList"),
- _id: conversation.id,
- row_status: "NORMAL",
- };
- return c;
+const convertConversationToEntity = (
+ conversation: Conversation
+): ConversationEntity => ({
+ ...omit(conversation, "id", "messageList"),
+ _id: conversation.id,
+ row_status: "NORMAL",
+});
+
+const convertMessageToEntity = (message: Message): MessageEntity => ({
+ ...omit(message, "id", "conversation"),
+ _id: message.id,
+ row_status: "NORMAL",
+ conversation_id: message.conversation.id,
+});
+
+const FK_MESSAGE_CONVERSATION_ID = "fk_message_conversation_id";
+
+const conversations = new PouchDB<ConversationEntity>(
+ "bb.plugin.ai.conversations"
+);
+const messages = new PouchDB<MessageEntity>("bb.plugin.ai.messages");
+const ready: Promise<unknown>[] = [];
+ready.push(
+ messages.createIndex({
+ index: { name: FK_MESSAGE_CONVERSATION_ID, fields: ["conversation_id"] },
+ })
+);
+
+const connectionKey = (conn: { instance: string; database: string }) =>
+ `${conn.instance}/${conn.database}`;
+
+type ConversationState = {
+ conversationsById: Record<string, Conversation>;
+ readyByConnection: Record<string, boolean>;
+ fetchConversationListByConnection: (
+ conn: SQLEditorConnection
+ ) => Promise<Conversation[]>;
+ createConversation: (
+ conversationCreate: EntityCreate<ConversationEntity>
+ ) => Promise<Conversation>;
+ updateConversation: (conversation: Conversation) => Promise<Conversation>;
+ deleteConversation: (id: string) => Promise<void>;
+ createMessage: (
+ messageCreate: EntityCreate<MessageEntity>
+ ) => Promise<Message>;
+ updateMessage: (message: Message) => Promise<Message>;
+ reset: () => Promise<void>;
};
-const convertMessageToEntity = (message: Message) => {
- const m: MessageEntity = {
- ...omit(message, "id", "conversation"),
- _id: message.id,
- row_status: "NORMAL",
- conversation_id: message.conversation.id,
- };
- return m;
+// Build a plain Conversation (with its message back-refs) from entities.
+const buildConversation = (
+ c: ConversationEntity,
+ messageEntities: MessageEntity[]
+): Conversation => {
+ const conversation: Conversation = {
+ ...omit(c, "_id", "_rev", "row_status"),
+ id: c._id,
+ messageList: [],
+ } as Conversation;
+ conversation.messageList = messageEntities
+ .map<Message>(
+ (m) =>
+ ({
+ ...omit(m, "_id", "_rev", "row_status", "conversation_id"),
+ id: m._id,
+ conversation,
+ }) as Message
+ )
+ .sort((a, b) => a.created_ts - b.created_ts);
+ return conversation;
};
-const useLocalCache = () => {
- const conversationById = reactive(new Map<string, Conversation>());
- const messageById = reactive(new Map<string, Message>());
+// Immutably replace a conversation in the map.
+const withConversation = (
+ byId: Record<string, Conversation>,
+ conversation: Conversation
+): Record<string, Conversation> => ({
+ ...byId,
+ [conversation.id]: conversation,
+});
- const convertConversation = (
- c: ConversationEntity,
- messageList: Message[] = []
- ): Conversation => {
- const existed = conversationById.get(c._id);
- if (existed) {
- Object.assign(existed, {
- ...c,
- messageList,
- });
- return existed;
+export const useConversationStore = create<ConversationState>((set, get) => {
+ const deleteConversation = async (id: string): Promise<void> => {
+ const conversation = get().conversationsById[id];
+ if (!conversation) return;
+ if (conversation.messageList.length > 0) {
+ await messages.bulkDocs(
+ conversation.messageList.map((message) => ({
+ ...convertMessageToEntity(message),
+ row_status: "ARCHIVED" as const,
+ }))
+ );
}
- const conversation = reactive({
- ...c,
- id: c._id,
- messageList,
+ await conversations.put(
+ { ...convertConversationToEntity(conversation), row_status: "ARCHIVED" },
+ { force: true }
+ );
+ set((state) => {
+ const next = { ...state.conversationsById };
+ delete next[id];
+ return { conversationsById: next };
});
- conversationById.set(conversation.id, conversation);
- return conversation;
};
- const convertMessage = (
- m: MessageEntity,
- conversation: Conversation
- ): Message => {
- const existed = messageById.get(m._id);
- if (existed) {
- Object.assign(existed, {
- ...m,
- conversation,
- });
+ const updateMessage = async (message: Message): Promise<Message> => {
+ await messages.put(convertMessageToEntity(message), { force: true });
+ const conversation = get().conversationsById[message.conversation.id];
+ if (conversation) {
+ const nextConversation: Conversation = {
+ ...conversation,
+ messageList: conversation.messageList.map((m) =>
+ m.id === message.id ? message : m
+ ),
+ };
+ set((state) => ({
+ conversationsById: withConversation(
+ state.conversationsById,
+ nextConversation
+ ),
+ }));
}
- const message = reactive({
- ...m,
- id: m._id,
- conversation,
- });
- messageById.set(message.id, message);
return message;
};
- const getConversationById = (id: string) => {
- return conversationById.get(id)!;
- };
- const getMessageById = (id: string) => {
- return messageById.get(id)!;
- };
-
- return {
- conversationById,
- convertConversation,
- convertMessage,
- getConversationById,
- getMessageById,
+ const fixAbnormalMessages = async (messageList: Message[]) => {
+ const requests = messageList
+ .filter((message) => message.status === "LOADING")
+ .map((message) =>
+ updateMessage({
+ ...message,
+ status: "FAILED",
+ error: "Request timeout",
+ })
+ );
+ await Promise.all(requests);
};
-};
-
-const FK_MESSAGE_CONVERSATION_ID = "fk_message_conversation_id";
-
-export const useConversationStore = defineStore("ai-conversation", () => {
- const conversations = new PouchDB<ConversationEntity>(
- "bb.plugin.ai.conversations"
- );
- const messages = new PouchDB<MessageEntity>("bb.plugin.ai.messages");
- const ready: Promise<unknown>[] = [];
- ready.push(
- messages.createIndex({
- index: { name: FK_MESSAGE_CONVERSATION_ID, fields: ["conversation_id"] },
- })
- );
-
- const {
- conversationById,
- convertConversation,
- convertMessage,
- getConversationById,
- } = useLocalCache();
-
- const conversationList = computed(() => {
- return [...conversationById.values()];
- });
const fetchConversationListByConnection = async (
conn: SQLEditorConnection
- ) => {
+ ): Promise<Conversation[]> => {
const conversationEntityList = (
await conversations.find({
selector: {
@@ -145,51 +176,49 @@ export const useConversationStore = defineStore("ai-conversation", () => {
},
})
).docs;
- const flattenMessageMessageList = (
+ const flattenMessageList = (
await messages.find({
selector: {
row_status: { $eq: "NORMAL" },
- conversation_id: {
- $in: conversationEntityList.map((c) => c._id),
- },
+ conversation_id: { $in: conversationEntityList.map((c) => c._id) },
},
})
).docs;
const groupByConversationId = groupBy(
- flattenMessageMessageList,
+ flattenMessageList,
(m) => m.conversation_id
);
conversationEntityList.sort((a, b) => a.created_ts - b.created_ts);
- const rawConversationList = conversationEntityList.map<Conversation>(
- (c) => {
- const conversation = convertConversation(c);
- const messageEntityList = groupByConversationId[c._id] ?? [];
- conversation.messageList = messageEntityList.map((m) =>
- convertMessage(m, conversation)
- );
- conversation.messageList.sort((a, b) => a.created_ts - b.created_ts);
- return conversation;
- }
+ const rawConversationList = conversationEntityList.map<Conversation>((c) =>
+ buildConversation(c, groupByConversationId[c._id] ?? [])
);
+
await fixAbnormalMessages(
rawConversationList.flatMap((c) => c.messageList)
);
- // cleanup empty conversations
- const emptyConversationList: Conversation[] = [];
- rawConversationList.forEach((conversation) => {
- if (conversation.messageList.length === 0) {
- emptyConversationList.push(conversation);
- }
+
+ const emptyConversationList = rawConversationList.filter(
+ (c) => c.messageList.length === 0
+ );
+
+ set((state) => {
+ const next = { ...state.conversationsById };
+ for (const c of rawConversationList) next[c.id] = c;
+ return {
+ conversationsById: next,
+ readyByConnection: {
+ ...state.readyByConnection,
+ [connectionKey(conn)]: true,
+ },
+ };
});
+
await Promise.all(
- emptyConversationList.map((conversation) =>
- deleteConversation(conversation.id)
- )
- );
- return rawConversationList.filter(
- (conversation) => conversation.messageList.length > 0
+ emptyConversationList.map((c) => deleteConversation(c.id))
);
+
+ return rawConversationList.filter((c) => c.messageList.length > 0);
};
const createConversation = async (
@@ -203,38 +232,36 @@ export const useConversationStore = defineStore("ai-conversation", () => {
};
const response = await conversations.put(c);
c._rev = response.rev;
- return convertConversation(c);
- };
-
- const updateConversation = async (conversation: Conversation) => {
- const c = convertConversationToEntity(conversation);
- await conversations.put(c, { force: true });
- return convertConversation(c, conversation.messageList);
+ const conversation = buildConversation(c, []);
+ set((state) => ({
+ conversationsById: withConversation(
+ state.conversationsById,
+ conversation
+ ),
+ }));
+ return conversation;
};
- const deleteConversation = async (id: string) => {
- const conversation = getConversationById(id);
- if (conversation.messageList.length > 0) {
- await messages.bulkDocs(
- conversation.messageList.map((message) => ({
- ...convertMessageToEntity(message),
- row_status: "ARCHIVED",
- }))
- );
- }
- await conversations.put(
- {
- ...convertConversationToEntity(conversation),
- row_status: "ARCHIVED",
- },
- {
- force: true,
- }
- );
- conversationById.delete(conversation.id);
+ const updateConversation = async (
+ conversation: Conversation
+ ): Promise<Conversation> => {
+ await conversations.put(convertConversationToEntity(conversation), {
+ force: true,
+ });
+ const existing = get().conversationsById[conversation.id];
+ const next: Conversation = {
+ ...conversation,
+ messageList: existing?.messageList ?? conversation.messageList,
+ };
+ set((state) => ({
+ conversationsById: withConversation(state.conversationsById, next),
+ }));
+ return next;
};
- const createMessage = async (messageCreate: EntityCreate<MessageEntity>) => {
+ const createMessage = async (
+ messageCreate: EntityCreate<MessageEntity>
+ ): Promise<Message> => {
const m: MessageEntity = {
_id: uuidv1(),
created_ts: Date.now(),
@@ -243,43 +270,41 @@ export const useConversationStore = defineStore("ai-conversation", () => {
};
const response = await messages.put(m);
m._rev = response.rev;
- const conversation = getConversationById(m.conversation_id);
- const message = convertMessage(m, conversation);
- conversation.messageList.push(message);
+ const conversation = get().conversationsById[m.conversation_id];
+ const message: Message = {
+ ...omit(m, "_id", "_rev", "row_status", "conversation_id"),
+ id: m._id,
+ conversation,
+ } as Message;
+ if (conversation) {
+ const nextConversation: Conversation = {
+ ...conversation,
+ messageList: [...conversation.messageList, message],
+ };
+ message.conversation = nextConversation;
+ set((state) => ({
+ conversationsById: withConversation(
+ state.conversationsById,
+ nextConversation
+ ),
+ }));
+ }
return message;
};
- const updateMessage = async (message: Message) => {
- const m = convertMessageToEntity(message);
- await messages.put(m, {
- force: true,
- });
- return convertMessage(m, message.conversation);
- };
-
- const fixAbnormalMessages = async (messageList: Message[]) => {
- const requests = messageList
- .filter((message) => message.status === "LOADING")
- .map((message) => {
- message.status = "FAILED";
- message.error = "Request timeout";
- return updateMessage(message);
- });
- await Promise.all(requests);
- };
-
const reset = async () => {
try {
await Promise.all(ready);
await Promise.all([conversations.destroy(), messages.destroy()]);
} catch {
- // nothing todo
+ // nothing to do
}
+ set({ conversationsById: {}, readyByConnection: {} });
};
return {
- conversationById,
- conversationList,
+ conversationsById: {},
+ readyByConnection: {},
fetchConversationListByConnection,
createConversation,
updateConversation,
@@ -290,21 +315,17 @@ export const useConversationStore = defineStore("ai-conversation", () => {
};
});
-export const useConversationListByConnection = (
- conn: MaybeRef<SQLEditorConnection>
-) => {
- const store = useConversationStore();
- const ready = ref(false);
- watchEffect(async () => {
- ready.value = false;
- await store.fetchConversationListByConnection(unref(conn));
- ready.value = true;
- });
- const list = computed(() => {
- const { instance, database } = unref(conn);
- return store.conversationList.filter(
- (c) => c.instance === instance && c.database === database
- );
- });
- return { list, ready };
-};
+// Conversations for a given connection, sorted by creation time (mirrors the
+// Vue store's filtered `conversationList`).
+export const conversationListByConnection = (
+ state: ConversationState,
+ conn: { instance: string; database: string }
+): Conversation[] =>
+ Object.values(state.conversationsById)
+ .filter((c) => c.instance === conn.instance && c.database === conn.database)
+ .sort((a, b) => a.created_ts - b.created_ts);
+
+export const isConnectionReady = (
+ state: ConversationState,
+ conn: { instance: string; database: string }
+): boolean => !!state.readyByConnection[connectionKey(conn)];
diff --git a/frontend/src/plugins/ai/store/index.ts b/frontend/src/plugins/ai/store/index.ts
index a4409abfcf..3bbec14493 100644
--- a/frontend/src/plugins/ai/store/index.ts
+++ b/frontend/src/plugins/ai/store/index.ts
@@ -1,5 +1 @@
-import { createPinia } from "pinia";
-
-export const pinia = createPinia();
-
export * from "./conversation";
diff --git a/frontend/src/plugins/ai/types/context.ts b/frontend/src/plugins/ai/types/context.ts
index ce4951989a..b4014332fe 100644
--- a/frontend/src/plugins/ai/types/context.ts
+++ b/frontend/src/plugins/ai/types/context.ts
@@ -1,34 +1,11 @@
import type Emittery from "emittery";
-import type { Ref } from "vue";
-import type { Engine } from "@/types/proto-es/v1/common_pb";
-import type { DatabaseMetadata } from "@/types/proto-es/v1/database_service_pb";
-import type { AISetting } from "@/types/proto-es/v1/setting_service_pb";
-import type { Conversation } from "./conversation";
+// The React-shaped AI plugin context lives in `react/context.tsx`
+// (`ReactAIContext`). This module now only carries the framework-agnostic
+// event bus type shared between the plugin's logic and React layers.
export type AIContextEvents = Emittery<{
"run-statement": { statement: string };
error: string;
"new-conversation": { input: string };
"send-chat": { content: string; newChat?: boolean };
}>;
-
-export type AIChatInfo = {
- list: Ref<Conversation[]>;
- ready: Ref<boolean>;
- selected: Ref<Conversation | undefined>;
-};
-
-export type AIContext = {
- aiSetting: Ref<AISetting>;
- engine: Ref<Engine | undefined>;
- databaseMetadata: Ref<DatabaseMetadata | undefined>;
- schema: Ref<string | undefined>;
- showHistoryDialog: Ref<boolean>;
-
- chat: Ref<AIChatInfo>;
- pendingSendChat: Ref<{ content: string } | undefined>;
- pendingPreInput: Ref<string | undefined>;
-
- // Events
- events: AIContextEvents;
-};
diff --git a/frontend/src/plugins/i18n.ts b/frontend/src/plugins/i18n.ts
index 12faa2e5c7..1406e1a0a8 100644
--- a/frontend/src/plugins/i18n.ts
+++ b/frontend/src/plugins/i18n.ts
@@ -1,96 +1,44 @@
-import { useLocalStorage } from "@vueuse/core";
-import type { WritableComputedRef } from "vue";
-import { type Composer, createI18n } from "vue-i18n";
-import { STORAGE_KEY_LANGUAGE } from "@/utils/storage-keys";
+// The app's i18n is react-i18next (`@/react/i18n`). This module is a thin
+// compatibility layer over that single instance for non-React callers — shared
+// `.ts` modules that translate outside React components via `t` / `te` /
+// `locale`. React components use `useTranslation()` directly. vue-i18n is gone.
+import i18n from "@/react/i18n";
import { mergedLocalMessage } from "./i18n-messages";
-const validLocaleList = ["en-US", "zh-CN", "es-ES", "ja-JP", "vi-VN"];
-
-const normalizeStoredLocale = (stored: string): string => {
- if (validLocaleList.includes(stored)) {
- return stored;
- }
- try {
- const parsed = JSON.parse(stored);
- return typeof parsed === "string" ? parsed : "";
- } catch {
- return "";
- }
-};
-
-const getValidLocale = () => {
- const storage = useLocalStorage<string>(STORAGE_KEY_LANGUAGE, "");
-
- const params = new URL(globalThis.location.href).searchParams;
- let locale = params.get("locale") || "";
- if (validLocaleList.includes(locale)) {
- storage.value = locale;
- }
-
- locale = normalizeStoredLocale(storage.value || "");
- if (validLocaleList.includes(locale)) {
- return locale;
- }
-
- locale = navigator.language;
- if (locale === "en") {
- // To work with user stored legacy preferences, we switch to en-US
- // here if we got "en" from localStorage
- locale = "en-US";
- }
- if (locale === "ja") {
- locale = "ja-JP";
- }
- if (locale === "es") {
- locale = "es-ES";
- }
- if (locale === "vi") {
- locale = "vi-VN";
- }
- if (validLocaleList.includes(locale)) {
- return locale;
- }
-
- return "en-US";
-};
-
-const dtfOptions = {
- full: {
- month: "short" as const,
- day: "numeric" as const,
- year: "numeric" as const,
- hour: "numeric" as const,
- minute: "2-digit" as const,
- timeZoneName: "short" as const,
+// The shared `.ts` callers reference some legacy keys that aren't in the
+// React locale files (which are scoped to React-component usage). Merge the
+// legacy message set into the same react-i18next instance AT RUNTIME so those
+// keys resolve, without duplicating them into the React locale files (keeps
+// the React-i18n guard + locale set clean). React-owned keys win on conflict.
+// Guarded so tests that mock `@/react/i18n` with a partial instance don't
+// break at import time (addResourceBundle is always present on the real one).
+if (typeof i18n.addResourceBundle === "function") {
+ for (const [lng, messages] of Object.entries(
+ mergedLocalMessage as Record<string, Record<string, unknown>>
+ )) {
+ i18n.addResourceBundle(
+ lng,
+ "translation",
+ messages,
+ /* deep */ true,
+ /* overwrite */ false
+ );
+ }
+}
+
+export const t = i18n.t.bind(i18n);
+
+export const te = (key: string): boolean => i18n.exists(key);
+
+// Writable locale accessor mirroring the old vue-i18n `WritableComputedRef`
+// shape (`.value` get/set) for non-React callers.
+export const locale = {
+ get value(): string {
+ return i18n.language;
},
- date: {
- month: "short" as const,
- day: "numeric" as const,
- year: "numeric" as const,
- },
- dateShort: {
- month: "short" as const,
- day: "numeric" as const,
+ set value(next: string) {
+ void i18n.changeLanguage(next);
},
};
-const datetimeFormats = Object.fromEntries(
- validLocaleList.map((l) => [l, dtfOptions])
-);
-
-const i18n = createI18n({
- legacy: false,
- locale: getValidLocale(),
- globalInjection: true,
- messages: mergedLocalMessage as Record<string, Record<string, string>>,
- datetimeFormats,
- fallbackLocale: "en-US",
-});
-
-export const t = i18n.global.t as Composer["t"];
-
-export const te = i18n.global.te as Composer["te"];
-
-export const locale = i18n.global.locale as WritableComputedRef<string>;
-
export default i18n;
diff --git a/frontend/src/react/LandingPageMount.vue b/frontend/src/react/LandingPageMount.vue
deleted file mode 100644
index 86d038acba..0000000000
--- a/frontend/src/react/LandingPageMount.vue
+++ /dev/null
@@ -1,7 +0,0 @@
-<template>
- <ReactPageMount page="LandingPage" />
-</template>
-
-<script lang="ts" setup>
-import ReactPageMount from "./ReactPageMount.vue";
-</script>
diff --git a/frontend/src/react/ReactPageMount.vue b/frontend/src/react/ReactPageMount.vue
deleted file mode 100644
index f9ce720850..0000000000
--- a/frontend/src/react/ReactPageMount.vue
+++ /dev/null
@@ -1,107 +0,0 @@
-<template>
- <div ref="container" :class="containerClass" />
-</template>
-
-<script lang="ts" setup>
-defineOptions({ inheritAttrs: false });
-
-import { computed, onMounted, onUnmounted, ref, useAttrs, watch } from "vue";
-import { useI18n } from "vue-i18n";
-
-// `containerClass` defaults to `h-full` so full-height pages (Welcome,
-// HistoryPane, AccessPane, etc.) keep the previous behavior. Callers that
-// mount a natural-height surface (e.g. a toolbar inside a flex-col) should
-// override with something like `w-full` so the wrapper doesn't stretch to
-// fill its flex-column parent.
-const props = withDefaults(
- defineProps<{
- page: string;
- pageProps?: Record<string, unknown>;
- containerClass?: string;
- }>(),
- { containerClass: "h-full" }
-);
-const containerClass = computed(() => props.containerClass);
-
-const attrs = useAttrs();
-const { locale } = useI18n();
-const container = ref<HTMLElement>();
-// biome-ignore lint/suspicious/noExplicitAny: React Root type from dynamic import
-let root: any = null; // eslint-disable-line @typescript-eslint/no-explicit-any
-
-const pageProps = computed(() => {
- const a = attrs as Record<string, unknown>;
- if (props.pageProps || Object.keys(a).length > 0) {
- return {
- ...props.pageProps,
- ...a,
- };
- }
- return undefined;
-});
-
-let currentPage = "";
-let unmounted = false;
-// Serialization queue. `render()` is async and the dynamic imports yield
-// for several event-loop ticks, so without serialization a watcher firing
-// during the initial mount can race the onMounted call. Both pass the
-// `if (!root)` guard, both call `mountReactPage`, and React ends up with
-// two roots on the same container — the second mount silently uses stale
-// props captured by the first call. Symptom: the first click of a Vue
-// → React boolean toggle right after page refresh appears to do nothing
-// because `open=true` from the watcher gets clobbered by the in-flight
-// mount that captured `open=false`.
-let renderQueue: Promise<void> = Promise.resolve();
-
-function render(): Promise<void> {
- const next = renderQueue.then(() => doRender());
- // Catch on the chain we keep, so a rejection from one render doesn't
- // permanently break the queue. The original promise is still returned
- // to callers that may want to await it.
- renderQueue = next.catch(() => undefined);
- return next;
-}
-
-async function doRender() {
- if (unmounted || !container.value) return;
- const [{ mountReactPage, updateReactPage }, i18nModule] = await Promise.all([
- import("./mount"),
- import("./i18n"),
- ]);
- // Re-check after the dynamic imports — Close All / tab-switch can unmount
- // this component while the imports are in flight. Without the guard,
- // `container.value` may be `undefined` by the time we call createRoot,
- // producing "Target container is not a DOM element".
- if (unmounted || !container.value) return;
- if (i18nModule.default.language !== locale.value) {
- await i18nModule.default.changeLanguage(locale.value);
- if (unmounted || !container.value) return;
- }
- // When the page component changes, unmount old root and create a fresh one
- // to avoid stale React state from the previous page.
- if (root && currentPage !== props.page) {
- root.unmount();
- root = null;
- }
- if (!root) {
- root = await mountReactPage(container.value, props.page, pageProps.value);
- if (unmounted) {
- root?.unmount();
- root = null;
- return;
- }
- } else {
- await updateReactPage(root, props.page, pageProps.value);
- }
- currentPage = props.page;
-}
-
-onMounted(() => render());
-watch(locale, () => render());
-watch([() => props.page, pageProps], () => render());
-onUnmounted(() => {
- unmounted = true;
- root?.unmount();
- root = null;
-});
-</script>
diff --git a/frontend/src/react/ReactProjectSidebarMount.vue b/frontend/src/react/ReactProjectSidebarMount.vue
deleted file mode 100644
index 4474d475c3..0000000000
--- a/frontend/src/react/ReactProjectSidebarMount.vue
+++ /dev/null
@@ -1,34 +0,0 @@
-<template>
- <div ref="container" class="h-full" />
-</template>
-
-<script lang="ts" setup>
-defineOptions({ inheritAttrs: false });
-
-import { onMounted, onUnmounted, ref, watch } from "vue";
-import { useI18n } from "vue-i18n";
-
-const container = ref<HTMLElement>();
-// biome-ignore lint/suspicious/noExplicitAny: React Root type from dynamic import
-let root: any = null; // eslint-disable-line @typescript-eslint/no-explicit-any
-const { locale } = useI18n();
-
-async function render() {
- if (!container.value) return;
- const { mountProjectSidebar, updateProjectSidebarLocale } = await import(
- "./mountProjectSidebar"
- );
- if (!root) {
- root = await mountProjectSidebar(container.value, locale.value);
- } else {
- await updateProjectSidebarLocale(root, locale.value);
- }
-}
-
-onMounted(() => render());
-watch(locale, () => render());
-onUnmounted(() => {
- root?.unmount();
- root = null;
-});
-</script>
diff --git a/frontend/src/react/ReactRouteShellBridge.vue b/frontend/src/react/ReactRouteShellBridge.vue
deleted file mode 100644
index bef68d4a71..0000000000
--- a/frontend/src/react/ReactRouteShellBridge.vue
+++ /dev/null
@@ -1,53 +0,0 @@
-<template>
- <ReactPageMount
- :page="page"
- :page-props="{
- ...pageProps,
- routeKey: route.fullPath,
- onReady: handleReady,
- }"
- />
-
- <teleport v-if="targets.content" :to="targets.content">
- <router-view
- v-if="routerViewName"
- :name="routerViewName"
- v-bind="targets.routeProps ?? {}"
- />
- <router-view v-else v-bind="targets.routeProps ?? {}" />
- </teleport>
-
- <teleport v-if="targets.quickstart" :to="targets.quickstart">
- <ReactPageMount page="Quickstart" container-class="w-full" />
- </teleport>
-</template>
-
-<script lang="ts" setup>
-import { computed, shallowRef } from "vue";
-import { useRoute } from "vue-router";
-import { provideBodyLayoutContext } from "@/layouts/common";
-import type { ReactRouteShellTargets } from "@/react/dashboard-shell";
-import ReactPageMount from "@/react/ReactPageMount.vue";
-
-defineProps<{
- page: string;
- pageProps?: Record<string, unknown>;
- routerViewName?: string;
-}>();
-
-const route = useRoute();
-const targets = shallowRef<ReactRouteShellTargets>({
- content: null,
-});
-const mainContainerRef = computed(
- () => targets.value.mainContainer ?? undefined
-);
-
-const handleReady = (nextTargets: ReactRouteShellTargets | null) => {
- targets.value = nextTargets ?? { content: null };
-};
-
-provideBodyLayoutContext({
- mainContainerRef,
-});
-</script>
diff --git a/frontend/src/react/ReactSidebarMount.vue b/frontend/src/react/ReactSidebarMount.vue
deleted file mode 100644
index c98c539523..0000000000
--- a/frontend/src/react/ReactSidebarMount.vue
+++ /dev/null
@@ -1,32 +0,0 @@
-<template>
- <div ref="container" class="h-full" />
-</template>
-
-<script lang="ts" setup>
-defineOptions({ inheritAttrs: false });
-
-import { onMounted, onUnmounted, ref, watch } from "vue";
-import { useI18n } from "vue-i18n";
-
-const container = ref<HTMLElement>();
-// biome-ignore lint/suspicious/noExplicitAny: React Root type from dynamic import
-let root: any = null; // eslint-disable-line @typescript-eslint/no-explicit-any
-const { locale } = useI18n();
-
-async function render() {
- if (!container.value) return;
- const { mountSidebar, updateSidebarLocale } = await import("./mountSidebar");
- if (!root) {
- root = await mountSidebar(container.value, locale.value);
- } else {
- await updateSidebarLocale(root, locale.value);
- }
-}
-
-onMounted(() => render());
-watch(locale, () => render());
-onUnmounted(() => {
- root?.unmount();
- root = null;
-});
-</script>
diff --git a/frontend/src/react/app/AppRoot.tsx b/frontend/src/react/app/AppRoot.tsx
new file mode 100644
index 0000000000..e5411d0e92
--- /dev/null
+++ b/frontend/src/react/app/AppRoot.tsx
@@ -0,0 +1,47 @@
+import {
+ createBrowserRouter,
+ type LoaderFunctionArgs,
+ matchRoutes,
+ RouterProvider,
+} from "react-router-dom";
+import { rootGuard } from "@/react/router/guard";
+import { setAppRouter, setRouteNameIndex } from "@/react/router/navigation";
+import { buildRouteNameIndex, routes } from "@/react/router/routes";
+
+// Register the name→path index so the guard + auth lifecycle can resolve their
+// by-name redirects to paths.
+setRouteNameIndex(buildRouteNameIndex());
+
+// Single root-route loader: runs on every navigation (the root route matches
+// every URL). Resolves the matched leaf route's `handle.name` and delegates to
+// the faithful `beforeEach` port; a returned `redirect()` Response navigates.
+function rootLoader({ request }: LoaderFunctionArgs) {
+ const url = new URL(request.url);
+ const matched = matchRoutes(routes, url.pathname);
+ const name = (matched?.at(-1)?.route.handle as { name?: string } | undefined)
+ ?.name;
+ return rootGuard({ name, url });
+}
+
+// Attach the guard to the root (RootLayout) route.
+routes[0].loader = rootLoader;
+
+// react-router runs `rootLoader` during initial hydration. With partial
+// hydration (the v7 default) and no hydrate fallback, react-router first
+// renders the matched route tree — for "/" that is the element-less
+// `WORKSPACE_ROOT_MODULE` index route — for one tick before the loader's
+// `redirect()` resolves, logging "No HydrateFallback element provided" and
+// "Matched leaf route at location '/' does not have an element". The loader
+// resolves synchronously (it reads the app store and returns a redirect), so a
+// fallback that renders nothing is shown for ~0 frames; defining one satisfies
+// react-router's partial-hydration contract and silences both warnings.
+routes[0].HydrateFallback = () => null;
+
+export const appRouter = createBrowserRouter(routes);
+
+// Let non-component code (the auth slice) navigate through this instance.
+setAppRouter(appRouter);
+
+export function AppRoot() {
+ return <RouterProvider router={appRouter} />;
+}
diff --git a/frontend/src/react/app/AuthGate.tsx b/frontend/src/react/app/AuthGate.tsx
new file mode 100644
index 0000000000..1fa8f4ef23
--- /dev/null
+++ b/frontend/src/react/app/AuthGate.tsx
@@ -0,0 +1,114 @@
+import { Loader2 } from "lucide-react";
+import { type ReactNode, useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { useMatches, useNavigate } from "react-router-dom";
+import { InactiveRemindModal } from "@/react/components/auth/InactiveRemindModal";
+import { isAuthRelatedRoute } from "@/react/router/guard";
+import { WORKSPACE_ROOT_MODULE } from "@/react/router/handles";
+import { resolvePath } from "@/react/router/navigation";
+import { useAppStore } from "@/react/stores/app";
+import { pushNotification } from "@/store";
+import { isDev } from "@/utils";
+
+// Session-validity poll interval (1 min dev, 5 min prod), mirroring the legacy
+// AuthContext.vue.
+const CHECK_AUTHORIZATION_INTERVAL = isDev() ? 60 * 1000 : 60 * 1000 * 5;
+
+// Replaces AuthContext.vue: gates the app render on the authenticated session
+// (loading workspace-scoped data first), polls session validity, redirects on a
+// cross-tab user switch, and mounts the inactivity reminder. Reads session
+// state from the app store (the single source of truth).
+export function AuthGate({ children }: { children: ReactNode }) {
+ const isLoggedIn = useAppStore((s) => s.isLoggedIn());
+ const currentUser = useAppStore((s) => s.currentUser);
+ const currentUserName = useAppStore((s) => s.currentUserName);
+ const unauthenticatedOccurred = useAppStore((s) => s.unauthenticatedOccurred);
+
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const matches = useMatches();
+ const currentRouteName = (
+ matches.at(-1)?.handle as { name?: string } | undefined
+ )?.name;
+ const isAuthRoute = Boolean(
+ currentRouteName && isAuthRelatedRoute(currentRouteName)
+ );
+
+ const [ready, setReady] = useState(false);
+
+ // Load workspace-scoped data once authenticated, then reveal the app.
+ useEffect(() => {
+ const store = useAppStore.getState();
+ if (!isLoggedIn || !currentUser) {
+ setReady(true);
+ return;
+ }
+ let cancelled = false;
+ setReady(false);
+ void Promise.all([
+ store.loadSubscription(),
+ store.fetchWorkspaceIamPolicy(),
+ store.loadWorkspaceList(),
+ store.listRoles(),
+ store.batchGetOrFetchGroups(currentUser.groups),
+ ]).finally(() => {
+ if (!cancelled) setReady(true);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [isLoggedIn, currentUser]);
+
+ // Periodically revalidate the session (skip when logged out / on auth routes).
+ useEffect(() => {
+ const id = setInterval(() => {
+ const store = useAppStore.getState();
+ if (!store.isLoggedIn() || store.unauthenticatedOccurred) return;
+ if (isAuthRoute) return;
+ void store.fetchCurrentUser();
+ }, CHECK_AUTHORIZATION_INTERVAL);
+ return () => clearInterval(id);
+ }, [isAuthRoute]);
+
+ // Cross-tab user switch: when the signed-in user changes, redirect to the
+ // workspace root with a notification (unless it's a self email update).
+ const prevUserName = useRef(currentUserName);
+ useEffect(() => {
+ const prev = prevUserName.current;
+ prevUserName.current = currentUserName;
+ if (!currentUserName || !prev || currentUserName === prev) return;
+ const store = useAppStore.getState();
+ if (store.isSelfEmailUpdate) {
+ store.setIsSelfEmailUpdate(false);
+ return;
+ }
+ navigate(
+ resolvePath(WORKSPACE_ROOT_MODULE, { query: { _r: `${Date.now()}` } })
+ );
+ pushNotification({
+ module: "bytebase",
+ style: "INFO",
+ title: t("auth.login-as-another.title"),
+ description: t("auth.login-as-another.content"),
+ });
+ }, [currentUserName, navigate, t]);
+
+ return (
+ <>
+ {ready ? (
+ children
+ ) : (
+ <div className="flex items-center justify-center h-screen">
+ <Loader2
+ className="size-5 text-accent animate-spin"
+ aria-label="Loading"
+ role="status"
+ />
+ </div>
+ )}
+ {!isAuthRoute && isLoggedIn && !unauthenticatedOccurred && (
+ <InactiveRemindModal />
+ )}
+ </>
+ );
+}
diff --git a/frontend/src/react/app/RootLayout.tsx b/frontend/src/react/app/RootLayout.tsx
new file mode 100644
index 0000000000..77dd2c175c
--- /dev/null
+++ b/frontend/src/react/app/RootLayout.tsx
@@ -0,0 +1,67 @@
+import type { Location } from "react-router-dom";
+import { matchRoutes, Outlet, useBlocker } from "react-router-dom";
+import { AuthGate } from "@/react/app/AuthGate";
+import { SessionExpiredSurfaceGate } from "@/react/app/SessionExpiredSurfaceGate";
+import { Toaster } from "@/react/components/ui/toaster";
+import { Watermark } from "@/react/components/Watermark";
+import { AgentWindow } from "@/react/plugins/agent/components/AgentWindow";
+import type { ReactRoute } from "@/react/router";
+import { buildReactRoute, runBeforeEachGuards } from "@/react/router";
+import { routes } from "@/react/router/routes";
+
+// Translate a react-router Location into the legacy `ReactRoute` snapshot the
+// registered `beforeEach` leave guards expect (they read `to.name` /
+// `to.fullPath`). Route name comes from matching the path against the table.
+function snapshotLocation(location: Location): ReactRoute {
+ const matched = matchRoutes(routes, location.pathname) ?? [];
+ const leaf = matched.at(-1);
+ return buildReactRoute(
+ {
+ pathname: location.pathname,
+ search: location.search,
+ hash: location.hash,
+ },
+ matched.map((m) => ({ handle: m.route.handle })),
+ (leaf?.params ?? {}) as Record<string, string | string[] | undefined>
+ );
+}
+
+// Single blocker reproducing vue-router's global `beforeEach` cancellation:
+// consults every registered leave guard and blocks the navigation if any calls
+// `next(false)`. The guards run `window.confirm` synchronously and remember a
+// pending target themselves, so a blocked navigation simply stays put.
+function LeaveGuardBlocker() {
+ useBlocker(({ currentLocation, nextLocation }) => {
+ if (
+ currentLocation.pathname === nextLocation.pathname &&
+ currentLocation.search === nextLocation.search
+ ) {
+ return false;
+ }
+ return runBeforeEachGuards(
+ snapshotLocation(nextLocation),
+ snapshotLocation(currentLocation)
+ );
+ });
+ return null;
+}
+
+// Root route element for the react-router app shell. Hosts the global overlays
+// that previously lived in `ReactApp.tsx` (Watermark / Toaster / AgentWindow /
+// SessionExpiredSurfaceGate) and wraps the routed tree in `<AuthGate>` so the
+// session lifecycle (load gate, poll, cross-tab switch, inactivity reminder)
+// runs around every page.
+export function RootLayout() {
+ return (
+ <>
+ <Watermark />
+ <Toaster />
+ <AgentWindow />
+ <SessionExpiredSurfaceGate />
+ <LeaveGuardBlocker />
+ <AuthGate>
+ <Outlet />
+ </AuthGate>
+ </>
+ );
+}
diff --git a/frontend/src/react/app/SessionExpiredSurfaceGate.test.tsx b/frontend/src/react/app/SessionExpiredSurfaceGate.test.tsx
index 45bee04d68..000540ca1c 100644
--- a/frontend/src/react/app/SessionExpiredSurfaceGate.test.tsx
+++ b/frontend/src/react/app/SessionExpiredSurfaceGate.test.tsx
@@ -8,34 +8,27 @@ const isLoggedInRef = ref(true);
const fullPathRef = ref("/");
const routeNameRef = ref("workspace.dashboard");
-vi.mock("@/react/hooks/useVueState", () => ({
- // Passthrough — calls getter() synchronously on each render. Does NOT
- // re-render when Vue state changes after mount; set state on the refs
- // above BEFORE rendering in each test.
- useVueState: <T,>(getter: () => T) => getter(),
+vi.mock("@/react/stores/app", () => ({
+ useAppStore: <T,>(selector: (s: unknown) => T) =>
+ selector({
+ isLoggedIn: () => isLoggedInRef.value,
+ unauthenticatedOccurred: unauthenticatedOccurredRef.value,
+ }),
}));
-vi.mock("@/store", () => ({
- useAuthStore: () => ({
- get unauthenticatedOccurred() {
- return unauthenticatedOccurredRef.value;
- },
- get isLoggedIn() {
- return isLoggedInRef.value;
- },
+vi.mock("@/react/router", () => ({
+ useCurrentRoute: () => ({
+ name: routeNameRef.value,
+ fullPath: fullPathRef.value,
+ hash: "",
+ params: {},
+ query: {},
+ requiredPermissions: [],
+ overrideDocumentTitle: false,
+ meta: {},
}),
}));
-vi.mock("@/router", () => ({
- router: {
- currentRoute: {
- get value() {
- return { fullPath: fullPathRef.value, name: routeNameRef.value };
- },
- },
- },
-}));
-
vi.mock("@/utils/auth", () => ({
isAuthRelatedRoute: (name: string) =>
[
diff --git a/frontend/src/react/app/SessionExpiredSurfaceGate.tsx b/frontend/src/react/app/SessionExpiredSurfaceGate.tsx
index 834f3d8130..3475217f4a 100644
--- a/frontend/src/react/app/SessionExpiredSurfaceGate.tsx
+++ b/frontend/src/react/app/SessionExpiredSurfaceGate.tsx
@@ -1,18 +1,14 @@
import { SessionExpiredSurface } from "@/react/components/auth/SessionExpiredSurface";
-import { useVueState } from "@/react/hooks/useVueState";
-import { router } from "@/router";
-import { useAuthStore } from "@/store";
+import { useCurrentRoute } from "@/react/router";
+import { useAppStore } from "@/react/stores/app";
import { isAuthRelatedRoute } from "@/utils/auth";
export function SessionExpiredSurfaceGate() {
- const isAuthRoute = useVueState(() =>
- isAuthRelatedRoute(String(router.currentRoute.value.name ?? ""))
- );
- const isLoggedIn = useVueState(() => useAuthStore().isLoggedIn);
- const unauthenticatedOccurred = useVueState(
- () => useAuthStore().unauthenticatedOccurred
- );
- const currentPath = useVueState(() => router.currentRoute.value.fullPath);
+ const route = useCurrentRoute();
+ const isAuthRoute = isAuthRelatedRoute(String(route.name ?? ""));
+ const isLoggedIn = useAppStore((s) => s.isLoggedIn());
+ const unauthenticatedOccurred = useAppStore((s) => s.unauthenticatedOccurred);
+ const currentPath = route.fullPath;
// Match the guards that previously lived in AuthContext.vue: the
// surface is only shown for an already-signed-in user on a non-auth
// route who just lost their session — otherwise the modal would block
diff --git a/frontend/src/react/app/layouts/BodyLayout.tsx b/frontend/src/react/app/layouts/BodyLayout.tsx
new file mode 100644
index 0000000000..c18cd1836b
--- /dev/null
+++ b/frontend/src/react/app/layouts/BodyLayout.tsx
@@ -0,0 +1,125 @@
+import { useEffect, useState } from "react";
+import { createPortal } from "react-dom";
+import { Outlet, useLocation, useMatches } from "react-router-dom";
+import { DashboardBodyShell } from "@/react/components/DashboardBodyShell";
+import { DashboardSidebar } from "@/react/components/DashboardSidebar";
+import { ProjectSidebar } from "@/react/components/ProjectSidebar";
+import { Quickstart } from "@/react/components/Quickstart";
+import { RoutePermissionGuardShell } from "@/react/components/RoutePermissionGuardShell";
+import type { DashboardShellTargets } from "@/react/dashboard-shell";
+import {
+ PROJECT_V1_ROUTE_DASHBOARD,
+ WORKSPACE_ROOT_MODULE,
+ WORKSPACE_ROUTE_MY_ISSUES,
+} from "@/react/router/handles";
+
+// Ported from `src/layouts/BodyLayout.vue`. Mounts the workspace
+// `DashboardBodyShell` (header + sidebar slot + body slot) and portals the
+// React sidebar, routed body (`<Outlet/>` — the Vue named views collapse to
+// one outlet here, gated by `RoutePermissionGuardShell` on non-project
+// routes), and quickstart into the shell's reported targets. The
+// shell owns the responsive sidebar / mobile drawer; this layout supplies the
+// React `DashboardSidebar` tree directly instead of the Vue ReactSidebarMount.
+// Also ports the agent keyboard shortcut from the Vue layout's lifecycle.
+//
+// NOTE: the Vue layout's periodic "refresh reminder" (actuatorStore
+// .tryToRemindRefresh) is intentionally omitted — it reads Pinia-only actuator
+// state with no app-store equivalent yet, and this layout is restricted to
+// `useAppStore` / react-router reads. Reattach once that surface is ported.
+export function BodyLayout() {
+ const matches = useMatches();
+ const location = useLocation();
+ const currentRouteName = (
+ matches.at(-1)?.handle as { name?: string } | undefined
+ )?.name;
+ const isRootPath = currentRouteName === WORKSPACE_ROOT_MODULE;
+ // Workspace "My Issues" is a standalone full-width page: header (with logo)
+ // but no sidebar, mirroring the Vue IssuesRouteShell (variant="issues").
+ const isMyIssues = currentRouteName === WORKSPACE_ROUTE_MY_ISSUES;
+ // Project-scoped routes (`workspace.project.*`) get the project sidebar; the
+ // bare projects list (`workspace.project`) keeps the workspace sidebar.
+ const isProjectRoute = Boolean(
+ currentRouteName?.startsWith(`${PROJECT_V1_ROUTE_DASHBOARD}.`)
+ );
+ const Sidebar = isProjectRoute ? ProjectSidebar : DashboardSidebar;
+ const variant = isMyIssues ? "issues" : "workspace";
+ const routeKey = `${location.pathname}${location.search}`;
+
+ const [targets, setTargets] = useState<DashboardShellTargets>({
+ desktopSidebar: null,
+ mobileSidebar: null,
+ content: null,
+ quickstart: null,
+ mainContainer: null,
+ });
+
+ // Non-project routes render through `RoutePermissionGuardShell`: it mounts
+ // into the shell's content target and reports a non-null target only once the
+ // route's `requiredPermissions` are satisfied, so a restricted page never
+ // mounts (it shows the permission-denied / request-role fallback instead).
+ // This mirrors the Vue `BodyLayout.vue` content teleport. Project routes
+ // (`workspace.project.*`) bypass this gate — their gating belongs to
+ // `ProjectRouteShell`, which loads the project resource for project-scoped
+ // permission checks.
+ const [permissionTarget, setPermissionTarget] =
+ useState<HTMLDivElement | null>(null);
+
+ // Agent toggle shortcut (Ctrl/Cmd+Shift+A), ported from the Vue layout.
+ useEffect(() => {
+ const handler = async (e: KeyboardEvent) => {
+ if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === "A") {
+ e.preventDefault();
+ const { useAgentStore } = await import(
+ "@/react/plugins/agent/store/agent"
+ );
+ useAgentStore.getState().toggle();
+ }
+ };
+ window.addEventListener("keydown", handler);
+ return () => window.removeEventListener("keydown", handler);
+ }, []);
+
+ const showSidebar = !isRootPath;
+ const sidebarTargets = [targets.desktopSidebar, targets.mobileSidebar];
+
+ return (
+ <>
+ <DashboardBodyShell
+ variant={variant}
+ isRootPath={isRootPath}
+ routeKey={routeKey}
+ onReady={setTargets}
+ />
+
+ {showSidebar
+ ? sidebarTargets.map((target, i) =>
+ target ? createPortal(<Sidebar />, target, `sidebar-${i}`) : null
+ )
+ : null}
+
+ {isProjectRoute
+ ? targets.content
+ ? createPortal(<Outlet />, targets.content)
+ : null
+ : targets.content
+ ? createPortal(
+ <RoutePermissionGuardShell
+ routeKey={routeKey}
+ className="m-4"
+ targetClassName="h-full min-h-0"
+ onReady={setPermissionTarget}
+ />,
+ targets.content
+ )
+ : null}
+
+ {!isProjectRoute && permissionTarget
+ ? createPortal(<Outlet />, permissionTarget)
+ : null}
+
+ {targets.quickstart
+ ? createPortal(<Quickstart />, targets.quickstart)
+ : null}
+ </>
+ );
+}
diff --git a/frontend/src/react/app/layouts/DashboardLayout.tsx b/frontend/src/react/app/layouts/DashboardLayout.tsx
new file mode 100644
index 0000000000..be07d4e714
--- /dev/null
+++ b/frontend/src/react/app/layouts/DashboardLayout.tsx
@@ -0,0 +1,28 @@
+import { useState } from "react";
+import { createPortal } from "react-dom";
+import { Outlet } from "react-router-dom";
+import { DashboardFrameShell } from "@/react/components/DashboardFrameShell";
+import type { DashboardFrameShellTargets } from "@/react/dashboard-shell";
+import { useEnsureWorkspaceCommonData } from "@/react/hooks/useEnsureWorkspaceCommonData";
+
+// Ported from `src/layouts/DashboardLayout.vue`. The Vue layout mounted
+// `DashboardFrameShell` and teleported `<router-view name="body"/>` into the
+// shell's body target. In React the named view collapses to the single
+// `<Outlet/>`, portaled into the body element the shell reports via `onReady`.
+// The shell renders banners + a loading gate; this layout also kicks off the
+// workspace-scope bootstrap (idempotent, deduped by the app store).
+export function DashboardLayout() {
+ useEnsureWorkspaceCommonData();
+
+ const [targets, setTargets] = useState<DashboardFrameShellTargets>({
+ banner: null,
+ body: null,
+ });
+
+ return (
+ <>
+ <DashboardFrameShell onReady={setTargets} />
+ {targets.body ? createPortal(<Outlet />, targets.body) : null}
+ </>
+ );
+}
diff --git a/frontend/src/react/app/layouts/SplashLayout.tsx b/frontend/src/react/app/layouts/SplashLayout.tsx
new file mode 100644
index 0000000000..942b74c89c
--- /dev/null
+++ b/frontend/src/react/app/layouts/SplashLayout.tsx
@@ -0,0 +1,41 @@
+import { Outlet, useMatches } from "react-router-dom";
+import signinImage from "@/assets/illustration/signin.webp";
+import signupImage from "@/assets/illustration/signup.webp";
+import { AUTH_SIGNUP_MODULE } from "@/react/router/handles";
+import { useAppStore } from "@/react/stores/app";
+import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";
+
+// Ported from `src/layouts/SplashLayout.vue`. Two-column auth chrome: an
+// optional branding illustration on the left (shown unless the workspace is on
+// a non-trialing enterprise plan) and the routed auth page on the right.
+export function SplashLayout() {
+ const matches = useMatches();
+ const currentRouteName = (
+ matches.at(-1)?.handle as { name?: string } | undefined
+ )?.name;
+
+ const currentPlan = useAppStore((s) => s.currentPlan());
+ const isTrialing = useAppStore((s) => s.isTrialing());
+ const showBrandingImage = currentPlan !== PlanType.ENTERPRISE || isTrialing;
+
+ return (
+ <div className="min-h-screen overflow-hidden flex">
+ {showBrandingImage ? (
+ <div className="hidden bg-white lg:block relative w-0 flex-1">
+ <img
+ className="absolute inset-0 h-full w-full object-cover"
+ src={
+ currentRouteName === AUTH_SIGNUP_MODULE
+ ? signupImage
+ : signinImage
+ }
+ alt=""
+ />
+ </div>
+ ) : null}
+ <div className="relative mx-auto flex-1 flex flex-col justify-center py-12 pb-24 px-4 sm:px-6 lg:flex-none lg:px-20 lg:w-1/2 xl:px-24">
+ <Outlet />
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/react/app/mountApp.ts b/frontend/src/react/app/mountApp.ts
new file mode 100644
index 0000000000..53e3a70ac9
--- /dev/null
+++ b/frontend/src/react/app/mountApp.ts
@@ -0,0 +1,27 @@
+import { buildTree, loadCoreDeps, type ReactComponent } from "@/react/mount";
+
+// import.meta.glob keeps vue-tsc from following into the .tsx file (it stays in
+// the React tsconfig project). Vite resolves the glob at build time.
+const appRootLoaders = import.meta.glob("./AppRoot.tsx");
+
+// Mounts the single React-Router application root (replaces the Vue
+// `createApp(App)` mount + the separate `#react-app` overlay mount). The
+// global overlays (Toaster, AgentWindow, SessionExpiredSurface, Watermark)
+// live in RootLayout, so this one root hosts everything.
+export async function mountReactRouterApp(selector: string) {
+ const container = document.querySelector(selector);
+ if (!container) {
+ throw new Error(`mountReactRouterApp: missing container ${selector}`);
+ }
+ const loader = appRootLoaders["./AppRoot.tsx"] as
+ | (() => Promise<Record<string, unknown>>)
+ | undefined;
+ if (!loader) {
+ throw new Error("mountReactRouterApp: AppRoot loader not registered");
+ }
+ const [deps, mod] = await Promise.all([loadCoreDeps(), loader()]);
+ const AppRoot = mod.AppRoot as ReactComponent;
+ const root = deps.createRoot(container);
+ root.render(buildTree(deps, AppRoot));
+ return root;
+}
diff --git a/frontend/src/react/components/CreateWorkloadIdentitySheet.tsx b/frontend/src/react/components/CreateWorkloadIdentitySheet.tsx
index e82c9f584d..fb74770ee4 100644
--- a/frontend/src/react/components/CreateWorkloadIdentitySheet.tsx
+++ b/frontend/src/react/components/CreateWorkloadIdentitySheet.tsx
@@ -14,7 +14,7 @@ import {
SheetHeader,
SheetTitle,
} from "@/react/components/ui/sheet";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { useAppStore } from "@/react/stores/app";
import { ensureWorkloadIdentityFullName } from "@/react/stores/app/workloadIdentity";
import { pushNotification } from "@/store";
@@ -144,9 +144,8 @@ function WorkloadIdentityForm({
(state) => state.updateWorkloadIdentity
);
- const projectEntity = useVueState(() =>
- project ? useAppStore.getState().getProjectByName(project) : undefined
- );
+ const projectFromName = useProjectByName(project ?? "");
+ const projectEntity = project ? projectFromName : undefined;
void projectsByName;
const isEditMode = !!workloadIdentity && !!workloadIdentity.email;
diff --git a/frontend/src/react/components/DashboardFrameShell.test.tsx b/frontend/src/react/components/DashboardFrameShell.test.tsx
index c8beb37dca..9720fc7967 100644
--- a/frontend/src/react/components/DashboardFrameShell.test.tsx
+++ b/frontend/src/react/components/DashboardFrameShell.test.tsx
@@ -96,8 +96,6 @@ describe("DashboardFrameShell", () => {
expect(onReady).toHaveBeenCalled();
expect(mocks.loadCurrentUser).toHaveBeenCalled();
- expect(mocks.fetchEnvironments).toHaveBeenCalled();
- expect(mocks.getOrFetchSettingByName).toHaveBeenCalled();
const targets = onReady.mock.lastCall?.[0];
expect(targets.banner).toBeInstanceOf(HTMLDivElement);
expect(targets.body).toBeInstanceOf(HTMLDivElement);
diff --git a/frontend/src/react/components/DashboardFrameShell.tsx b/frontend/src/react/components/DashboardFrameShell.tsx
index f65e2feb19..4d2ff11755 100644
--- a/frontend/src/react/components/DashboardFrameShell.tsx
+++ b/frontend/src/react/components/DashboardFrameShell.tsx
@@ -1,46 +1,13 @@
import { LoaderCircle } from "lucide-react";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useRef } from "react";
import type { DashboardFrameShellProps } from "@/react/dashboard-shell";
import { useEnsureWorkspaceCommonData } from "@/react/hooks/useEnsureWorkspaceCommonData";
-import { useEnvironmentV1Store, useSettingV1Store } from "@/store";
-import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
import { BannersWrapper } from "./BannersWrapper";
-// Legacy Pinia bootstrap kept alongside the app-store bootstrap because the
-// remaining Vue / shared-util surfaces still read from these Pinia stores
-// (e.g. expr.ts environment options, DashboardSidebar's app-feature profile).
-// The app store is loaded separately by useEnsureWorkspaceCommonData. Once
-// those Pinia readers are migrated this block can go away.
-const loadLegacyDashboardState = () => {
- return Promise.all([
- useEnvironmentV1Store().fetchEnvironments(),
- useSettingV1Store().getOrFetchSettingByName(
- Setting_SettingName.WORKSPACE_PROFILE
- ),
- ]);
-};
-
export function DashboardFrameShell({ onReady }: DashboardFrameShellProps) {
const bannerRef = useRef<HTMLDivElement>(null);
const bodyRef = useRef<HTMLDivElement>(null);
- const [legacyReady, setLegacyReady] = useState(false);
- const commonDataReady = useEnsureWorkspaceCommonData();
-
- useEffect(() => {
- let mounted = true;
- void loadLegacyDashboardState()
- .catch(() => undefined)
- .then(() => {
- if (mounted) {
- setLegacyReady(true);
- }
- });
- return () => {
- mounted = false;
- };
- }, []);
-
- const initialized = commonDataReady && legacyReady;
+ const initialized = useEnsureWorkspaceCommonData();
useEffect(() => {
if (!initialized) return;
diff --git a/frontend/src/react/components/DatabaseGroupDataTable.test.tsx b/frontend/src/react/components/DatabaseGroupDataTable.test.tsx
index b37c4cca4c..0e83b6ed39 100644
--- a/frontend/src/react/components/DatabaseGroupDataTable.test.tsx
+++ b/frontend/src/react/components/DatabaseGroupDataTable.test.tsx
@@ -11,14 +11,11 @@ vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: { resolve: vi.fn(() => ({ fullPath: "/x" })) },
}));
-vi.mock("@/router/dashboard/projectV1", () => ({
- PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL: "project.dbgroup.detail",
-}));
-
vi.mock("@/store", () => ({
getProjectNameAndDatabaseGroupName: (name: string) => name.split("/"),
}));
diff --git a/frontend/src/react/components/DatabaseGroupDataTable.tsx b/frontend/src/react/components/DatabaseGroupDataTable.tsx
index 3d32aff5be..dad06b3f12 100644
--- a/frontend/src/react/components/DatabaseGroupDataTable.tsx
+++ b/frontend/src/react/components/DatabaseGroupDataTable.tsx
@@ -17,8 +17,8 @@ import {
TableRow,
} from "@/react/components/ui/table";
import { cn } from "@/react/lib/utils";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL } from "@/router/dashboard/projectV1";
+import { router } from "@/react/router";
+import { PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL } from "@/react/router/handles";
import { getProjectNameAndDatabaseGroupName } from "@/store";
import type { DatabaseGroup } from "@/types/proto-es/v1/database_group_service_pb";
diff --git a/frontend/src/react/components/DatabaseResourceSelector.test.tsx b/frontend/src/react/components/DatabaseResourceSelector.test.tsx
index 42d8a84fd6..b5ffe45aee 100644
--- a/frontend/src/react/components/DatabaseResourceSelector.test.tsx
+++ b/frontend/src/react/components/DatabaseResourceSelector.test.tsx
@@ -48,10 +48,6 @@ vi.mock("@/plugins/i18n", () => ({
t: (key: string) => key,
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: (getter: () => unknown) => getter(),
-}));
-
vi.mock("@/react/components/AdvancedSearch", () => ({
getValueFromScopes: (
params: { scopes: { id: string; value: string }[] },
diff --git a/frontend/src/react/components/FeatureAttention.test.tsx b/frontend/src/react/components/FeatureAttention.test.tsx
index 83cdb472c9..16589be545 100644
--- a/frontend/src/react/components/FeatureAttention.test.tsx
+++ b/frontend/src/react/components/FeatureAttention.test.tsx
@@ -39,7 +39,8 @@ vi.mock("@/react/components/InstanceAssignmentSheet", () => ({
InstanceAssignmentSheet: () => null,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
push: mocks.routerPush,
},
diff --git a/frontend/src/react/components/FeatureAttention.tsx b/frontend/src/react/components/FeatureAttention.tsx
index 825bebe872..6f8cd23db1 100644
--- a/frontend/src/react/components/FeatureAttention.tsx
+++ b/frontend/src/react/components/FeatureAttention.tsx
@@ -6,8 +6,8 @@ import {
useServerState,
useSubscriptionState,
} from "@/react/hooks/useAppState";
+import { router } from "@/react/router";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
import { ENTERPRISE_INQUIRE_LINK, instanceLimitFeature } from "@/types";
import type {
Instance,
diff --git a/frontend/src/react/components/IssueTable.tsx b/frontend/src/react/components/IssueTable.tsx
index 4c31a38c7b..48ae5e868c 100644
--- a/frontend/src/react/components/IssueTable.tsx
+++ b/frontend/src/react/components/IssueTable.tsx
@@ -31,10 +31,12 @@ import { useClickOutside } from "@/react/hooks/useClickOutside";
import { useEscapeKey } from "@/react/hooks/useEscapeKey";
import { displayRoleTitleFromList } from "@/react/lib/role";
import { cn } from "@/react/lib/utils";
+import { router } from "@/react/router";
+import {
+ PROJECT_V1_ROUTE_DETAIL,
+ WORKSPACE_ROUTE_USER_PROFILE,
+} from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_DETAIL } from "@/router/dashboard/projectV1";
-import { WORKSPACE_ROUTE_USER_PROFILE } from "@/router/dashboard/workspaceRoutes";
import { pushNotification } from "@/store";
import {
getTimeForPbTimestampProtoEs,
diff --git a/frontend/src/react/components/PermissionGuard.test.tsx b/frontend/src/react/components/PermissionGuard.test.tsx
index fe7c1ea0b6..e3e116246d 100644
--- a/frontend/src/react/components/PermissionGuard.test.tsx
+++ b/frontend/src/react/components/PermissionGuard.test.tsx
@@ -55,6 +55,7 @@ vi.mock("@/react/stores/app", () => ({
}));
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: () => ({ t: (key: string) => key }),
}));
diff --git a/frontend/src/react/components/ProjectSidebar.tsx b/frontend/src/react/components/ProjectSidebar.tsx
index db08ab2ed7..3542f554e6 100644
--- a/frontend/src/react/components/ProjectSidebar.tsx
+++ b/frontend/src/react/components/ProjectSidebar.tsx
@@ -11,12 +11,10 @@ import {
import type { ElementType } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
-import { effectScope } from "vue";
import logoFull from "@/assets/logo-full.svg";
import { useWorkspace } from "@/react/hooks/useAppState";
-import { useVueState } from "@/react/hooks/useVueState";
-import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
+import { useRecentVisit } from "@/react/hooks/useRecentVisit";
+import { router, useCurrentRoute } from "@/react/router";
import {
PROJECT_V1_ROUTE_ACCESS_GRANTS,
PROJECT_V1_ROUTE_AUDIT_LOGS,
@@ -35,8 +33,8 @@ import {
PROJECT_V1_ROUTE_SYNC_SCHEMA,
PROJECT_V1_ROUTE_WEBHOOKS,
PROJECT_V1_ROUTE_WORKLOAD_IDENTITIES,
-} from "@/router/dashboard/projectV1";
-import { useRecentVisit } from "@/router/useRecentVisit";
+} from "@/react/router/handles";
+import { useAppStore } from "@/react/stores/app";
import { projectNamePrefix } from "@/store/modules/v1/common";
// ---------------------------------------------------------------------------
@@ -75,12 +73,13 @@ function useSidebarItems(): SidebarItem[] {
const { t } = useTranslation();
const defaultProject = useAppStore((s) => s.serverInfo?.defaultProject ?? "");
- const isDefault = useVueState(() => {
- const projectId =
- (router.currentRoute.value.params.projectId as string | undefined) ?? "";
- const projectName = projectId ? `${projectNamePrefix}${projectId}` : "";
- return !!defaultProject && projectName === defaultProject;
- });
+ const sidebarRoute = useCurrentRoute();
+ const sidebarProjectId =
+ (sidebarRoute.params.projectId as string | undefined) ?? "";
+ const sidebarProjectName = sidebarProjectId
+ ? `${projectNamePrefix}${sidebarProjectId}`
+ : "";
+ const isDefault = !!defaultProject && sidebarProjectName === defaultProject;
return useMemo(
(): SidebarItem[] => [
@@ -238,29 +237,15 @@ export function ProjectSidebar() {
const rawItems = useSidebarItems();
const filteredItems = useMemo(() => filterSidebarList(rawItems), [rawItems]);
- const currentRouteName = useVueState(
- () => router.currentRoute.value.name?.toString() ?? ""
- );
-
- const projectId = useVueState(
- () =>
- (router.currentRoute.value.params.projectId as string | undefined) ?? ""
- );
+ const route = useCurrentRoute();
+ const currentRouteName = route.name?.toString() ?? "";
+ const projectId = (route.params.projectId as string | undefined) ?? "";
const customLogo = useWorkspace()?.logo ?? "";
- // Create a Vue effectScope so we can call the Vue composable useRecentVisit.
- const recordVisitRef = useRef<((path: string) => void) | null>(null);
- useEffect(() => {
- // TODO(steven): Replace this Vue composable bridge with a shared framework-agnostic
- // recent-visit helper so React components don't need a Vue effect scope.
- const scope = effectScope();
- scope.run(() => {
- const { record } = useRecentVisit();
- recordVisitRef.current = record;
- });
- return () => scope.stop();
- }, []);
+ const { record } = useRecentVisit();
+ const recordVisitRef = useRef(record);
+ recordVisitRef.current = record;
// Ensure the project is fetched into the store cache.
// ProjectRouteShell also fetches it, but this guards against race conditions.
diff --git a/frontend/src/react/components/Quickstart.tsx b/frontend/src/react/components/Quickstart.tsx
index c254bdebca..9398382bfe 100644
--- a/frontend/src/react/components/Quickstart.tsx
+++ b/frontend/src/react/components/Quickstart.tsx
@@ -1,19 +1,19 @@
import { CheckCircle, X } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
-import type { RouteLocationRaw } from "vue-router";
import { cn } from "@/react/lib/utils";
+import type { RouteTarget } from "@/react/router";
import { useNavigate } from "@/react/router";
-import { useAppStore } from "@/react/stores/app";
-import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
import {
DATABASE_ROUTE_DASHBOARD,
ENVIRONMENT_V1_ROUTE_DASHBOARD,
INSTANCE_ROUTE_DASHBOARD,
PROJECT_V1_ROUTE_DASHBOARD,
+ PROJECT_V1_ROUTE_ISSUE_DETAIL,
+ SQL_EDITOR_WORKSHEET_MODULE,
WORKSPACE_ROUTE_USERS,
-} from "@/router/dashboard/workspaceRoutes";
-import { SQL_EDITOR_WORKSHEET_MODULE } from "@/router/sqlEditor";
+} from "@/react/router/handles";
+import { useAppStore } from "@/react/stores/app";
import { pushNotification } from "@/store";
import { projectNamePrefix } from "@/store/modules/v1/common";
import type { Permission } from "@/types";
@@ -31,7 +31,7 @@ const SAMPLE_SHEET_ID = "101";
interface IntroItem {
name: string;
- link: RouteLocationRaw;
+ link: RouteTarget;
done: boolean;
hide?: boolean;
requiredPermissions?: Permission[];
@@ -48,11 +48,11 @@ interface IntroItem {
* see tasks they can perform; tasks that depend on the sample project
* are filtered out when no sample project exists for this workspace.
*
- * State sources (all Pinia, read via `useVueState`):
- * - `actuatorStore.quickStartEnabled` — disabled in self-hosted /
- * enterprise builds via the actuator config.
- * - `uiStateStore.getIntroStateByKey(...)` — per-task done flags and
- * the global `hidden` flag (toggled when the user dismisses).
+ * State sources (app store):
+ * - `quickStartEnabled()` — disabled in self-hosted / enterprise builds
+ * via the actuator config.
+ * - `getIntroStateByKey(...)` — per-task done flags and the global
+ * `hidden` flag (toggled when the user dismisses).
*
* Async fetches (project / sample issue / sample worksheet) run on
* mount and fall back to undefined when the sample data is missing
diff --git a/frontend/src/react/components/RoutePermissionGuardShell.test.tsx b/frontend/src/react/components/RoutePermissionGuardShell.test.tsx
index ea2da3f3a2..4976687ab3 100644
--- a/frontend/src/react/components/RoutePermissionGuardShell.test.tsx
+++ b/frontend/src/react/components/RoutePermissionGuardShell.test.tsx
@@ -27,10 +27,6 @@ vi.mock("@/react/router", () => ({
useCurrentRoute: () => mocks.route,
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: (getter: () => unknown) => getter(),
-}));
-
vi.mock("@/react/components/FeatureBadge", () => ({
FeatureBadge: () => <span data-testid="feature-badge" />,
}));
@@ -75,6 +71,7 @@ vi.mock("@/react/stores/app", () => ({
}));
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: () => ({ t: (key: string) => key }),
}));
diff --git a/frontend/src/react/components/auth/AuthFooter.test.tsx b/frontend/src/react/components/auth/AuthFooter.test.tsx
index 7558c456c2..ebd10ae0f7 100644
--- a/frontend/src/react/components/auth/AuthFooter.test.tsx
+++ b/frontend/src/react/components/auth/AuthFooter.test.tsx
@@ -8,14 +8,13 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
).IS_REACT_ACT_ENVIRONMENT = true;
const mocks = vi.hoisted(() => ({
- useVueState: vi.fn<(getter: () => unknown) => unknown>(),
+ language: { value: "en-US" },
+ changeLanguage: vi.fn(),
emitStorageChangedEvent: vi.fn(),
setDocumentTitle: vi.fn(),
- routeTitle: vi.fn((_route: unknown) => "Signin"),
- locale: { value: "en-US" },
currentRoute: {
value: {
- meta: {} as { title?: (route: unknown) => string },
+ title: undefined as string | undefined,
},
},
}));
@@ -39,19 +38,23 @@ const localStorageMock = {
},
};
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ i18n: {
+ get language() {
+ return mocks.language.value;
+ },
+ changeLanguage: mocks.changeLanguage,
+ },
+ }),
}));
-vi.mock("@/plugins/i18n", () => ({
- default: {
- global: {
- locale: mocks.locale,
- },
- },
+vi.mock("@/react/i18n", () => ({
+ default: { changeLanguage: mocks.changeLanguage },
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
currentRoute: mocks.currentRoute,
},
@@ -87,8 +90,8 @@ const renderIntoContainer = (element: ReactElement) => {
beforeEach(async () => {
vi.clearAllMocks();
- mocks.locale.value = "en-US";
- mocks.currentRoute.value.meta = {};
+ mocks.language.value = "en-US";
+ mocks.currentRoute.value.title = undefined;
storage.clear();
Object.defineProperty(globalThis, "localStorage", {
value: localStorageMock,
@@ -106,7 +109,7 @@ afterEach(() => {
describe("AuthFooter", () => {
test("renders five language links in order", () => {
- mocks.useVueState.mockReturnValue("en-US");
+ mocks.language.value = "en-US";
const { container, render, unmount } = renderIntoContainer(<AuthFooter />);
render();
const anchors = Array.from(container.querySelectorAll("a"));
@@ -121,7 +124,7 @@ describe("AuthFooter", () => {
});
test("highlights the current locale with text-main", () => {
- mocks.useVueState.mockReturnValue("zh-CN");
+ mocks.language.value = "zh-CN";
const { container, render, unmount } = renderIntoContainer(<AuthFooter />);
render();
const anchors = Array.from(container.querySelectorAll("a"));
@@ -132,9 +135,9 @@ describe("AuthFooter", () => {
unmount();
});
- test("invokes Vue i18n + storage + title setter on click", () => {
- mocks.useVueState.mockReturnValue("en-US");
- mocks.currentRoute.value.meta = { title: mocks.routeTitle };
+ test("changes language + storage + title setter on click", () => {
+ mocks.language.value = "en-US";
+ mocks.currentRoute.value.title = "Signin";
const { container, render, unmount } = renderIntoContainer(<AuthFooter />);
render();
const esAnchor = Array.from(container.querySelectorAll("a")).find(
@@ -144,10 +147,9 @@ describe("AuthFooter", () => {
act(() => {
esAnchor?.click();
});
- expect(mocks.locale.value).toBe("es-ES");
+ expect(mocks.changeLanguage).toHaveBeenCalledWith("es-ES");
expect(localStorage.getItem("bb.language")).toBe('"es-ES"');
expect(mocks.emitStorageChangedEvent).toHaveBeenCalledTimes(1);
- expect(mocks.routeTitle).toHaveBeenCalledTimes(1);
expect(mocks.setDocumentTitle).toHaveBeenCalledWith("Signin");
unmount();
});
diff --git a/frontend/src/react/components/auth/AuthFooter.tsx b/frontend/src/react/components/auth/AuthFooter.tsx
index 7ae505fc7e..7ef68439b5 100644
--- a/frontend/src/react/components/auth/AuthFooter.tsx
+++ b/frontend/src/react/components/auth/AuthFooter.tsx
@@ -1,6 +1,6 @@
-import i18n from "@/plugins/i18n";
-import { useVueState } from "@/react/hooks/useVueState";
-import { router } from "@/router";
+import { useTranslation } from "react-i18next";
+import reactI18n from "@/react/i18n";
+import { router } from "@/react/router";
import { emitStorageChangedEvent, setDocumentTitle } from "@/utils";
import { STORAGE_KEY_LANGUAGE } from "@/utils/storage-keys";
@@ -26,18 +26,18 @@ function resolveLabel(locale: string): string {
}
function setAppLocale(lang: string) {
- i18n.global.locale.value = lang;
+ void reactI18n.changeLanguage(lang);
localStorage.setItem(STORAGE_KEY_LANGUAGE, JSON.stringify(lang));
emitStorageChangedEvent();
const route = router.currentRoute.value;
- if (route.meta.title) {
- setDocumentTitle(route.meta.title(route));
+ if (route.title) {
+ setDocumentTitle(route.title);
}
}
export function AuthFooter() {
- const currentLocale = useVueState(() => i18n.global.locale.value as string);
- const activeLabel = resolveLabel(currentLocale);
+ const { i18n: reactI18nInstance } = useTranslation();
+ const activeLabel = resolveLabel(reactI18nInstance.language);
const year = new Date().getFullYear();
return (
diff --git a/frontend/src/react/components/auth/EmailCodeSigninForm.test.tsx b/frontend/src/react/components/auth/EmailCodeSigninForm.test.tsx
index b0c54c0513..a82204faf0 100644
--- a/frontend/src/react/components/auth/EmailCodeSigninForm.test.tsx
+++ b/frontend/src/react/components/auth/EmailCodeSigninForm.test.tsx
@@ -17,8 +17,15 @@ const mocks = vi.hoisted(() => ({
vi.mock("@/store", () => ({
pushNotification: mocks.pushNotification,
- useAuthStore: () => ({
- sendEmailLoginCode: mocks.sendEmailLoginCode,
+}));
+
+vi.mock("@/react/stores/app", () => ({
+ useAppStore: Object.assign(() => ({}), {
+ getState: () => ({
+ sendEmailLoginCode: mocks.sendEmailLoginCode,
+ // resolveWorkspaceName() (the 2nd send-code arg) reads this.
+ workspaceResourceName: () => "",
+ }),
}),
}));
@@ -51,6 +58,7 @@ vi.mock("react-i18next", () => ({
t: (key: string, vars?: Record<string, unknown>) =>
vars ? `${key}:${JSON.stringify(vars)}` : key,
}),
+ initReactI18next: { type: "3rdParty", init: () => {} },
}));
let EmailCodeSigninForm: typeof import("./EmailCodeSigninForm").EmailCodeSigninForm;
diff --git a/frontend/src/react/components/auth/EmailCodeSigninForm.tsx b/frontend/src/react/components/auth/EmailCodeSigninForm.tsx
index 59a257274a..306adba621 100644
--- a/frontend/src/react/components/auth/EmailCodeSigninForm.tsx
+++ b/frontend/src/react/components/auth/EmailCodeSigninForm.tsx
@@ -4,12 +4,14 @@ import { useTranslation } from "react-i18next";
import { Button } from "@/react/components/ui/button";
import { Input } from "@/react/components/ui/input";
import { OtpInput } from "@/react/components/ui/otp-input";
-import { pushNotification, useAuthStore } from "@/store";
+import { resolveWorkspaceName } from "@/react/lib/workspace";
+import { useAppStore } from "@/react/stores/app";
+import { pushNotification } from "@/store";
import {
type LoginRequest,
LoginRequestSchema,
} from "@/types/proto-es/v1/auth_service_pb";
-import { isValidEmail, resolveWorkspaceName } from "@/utils";
+import { isValidEmail } from "@/utils";
type Props = {
readonly loading: boolean;
@@ -60,7 +62,9 @@ export function EmailCodeSigninForm({ loading, onSignin }: Props) {
if (!isValidEmail(email) || sending || resendCountdown > 0) return;
setSending(true);
try {
- await useAuthStore().sendEmailLoginCode(email, resolveWorkspaceName());
+ await useAppStore
+ .getState()
+ .sendEmailLoginCode(email, resolveWorkspaceName());
setStep("code");
startCountdown();
} catch (e) {
diff --git a/frontend/src/react/components/auth/InactiveRemindModal.tsx b/frontend/src/react/components/auth/InactiveRemindModal.tsx
index 4995e92df3..dd25937b28 100644
--- a/frontend/src/react/components/auth/InactiveRemindModal.tsx
+++ b/frontend/src/react/components/auth/InactiveRemindModal.tsx
@@ -9,7 +9,6 @@ import {
} from "@/react/components/ui/dialog";
import { useCurrentUser } from "@/react/hooks/useAppState";
import { useAppStore } from "@/react/stores/app";
-import { useAuthStore } from "@/store";
import { storageKeyLastActivity } from "@/utils/storage-keys";
const SHOW_THRESHOLD_MIN = 3;
@@ -69,7 +68,7 @@ export function InactiveRemindModal() {
}
logoutTimerRef.current = setTimeout(
() => {
- useAuthStore().logout();
+ useAppStore.getState().logout();
},
SHOW_THRESHOLD_MIN * 60 * 1000
);
@@ -87,7 +86,7 @@ export function InactiveRemindModal() {
setLastActivityTs(now);
};
- const logout = () => useAuthStore().logout();
+ const logout = () => useAppStore.getState().logout();
if (!shouldShow) return null;
diff --git a/frontend/src/react/components/auth/PasswordSigninForm.tsx b/frontend/src/react/components/auth/PasswordSigninForm.tsx
index 7b7ca827e9..012343171f 100644
--- a/frontend/src/react/components/auth/PasswordSigninForm.tsx
+++ b/frontend/src/react/components/auth/PasswordSigninForm.tsx
@@ -4,13 +4,13 @@ import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/react/components/ui/button";
import { Input } from "@/react/components/ui/input";
-import { router } from "@/router";
-import { AUTH_PASSWORD_FORGOT_MODULE } from "@/router/auth";
+import { resolveWorkspaceName } from "@/react/lib/workspace";
+import { router } from "@/react/router";
+import { AUTH_PASSWORD_FORGOT_MODULE } from "@/react/router/handles";
import {
type LoginRequest,
LoginRequestSchema,
} from "@/types/proto-es/v1/auth_service_pb";
-import { resolveWorkspaceName } from "@/utils";
type Props = {
readonly loading: boolean;
diff --git a/frontend/src/react/components/auth/SessionExpiredSurface.test.tsx b/frontend/src/react/components/auth/SessionExpiredSurface.test.tsx
index 9743072c41..dc1d4fa543 100644
--- a/frontend/src/react/components/auth/SessionExpiredSurface.test.tsx
+++ b/frontend/src/react/components/auth/SessionExpiredSurface.test.tsx
@@ -6,9 +6,9 @@ vi.mock("@/react/pages/auth/SigninPage", () => ({
SigninPage: () => <button data-testid="signin-bridge">Sign in</button>,
}));
-vi.mock("@/store", () => ({
- useAuthStore: () => ({
- logout: vi.fn(),
+vi.mock("@/react/stores/app", () => ({
+ useAppStore: Object.assign(() => ({}), {
+ getState: () => ({ logout: vi.fn() }),
}),
}));
@@ -16,6 +16,7 @@ vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string) => key,
}),
+ initReactI18next: { type: "3rdParty", init: () => {} },
}));
import { Dialog, DialogContent } from "@/react/components/ui/dialog";
diff --git a/frontend/src/react/components/auth/SessionExpiredSurface.tsx b/frontend/src/react/components/auth/SessionExpiredSurface.tsx
index b09d818b66..b85d95f895 100644
--- a/frontend/src/react/components/auth/SessionExpiredSurface.tsx
+++ b/frontend/src/react/components/auth/SessionExpiredSurface.tsx
@@ -6,7 +6,7 @@ import {
LAYER_SURFACE_CLASS,
} from "@/react/components/ui/layer";
import { SigninPage } from "@/react/pages/auth/SigninPage";
-import { useAuthStore } from "@/store";
+import { useAppStore } from "@/react/stores/app";
export function SessionExpiredSurface({
currentPath,
@@ -20,7 +20,7 @@ export function SessionExpiredSurface({
<button
type="button"
className="text-sm text-control-light hover:underline"
- onClick={() => useAuthStore().logout()}
+ onClick={() => useAppStore.getState().logout()}
>
{t("common.logout")}
</button>
diff --git a/frontend/src/react/components/database/CreateDatabaseSheet.test.tsx b/frontend/src/react/components/database/CreateDatabaseSheet.test.tsx
index 624b15e25c..40af2bfea4 100644
--- a/frontend/src/react/components/database/CreateDatabaseSheet.test.tsx
+++ b/frontend/src/react/components/database/CreateDatabaseSheet.test.tsx
@@ -156,15 +156,14 @@ vi.mock("@/react/hooks/useAppState", () => ({
useCurrentUser: () => mocks.currentUser,
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: (getter: () => unknown) => getter(),
-}));
-
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
-vi.mock("@/router", () => ({ router: { push: vi.fn() } }));
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
+ router: { push: vi.fn() },
+}));
vi.mock("@/types", () => ({
isValidProjectName: (name: string) =>
diff --git a/frontend/src/react/components/database/CreateDatabaseSheet.tsx b/frontend/src/react/components/database/CreateDatabaseSheet.tsx
index 849c4ed062..7087196dd4 100644
--- a/frontend/src/react/components/database/CreateDatabaseSheet.tsx
+++ b/frontend/src/react/components/database/CreateDatabaseSheet.tsx
@@ -18,11 +18,11 @@ import {
SheetTitle,
} from "@/react/components/ui/sheet";
import { useCurrentUser } from "@/react/hooks/useAppState";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { cn } from "@/react/lib/utils";
+import { router } from "@/react/router";
import { useAppStore } from "@/react/stores/app";
import { experimentalCreateIssueByPlan } from "@/react/stores/app/issue";
-import { router } from "@/router";
import { pushNotification } from "@/store";
import {
defaultCharsetOfEngineV1,
@@ -96,17 +96,14 @@ export function CreateDatabaseSheet({
const effectiveProjectName = fixedProjectName || projectName;
- // Intentional split: enforceIssueTitle is read reactively via useVueState
- // because it's a governance gate that MUST reflect the live project state
+ // Intentional split: enforceIssueTitle is read reactively (via the app-store
+ // project cache) because it's a governance gate that MUST reflect live state
// (workspace-picker swaps change projects mid-form). `issueLabels` /
// `forceIssueLabels` stay on the pre-existing `selectedProject` snapshot
// pattern below — they have a known staleness seam that is out of scope
// for BYT-9310. Do not collapse these back together without a separate spec.
- const projectReactive = useVueState(() =>
- effectiveProjectName
- ? useAppStore.getState().getProjectByName(effectiveProjectName)
- : undefined
- );
+ const projectFromName = useProjectByName(effectiveProjectName ?? "");
+ const projectReactive = effectiveProjectName ? projectFromName : undefined;
void projectsByName;
// Note on hydration: projectStore.getProjectByName returns an
diff --git a/frontend/src/react/components/database/DatabaseTable.tsx b/frontend/src/react/components/database/DatabaseTable.tsx
index bffab5ca1b..a76397ba7e 100644
--- a/frontend/src/react/components/database/DatabaseTable.tsx
+++ b/frontend/src/react/components/database/DatabaseTable.tsx
@@ -5,8 +5,8 @@ import {
useSessionPageSize,
} from "@/react/hooks/useSessionPageSize";
import type { DatabaseFilter } from "@/react/lib/databaseFilter";
+import { router } from "@/react/router";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import { autoDatabaseRoute } from "@/utils";
import {
diff --git a/frontend/src/react/components/header/ProfileMenuTrigger.tsx b/frontend/src/react/components/header/ProfileMenuTrigger.tsx
index d8ae9e7027..d0dc5fb763 100644
--- a/frontend/src/react/components/header/ProfileMenuTrigger.tsx
+++ b/frontend/src/react/components/header/ProfileMenuTrigger.tsx
@@ -21,7 +21,6 @@ import {
useWorkspace,
} from "@/react/hooks/useAppState";
import {
- AUTH_SIGNIN_MODULE,
isSqlEditorRouteName,
SETTING_ROUTE_PROFILE,
SQL_EDITOR_HOME_MODULE,
@@ -236,15 +235,9 @@ export function ProfileMenuTrigger({
<DropdownMenuItem
onClick={() => {
setOpen(false);
- const redirect =
- route.fullPath.startsWith("/auth") || !route.fullPath
- ? undefined
- : route.fullPath;
- const signinUrl = navigate.resolve({
- name: AUTH_SIGNIN_MODULE,
- query: { redirect },
- }).fullPath;
- void useAppStore.getState().logout(signinUrl);
+ // logout() computes the signin redirect itself (mirrors the
+ // legacy Pinia auth store) and hard-redirects to clear state.
+ void useAppStore.getState().logout();
}}
>
{t("common.logout")}
diff --git a/frontend/src/react/components/header/ProjectSwitchPanel.test.tsx b/frontend/src/react/components/header/ProjectSwitchPanel.test.tsx
index 56f774a4ce..23411e152f 100644
--- a/frontend/src/react/components/header/ProjectSwitchPanel.test.tsx
+++ b/frontend/src/react/components/header/ProjectSwitchPanel.test.tsx
@@ -57,6 +57,7 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: () => ({
t: (key: string) =>
({
diff --git a/frontend/src/react/components/instance/InstanceActionDropdown.tsx b/frontend/src/react/components/instance/InstanceActionDropdown.tsx
index 2278b0a9d2..af679ebd0e 100644
--- a/frontend/src/react/components/instance/InstanceActionDropdown.tsx
+++ b/frontend/src/react/components/instance/InstanceActionDropdown.tsx
@@ -7,9 +7,9 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/react/components/ui/dropdown-menu";
+import { router } from "@/react/router";
+import { INSTANCE_ROUTE_DASHBOARD } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { INSTANCE_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";
import { pushNotification } from "@/store";
import { State } from "@/types/proto-es/v1/common_pb";
import type { Instance } from "@/types/proto-es/v1/instance_service_pb";
diff --git a/frontend/src/react/components/instance/InstanceFormButtons.tsx b/frontend/src/react/components/instance/InstanceFormButtons.tsx
index 7834cd068d..e683bb6726 100644
--- a/frontend/src/react/components/instance/InstanceFormButtons.tsx
+++ b/frontend/src/react/components/instance/InstanceFormButtons.tsx
@@ -3,8 +3,8 @@ import { cloneDeep, isEqual } from "lodash-es";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { cn } from "@/react/lib/utils";
+import { router } from "@/react/router";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
import { pushNotification } from "@/store";
import { Engine } from "@/types/proto-es/v1/common_pb";
import type {
diff --git a/frontend/src/react/components/release/ReleaseInfoCard.test.tsx b/frontend/src/react/components/release/ReleaseInfoCard.test.tsx
index f159db4346..aa00a02be7 100644
--- a/frontend/src/react/components/release/ReleaseInfoCard.test.tsx
+++ b/frontend/src/react/components/release/ReleaseInfoCard.test.tsx
@@ -15,6 +15,7 @@ import {
).IS_REACT_ACT_ENVIRONMENT = true;
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: () => ({
t: (key: string, options?: Record<string, unknown>) =>
options && "count" in options ? `${key}:${options.count}` : key,
diff --git a/frontend/src/react/components/revision/RevisionDetailPanel.tsx b/frontend/src/react/components/revision/RevisionDetailPanel.tsx
index d8037106fe..6908e6a1f2 100644
--- a/frontend/src/react/components/revision/RevisionDetailPanel.tsx
+++ b/frontend/src/react/components/revision/RevisionDetailPanel.tsx
@@ -5,8 +5,8 @@ import { sheetServiceClientConnect } from "@/connect";
import { ReadonlyMonaco } from "@/react/components/monaco";
import { TaskRunLogViewer } from "@/react/components/task-run-log";
import { useRevisionByName } from "@/react/hooks/useAppState";
+import { router } from "@/react/router";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
import { pushNotification } from "@/store";
import { getTimeForPbTimestampProtoEs } from "@/types";
import { bytesToString, formatAbsoluteDateTime } from "@/utils";
diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx
index dab94e1412..c5787e4736 100644
--- a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx
+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx
@@ -9,8 +9,6 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
- // Pinia bridge — resolves the current user's email from the Pinia ref.
- usePiniaBridge: vi.fn<(getter: () => unknown) => unknown>(),
// Zustand editor store project read.
project: "projects/proj1" as string,
// Current tab connection database used to derive default targets.
@@ -30,10 +28,6 @@ vi.mock("react-i18next", () => ({
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/react/hooks/usePiniaBridge", () => ({
- usePiniaBridge: mocks.usePiniaBridge,
-}));
-
vi.mock("@/react/hooks/useAppState", () => ({
useCurrentUser: () => ({
name: "users/me",
@@ -92,16 +86,13 @@ vi.mock("@/connect", () => ({
},
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
resolve: mocks.routerResolve,
},
}));
-vi.mock("@/router/dashboard/projectV1", () => ({
- PROJECT_V1_ROUTE_ISSUE_DETAIL: "project.issue-detail",
-}));
-
vi.mock("@/utils", () => ({
extractDatabaseResourceName: vi.fn((name: string) => {
const parts = name.split("/");
@@ -327,8 +318,6 @@ const setupMocks = () => {
mocks.currentTabDatabase = "instances/inst1/databases/db1";
mocks.fetchDatabases.mockResolvedValue({ databases: [], nextPageToken: "" });
-
- mocks.usePiniaBridge.mockImplementation((getter: () => unknown) => getter());
};
beforeEach(async () => {
diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx
index 9a98a6bd00..d8b19714bc 100644
--- a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx
+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx
@@ -20,12 +20,12 @@ import {
} from "@/react/components/ui/sheet";
import { Textarea } from "@/react/components/ui/textarea";
import { useCurrentUser } from "@/react/hooks/useAppState";
+import { router } from "@/react/router";
+import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";
import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
import {
AccessGrant_Status,
AccessGrantSchema,
diff --git a/frontend/src/react/components/sql-editor/AsidePanel.tsx b/frontend/src/react/components/sql-editor/AsidePanel.tsx
index 89fdefedeb..14aa45c4dc 100644
--- a/frontend/src/react/components/sql-editor/AsidePanel.tsx
+++ b/frontend/src/react/components/sql-editor/AsidePanel.tsx
@@ -1,6 +1,8 @@
import { useCallback, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { ProjectSelect } from "@/react/components/ProjectSelect";
+import { router } from "@/react/router";
+import { PROJECT_V1_ROUTE_DASHBOARD } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
import {
@@ -8,8 +10,6 @@ import {
useSQLEditorEditorState,
} from "@/react/stores/sqlEditor/editor";
import { useIsDisconnected } from "@/react/stores/sqlEditor/tab";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";
import { defaultProject, isValidProjectName } from "@/types";
import { AccessPane } from "./AccessPane";
import { ActionBar } from "./AsidePanel/ActionBar";
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx
index e00d65acff..65c06dd5fb 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx
@@ -99,19 +99,15 @@ const mocks = vi.hoisted(() => {
treeStore,
appStore,
currentUser,
- usePiniaBridge: vi.fn<(getter: () => unknown) => unknown>(),
pushNotification: vi.fn(),
};
});
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: () => ({ t: (key: string) => key }),
}));
-vi.mock("@/react/hooks/usePiniaBridge", () => ({
- usePiniaBridge: mocks.usePiniaBridge,
-}));
-
vi.mock("@/react/hooks/useSQLEditorBridge", () => ({
// FEATURE_BATCH_QUERY === 1, FEATURE_DATABASE_GROUPS === 2 (see the
// subscription_service_pb mock below).
@@ -218,22 +214,37 @@ vi.mock("@/types", () => ({
}),
}));
-vi.mock("@/types/proto-es/v1/instance_service_pb", () => ({
+vi.mock("@/types/proto-es/v1/instance_service_pb", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@/types/proto-es/v1/instance_service_pb")
+ >()),
DataSourceType: { ADMIN: 1, READ_ONLY: 2 },
}));
-vi.mock("@/types/proto-es/v1/subscription_service_pb", () => ({
- PlanFeature: {
- FEATURE_BATCH_QUERY: 1,
- FEATURE_DATABASE_GROUPS: 2,
- FEATURE_ENVIRONMENT_TIERS: 3,
- },
- PlanType: { FREE: 0, TEAM: 1, ENTERPRISE: 3 },
-}));
-
-vi.mock("@/types/proto-es/v1/database_group_service_pb", () => ({
- DatabaseGroupView: { FULL: 2 },
-}));
+vi.mock(
+ "@/types/proto-es/v1/subscription_service_pb",
+ async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@/types/proto-es/v1/subscription_service_pb")
+ >()),
+ PlanFeature: {
+ FEATURE_BATCH_QUERY: 1,
+ FEATURE_DATABASE_GROUPS: 2,
+ FEATURE_ENVIRONMENT_TIERS: 3,
+ },
+ PlanType: { FREE: 0, TEAM: 1, ENTERPRISE: 3 },
+ })
+);
+
+vi.mock(
+ "@/types/proto-es/v1/database_group_service_pb",
+ async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@/types/proto-es/v1/database_group_service_pb")
+ >()),
+ DatabaseGroupView: { FULL: 2 },
+ })
+);
vi.mock("@/utils", () => ({
extractDatabaseResourceName: (n: string) => ({
@@ -421,7 +432,6 @@ const renderIntoContainer = (element: ReactElement) => {
beforeEach(async () => {
vi.clearAllMocks();
- mocks.usePiniaBridge.mockImplementation((getter) => getter());
// Reset feature flags default to true for render-path tests.
mocks.features.batchQuery = true;
mocks.features.databaseGroups = true;
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.test.tsx
index 7ee4b53dcc..47e47546b6 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.test.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.test.tsx
@@ -19,6 +19,7 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: () => ({ t: (key: string) => key }),
}));
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.test.tsx
index 18d6ade66e..d58f8c5481 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.test.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.test.tsx
@@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: () => ({ t: (key: string) => key }),
}));
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/InstanceNode.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/InstanceNode.test.tsx
index c8e31b57b8..476a7798e8 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/InstanceNode.test.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/InstanceNode.test.tsx
@@ -9,6 +9,7 @@ import type { SQLEditorTreeNode } from "@/types";
).IS_REACT_ACT_ENVIRONMENT = true;
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: () => ({ t: (key: string) => key }),
}));
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/LabelNode.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/LabelNode.test.tsx
index 2c0ebf7ee8..f234580537 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/LabelNode.test.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/LabelNode.test.tsx
@@ -9,6 +9,7 @@ import type { SQLEditorTreeNode } from "@/types";
).IS_REACT_ACT_ENVIRONMENT = true;
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: () => ({ t: (key: string) => key }),
}));
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/actions.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/actions.test.tsx
index 1c0cc43669..c1b1da072d 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/actions.test.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/actions.test.tsx
@@ -15,6 +15,7 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: () => ({ t: (key: string) => key }),
}));
@@ -52,14 +53,11 @@ vi.mock("@/react/stores/sqlEditor", () => ({
),
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: { resolve: vi.fn(() => ({ href: "/x" })) },
}));
-vi.mock("@/router/dashboard/projectV1", () => ({
- PROJECT_V1_ROUTE_DATABASE_DETAIL: "project.database.detail",
-}));
-
vi.mock("@/views/sql-editor/events", () => ({
sqlEditorEvents: { emit: mocks.sqlEditorEventsEmit },
}));
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/actions.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/actions.tsx
index 4f2f982f3d..6e707c00a9 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/actions.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/actions.tsx
@@ -7,11 +7,11 @@ import {
import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useSQLEditorAllowAdmin } from "@/react/hooks/useSQLEditorBridge";
+import { router } from "@/react/router";
+import { PROJECT_V1_ROUTE_DATABASE_DETAIL } from "@/react/router/handles";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";
import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_DATABASE_DETAIL } from "@/router/dashboard/projectV1";
import type {
BatchQueryContext,
SQLEditorConnection,
diff --git a/frontend/src/react/components/sql-editor/ConnectionPanel.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPanel.test.tsx
index 7af7c7f709..b0da2c6bb3 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPanel.test.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPanel.test.tsx
@@ -23,14 +23,11 @@ vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: { push: mocks.routerPush },
}));
-vi.mock("@/router/dashboard/workspaceRoutes", () => ({
- INSTANCE_ROUTE_DASHBOARD: "workspace.instance",
-}));
-
vi.mock("@/react/stores/sqlEditor", () => ({
useSQLEditorStore: (
selector: (s: {
diff --git a/frontend/src/react/components/sql-editor/ConnectionPanel.tsx b/frontend/src/react/components/sql-editor/ConnectionPanel.tsx
index 8b175983c8..327fe651bd 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPanel.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPanel.tsx
@@ -12,9 +12,9 @@ import {
} from "@/react/components/ui/sheet";
import { Tooltip } from "@/react/components/ui/tooltip";
import { cn } from "@/react/lib/utils";
+import { router } from "@/react/router";
+import { INSTANCE_ROUTE_DASHBOARD } from "@/react/router/handles";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
-import { router } from "@/router";
-import { INSTANCE_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";
import type { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import { hasWorkspacePermissionV2 } from "@/utils";
import { ConnectionPane } from "./ConnectionPane/ConnectionPane";
diff --git a/frontend/src/react/components/sql-editor/ContainerChooser.test.tsx b/frontend/src/react/components/sql-editor/ContainerChooser.test.tsx
index 5ee74078bc..4a556f4a23 100644
--- a/frontend/src/react/components/sql-editor/ContainerChooser.test.tsx
+++ b/frontend/src/react/components/sql-editor/ContainerChooser.test.tsx
@@ -52,7 +52,8 @@ vi.mock("@/react/stores/sqlEditor/tab", () => ({
getSQLEditorTabsState: mocks.getSQLEditorTabsState,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: mocks.router,
}));
diff --git a/frontend/src/react/components/sql-editor/ContainerChooser.tsx b/frontend/src/react/components/sql-editor/ContainerChooser.tsx
index bc3765e506..e071f64ab5 100644
--- a/frontend/src/react/components/sql-editor/ContainerChooser.tsx
+++ b/frontend/src/react/components/sql-editor/ContainerChooser.tsx
@@ -1,8 +1,8 @@
import { useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useAppDatabaseMetadata } from "@/react/hooks/useAppDatabaseMetadata";
+import { useReactiveRoute } from "@/react/hooks/useReactiveRoute";
import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";
-import { useVueRoute } from "@/react/hooks/useVueRoute";
import {
getSQLEditorTabsState,
useSQLEditorTabState,
@@ -69,7 +69,7 @@ export function ContainerChooser() {
// tracked both `route.query.table` and `tab.value` (the latter via the
// setter's reactive reads) so that switching to a new tab with the URL
// query still present re-seeded the new tab's connection.table.
- const queryParam = useVueRoute().query.table as string | undefined;
+ const queryParam = useReactiveRoute().query.table as string | undefined;
const currentTabId = useSQLEditorTabState((s) => s.currentTabId);
useEffect(() => {
if (queryParam) handleChange(queryParam);
diff --git a/frontend/src/react/components/sql-editor/ExecuteHint.tsx b/frontend/src/react/components/sql-editor/ExecuteHint.tsx
index 6aa7f9097c..8035c11cbc 100644
--- a/frontend/src/react/components/sql-editor/ExecuteHint.tsx
+++ b/frontend/src/react/components/sql-editor/ExecuteHint.tsx
@@ -4,11 +4,11 @@ import { Alert } from "@/react/components/ui/alert";
import { Button } from "@/react/components/ui/button";
import { useSQLEditorAllowAdmin } from "@/react/hooks/useSQLEditorBridge";
import { applyPlanTitleToQuery } from "@/react/lib/plan/title";
+import { router } from "@/react/router";
+import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";
import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";
import { unknownProject } from "@/types";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import {
diff --git a/frontend/src/react/components/sql-editor/GutterBar.test.tsx b/frontend/src/react/components/sql-editor/GutterBar.test.tsx
index c2d5bfd096..cfd8042c88 100644
--- a/frontend/src/react/components/sql-editor/GutterBar.test.tsx
+++ b/frontend/src/react/components/sql-editor/GutterBar.test.tsx
@@ -9,8 +9,6 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
- // Pinia bridge — runs the getter against the (mocked) Pinia stores.
- usePiniaBridge: vi.fn<(getter: () => unknown) => unknown>(),
// Zustand editor store project name.
project: "projects/test" as string,
// useAppProject (app store) return value.
@@ -29,10 +27,6 @@ vi.mock("react-i18next", () => ({
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/react/hooks/usePiniaBridge", () => ({
- usePiniaBridge: mocks.usePiniaBridge,
-}));
-
vi.mock("@/react/hooks/useAppProject", () => ({
useAppProject: () => mocks.projectData,
}));
@@ -55,7 +49,8 @@ vi.mock("@/react/stores/sqlEditor", () => ({
}),
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
resolve: mocks.routerResolve,
currentRoute: { value: { params: {} } },
@@ -63,14 +58,6 @@ vi.mock("@/router", () => ({
},
}));
-vi.mock("@/router/dashboard/projectV1", () => ({
- PROJECT_V1_ROUTE_DETAIL: "project.detail",
-}));
-
-vi.mock("@/router/dashboard/workspaceRoutes", () => ({
- WORKSPACE_ROUTE_LANDING: "workspace.landing",
-}));
-
vi.mock("@/assets/logo-icon.svg", () => ({
default: "/assets/logo-icon.svg",
}));
@@ -112,7 +99,6 @@ beforeEach(async () => {
describe("GutterBar", () => {
test("renders 3 tabs when project does not allow JIT access", () => {
- mocks.usePiniaBridge.mockImplementation((getter) => getter());
mocks.projectData = { allowJustInTimeAccess: false };
const { container, render, unmount } = renderIntoContainer(<GutterBar />);
render();
@@ -122,7 +108,6 @@ describe("GutterBar", () => {
});
test("renders 4 tabs when project allows JIT access", () => {
- mocks.usePiniaBridge.mockImplementation((getter) => getter());
mocks.projectData = { allowJustInTimeAccess: true };
const { container, render, unmount } = renderIntoContainer(<GutterBar />);
render();
@@ -132,7 +117,6 @@ describe("GutterBar", () => {
});
test("click writes asidePanelTab via setAsidePanelTab", () => {
- mocks.usePiniaBridge.mockImplementation((getter) => getter());
mocks.projectData = { allowJustInTimeAccess: false };
const { container, render, unmount } = renderIntoContainer(<GutterBar />);
render();
@@ -145,7 +129,6 @@ describe("GutterBar", () => {
});
test("logo link has target=_blank and rel=noopener noreferrer", () => {
- mocks.usePiniaBridge.mockImplementation((getter) => getter());
mocks.projectData = { allowJustInTimeAccess: false };
mocks.routerResolve.mockReturnValue({ href: "/workspace/home" });
const { container, render, unmount } = renderIntoContainer(<GutterBar />);
diff --git a/frontend/src/react/components/sql-editor/GutterBar.tsx b/frontend/src/react/components/sql-editor/GutterBar.tsx
index eb8b18393a..58c695c6da 100644
--- a/frontend/src/react/components/sql-editor/GutterBar.tsx
+++ b/frontend/src/react/components/sql-editor/GutterBar.tsx
@@ -1,13 +1,15 @@
import logoIcon from "@/assets/logo-icon.svg";
import { Separator } from "@/react/components/ui/separator";
import { useAppProject } from "@/react/hooks/useAppProject";
-import { useVueRoute } from "@/react/hooks/useVueRoute";
+import { useReactiveRoute } from "@/react/hooks/useReactiveRoute";
+import { router } from "@/react/router";
+import {
+ PROJECT_V1_ROUTE_DETAIL,
+ WORKSPACE_ROUTE_LANDING,
+} from "@/react/router/handles";
import type { AsidePanelTab } from "@/react/stores/sqlEditor";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_DETAIL } from "@/router/dashboard/projectV1";
-import { WORKSPACE_ROUTE_LANDING } from "@/router/dashboard/workspaceRoutes";
import { TabItem } from "./TabItem";
/**
@@ -24,7 +26,9 @@ export function GutterBar() {
const resolvedProject = useAppProject(projectName);
const project = projectName ? resolvedProject : undefined;
- const routeProjectParam = useVueRoute().params.project as string | undefined;
+ const routeProjectParam = useReactiveRoute().params.project as
+ | string
+ | undefined;
const logoHref = routeProjectParam
? router.resolve({
diff --git a/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx b/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx
index e674371206..573330c769 100644
--- a/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx
+++ b/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx
@@ -10,8 +10,6 @@ import { Engine } from "@/types/proto-es/v1/common_pb";
const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
- // Pinia bridge — runs the getter (resolves openAIEnabled from settings).
- usePiniaBridge: vi.fn<(getter: () => unknown) => unknown>(),
// Per-test controllable tab-derived state.
tabState: {
isDisconnected: false,
@@ -41,10 +39,6 @@ vi.mock("react-i18next", () => ({
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/react/hooks/usePiniaBridge", () => ({
- usePiniaBridge: mocks.usePiniaBridge,
-}));
-
vi.mock("@/store", () => ({
useSettingV1Store: mocks.useSettingV1Store,
}));
@@ -109,14 +103,11 @@ vi.mock("@/plugins/ai/logic/prompt", () => ({
findProblems: mocks.findProblems,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: { push: mocks.routerPush },
}));
-vi.mock("@/router/dashboard/workspaceSetting", () => ({
- SETTING_ROUTE_WORKSPACE_GENERAL: "settings.workspace.general",
-}));
-
// Minimal primitive stubs.
vi.mock("@/react/components/ui/button", () => ({
Button: ({
diff --git a/frontend/src/react/components/sql-editor/OpenAIButton.tsx b/frontend/src/react/components/sql-editor/OpenAIButton.tsx
index 8acc81791b..5b144a32fb 100644
--- a/frontend/src/react/components/sql-editor/OpenAIButton.tsx
+++ b/frontend/src/react/components/sql-editor/OpenAIButton.tsx
@@ -17,14 +17,14 @@ import {
} from "@/react/components/ui/popover";
import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";
import { cn } from "@/react/lib/utils";
+import { router } from "@/react/router";
+import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
import {
useIsDisconnected,
useSQLEditorTabState,
} from "@/react/stores/sqlEditor/tab";
-import { router } from "@/router";
-import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";
import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
import { hasWorkspacePermissionV2, nextAnimationFrame } from "@/utils";
diff --git a/frontend/src/react/components/sql-editor/ResultView/SensitiveDataIcon.tsx b/frontend/src/react/components/sql-editor/ResultView/SensitiveDataIcon.tsx
index 805b35e532..827a705ed4 100644
--- a/frontend/src/react/components/sql-editor/ResultView/SensitiveDataIcon.tsx
+++ b/frontend/src/react/components/sql-editor/ResultView/SensitiveDataIcon.tsx
@@ -2,8 +2,8 @@ import { EyeOffIcon } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Tooltip } from "@/react/components/ui/tooltip";
import { cn } from "@/react/lib/utils";
-import { router } from "@/router";
-import { WORKSPACE_ROUTE_GLOBAL_MASKING } from "@/router/dashboard/workspaceRoutes";
+import { router } from "@/react/router";
+import { WORKSPACE_ROUTE_GLOBAL_MASKING } from "@/react/router/handles";
import { hasWorkspacePermissionV2 } from "@/utils/iam/permission";
export function SensitiveDataIcon() {
diff --git a/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx b/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx
index 93fbba472c..25aaaad6a2 100644
--- a/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx
+++ b/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx
@@ -23,6 +23,7 @@ import { useAppProject } from "@/react/hooks/useAppProject";
import { applyPlanTitleToQuery } from "@/react/lib/plan/title";
import { cn } from "@/react/lib/utils";
import { useNavigate } from "@/react/router";
+import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";
@@ -31,7 +32,6 @@ import {
useCurrentSQLEditorTab,
useIsDisconnected,
} from "@/react/stores/sqlEditor/tab";
-import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";
import { unknownProject } from "@/types";
import {
extractDatabaseResourceName,
diff --git a/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx b/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx
index e041c26cd8..398fe80338 100644
--- a/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx
+++ b/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx
@@ -1,7 +1,7 @@
import { useEffect, useState } from "react";
import { BannersWrapper } from "@/react/components/BannersWrapper";
import { useEnsureWorkspaceCommonData } from "@/react/hooks/useEnsureWorkspaceCommonData";
-import { router } from "@/router";
+import { router } from "@/react/router";
import { provideSheetContext } from "@/views/sql-editor/Sheet";
import { RequestDrawerHost } from "./RequestDrawerHost";
import { SQLEditorRouteShell } from "./SQLEditorRouteShell";
diff --git a/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx b/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx
index 01eba7962c..e0f6749f99 100644
--- a/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx
+++ b/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx
@@ -9,7 +9,14 @@ import {
import { useAppProject } from "@/react/hooks/useAppProject";
import { useClampResultRowsLimitToPolicy } from "@/react/hooks/useSQLEditorBridge";
import { extractWorksheetConnection } from "@/react/lib/sqlEditorConnection";
-import { useCurrentRoute, useNavigate } from "@/react/router";
+import { router, useCurrentRoute, useNavigate } from "@/react/router";
+import {
+ SQL_EDITOR_DATABASE_MODULE,
+ SQL_EDITOR_HOME_MODULE,
+ SQL_EDITOR_INSTANCE_MODULE,
+ SQL_EDITOR_PROJECT_MODULE,
+ SQL_EDITOR_WORKSHEET_MODULE,
+} from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
import type { AsidePanelTab } from "@/react/stores/sqlEditor";
import { useSQLEditorStore } from "@/react/stores/sqlEditor";
@@ -21,14 +28,6 @@ import {
getSQLEditorTabsState,
useSQLEditorTabState,
} from "@/react/stores/sqlEditor/tab";
-import { router } from "@/router";
-import {
- SQL_EDITOR_DATABASE_MODULE,
- SQL_EDITOR_HOME_MODULE,
- SQL_EDITOR_INSTANCE_MODULE,
- SQL_EDITOR_PROJECT_MODULE,
- SQL_EDITOR_WORKSHEET_MODULE,
-} from "@/router/sqlEditor";
import { migrateLegacyCache } from "@/store/modules/sqlEditor/legacy/migration";
import {
DEFAULT_SQL_EDITOR_TAB_MODE,
diff --git a/frontend/src/react/components/sql-editor/SchemaChooser.test.tsx b/frontend/src/react/components/sql-editor/SchemaChooser.test.tsx
index de2953eeee..e7c925def9 100644
--- a/frontend/src/react/components/sql-editor/SchemaChooser.test.tsx
+++ b/frontend/src/react/components/sql-editor/SchemaChooser.test.tsx
@@ -55,7 +55,8 @@ vi.mock("@/utils", () => ({
instanceAllowsSchemaScopedQuery: mocks.instanceAllowsSchemaScopedQuery,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: mocks.router,
}));
diff --git a/frontend/src/react/components/sql-editor/SchemaChooser.tsx b/frontend/src/react/components/sql-editor/SchemaChooser.tsx
index 5fccdab357..cf0b455cb0 100644
--- a/frontend/src/react/components/sql-editor/SchemaChooser.tsx
+++ b/frontend/src/react/components/sql-editor/SchemaChooser.tsx
@@ -1,8 +1,8 @@
import { useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useAppDatabaseMetadata } from "@/react/hooks/useAppDatabaseMetadata";
+import { useReactiveRoute } from "@/react/hooks/useReactiveRoute";
import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";
-import { useVueRoute } from "@/react/hooks/useVueRoute";
import {
getSQLEditorTabsState,
useSQLEditorTabState,
@@ -69,7 +69,7 @@ export function SchemaChooser() {
// tracked both `route.query.schema` and `tab.value` (the latter via the
// setter's reactive reads) so that switching to a new tab with the URL
// query still present re-seeded the new tab's connection.schema.
- const queryParam = useVueRoute().query.schema as string | undefined;
+ const queryParam = useReactiveRoute().query.schema as string | undefined;
const currentTabId = useSQLEditorTabState((s) => s.currentTabId);
useEffect(() => {
if (queryParam) handleChange(queryParam);
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.test.tsx b/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.test.tsx
index 95c18ae938..87218a9d84 100644
--- a/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.test.tsx
+++ b/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.test.tsx
@@ -163,7 +163,10 @@ vi.mock("@/react/components/instance/constants", () => ({
EngineIconPath: { MYSQL: "/mysql.svg" } as Record<string, string>,
}));
-vi.mock("@/router", () => ({ router: { resolve: () => ({ href: "/" }) } }));
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
+ router: { resolve: () => ({ href: "/" }) },
+}));
vi.mock("@/router/sqlEditor", () => ({
SQL_EDITOR_DATABASE_MODULE: "sql-editor.database",
}));
@@ -250,10 +253,6 @@ vi.mock("@/react/components/ui/tree-utils", () => ({
countVisibleRows: () => 0,
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: <T,>(getter: () => T): T => getter(),
-}));
-
let SchemaPane: typeof import("./SchemaPane").SchemaPane;
const renderInto = (element: ReactElement) => {
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/actions.test.tsx b/frontend/src/react/components/sql-editor/SchemaPane/actions.test.tsx
index be1789bf34..7c93cefb66 100644
--- a/frontend/src/react/components/sql-editor/SchemaPane/actions.test.tsx
+++ b/frontend/src/react/components/sql-editor/SchemaPane/actions.test.tsx
@@ -130,16 +130,13 @@ vi.mock("@/types/proto-es/v1/database_service_pb", () => ({
GetSchemaStringRequest_ObjectType: { TABLE: 1, VIEW: 2 },
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
resolve: () => ({ href: "/sql-editor/db" }),
},
}));
-vi.mock("@/router/sqlEditor", () => ({
- SQL_EDITOR_DATABASE_MODULE: "sql-editor.database",
-}));
-
vi.mock("@/react/lib/keyWithPosition", () => ({
keyWithPosition: (k: string, p: number) => `${k}###${p}`,
}));
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx b/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx
index 8bf43bf1a6..7bd952e03e 100644
--- a/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx
+++ b/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx
@@ -18,10 +18,10 @@ import { useTranslation } from "react-i18next";
import { formatSQL } from "@/react/components/monaco/sqlFormatter";
import { useExecuteSQL } from "@/react/hooks/useExecuteSQL";
import { keyWithPosition } from "@/react/lib/keyWithPosition";
+import { router } from "@/react/router";
+import { SQL_EDITOR_DATABASE_MODULE } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";
-import { router } from "@/router";
-import { SQL_EDITOR_DATABASE_MODULE } from "@/router/sqlEditor";
import {
DEFAULT_SQL_EDITOR_TAB_MODE,
dialectOfEngineV1,
diff --git a/frontend/src/react/components/sql-editor/SharePopoverBody.test.tsx b/frontend/src/react/components/sql-editor/SharePopoverBody.test.tsx
index 52fdfdc838..195db8fd5f 100644
--- a/frontend/src/react/components/sql-editor/SharePopoverBody.test.tsx
+++ b/frontend/src/react/components/sql-editor/SharePopoverBody.test.tsx
@@ -9,7 +9,6 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
- usePiniaBridge: vi.fn<(getter: () => unknown) => unknown>(),
serverInfo: { externalUrl: "https://example.com" } as
| { externalUrl: string }
| undefined,
@@ -30,10 +29,6 @@ vi.mock("react-i18next", () => ({
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/react/hooks/usePiniaBridge", () => ({
- usePiniaBridge: mocks.usePiniaBridge,
-}));
-
vi.mock("@/react/hooks/useAppState", () => ({
useCurrentUser: mocks.useCurrentUser,
}));
@@ -73,7 +68,8 @@ vi.mock("@/utils", () => ({
extractWorksheetID: mocks.extractWorksheetID,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
resolve: mocks.routerResolve,
},
@@ -151,8 +147,6 @@ beforeEach(async () => {
mocks.patchWorksheet.mockResolvedValue({});
mocks.tabStatus = "CLEAN";
- mocks.usePiniaBridge.mockImplementation((getter: () => unknown) => getter());
-
// Mock clipboard
Object.defineProperty(navigator, "clipboard", {
value: { writeText: vi.fn().mockResolvedValue(undefined) },
@@ -201,9 +195,6 @@ describe("SharePopoverBody", () => {
name: "users/[email protected]",
});
- mocks.usePiniaBridge.mockImplementation((getter: () => unknown) =>
- getter()
- );
const { container, render, unmount } = renderIntoContainer(
<SharePopoverBody worksheet={mockWorksheet as never} />
@@ -264,9 +255,6 @@ describe("SharePopoverBody", () => {
test("copy button disabled when currentTab status is not CLEAN", () => {
mocks.tabStatus = "DIRTY";
- mocks.usePiniaBridge.mockImplementation((getter: () => unknown) =>
- getter()
- );
const { container, render, unmount } = renderIntoContainer(
<SharePopoverBody worksheet={mockWorksheet as never} />
diff --git a/frontend/src/react/components/sql-editor/SharePopoverBody.tsx b/frontend/src/react/components/sql-editor/SharePopoverBody.tsx
index a9fa2b0dbc..00fffd938a 100644
--- a/frontend/src/react/components/sql-editor/SharePopoverBody.tsx
+++ b/frontend/src/react/components/sql-editor/SharePopoverBody.tsx
@@ -15,10 +15,10 @@ import {
} from "@/react/components/ui/popover";
import { useCurrentUser } from "@/react/hooks/useAppState";
import { cn } from "@/react/lib/utils";
+import { router } from "@/react/router";
+import { SQL_EDITOR_WORKSHEET_MODULE } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
import { useSQLEditorTabState } from "@/react/stores/sqlEditor/tab";
-import { router } from "@/router";
-import { SQL_EDITOR_WORKSHEET_MODULE } from "@/router/sqlEditor";
import type { Worksheet } from "@/types/proto-es/v1/worksheet_service_pb";
import { Worksheet_Visibility } from "@/types/proto-es/v1/worksheet_service_pb";
import { extractProjectResourceName, extractWorksheetID } from "@/utils";
diff --git a/frontend/src/react/components/sql-editor/TreeNodeSuffix.test.tsx b/frontend/src/react/components/sql-editor/TreeNodeSuffix.test.tsx
index 9e1b9d040c..eaa7f5ed57 100644
--- a/frontend/src/react/components/sql-editor/TreeNodeSuffix.test.tsx
+++ b/frontend/src/react/components/sql-editor/TreeNodeSuffix.test.tsx
@@ -18,7 +18,6 @@ globalThis.ResizeObserver = class ResizeObserver {
const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({ t: (key: string) => key })),
- usePiniaBridge: vi.fn<(getter: () => unknown) => unknown>(),
getSQLEditorTabsState: vi.fn(),
getWorksheetByName: vi.fn<(name: string) => unknown>(),
getUserByIdentifier: vi.fn<() => { title: string } | undefined>(() => ({
@@ -32,10 +31,6 @@ vi.mock("react-i18next", () => ({
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/react/hooks/usePiniaBridge", () => ({
- usePiniaBridge: mocks.usePiniaBridge,
-}));
-
vi.mock("@/react/stores/app", () => {
const state = {
getWorksheetByName: mocks.getWorksheetByName,
@@ -132,7 +127,6 @@ const renderIntoContainer = (element: React.ReactElement) => {
let TreeNodeSuffix: typeof import("./TreeNodeSuffix").TreeNodeSuffix;
beforeEach(async () => {
- mocks.usePiniaBridge.mockImplementation((getter: () => unknown) => getter());
mocks.getWorksheetByName.mockImplementation((name: string) => ({
name,
starred: false,
diff --git a/frontend/src/react/components/sql-editor/Welcome.test.tsx b/frontend/src/react/components/sql-editor/Welcome.test.tsx
index 013b431612..3ed5ea0cd2 100644
--- a/frontend/src/react/components/sql-editor/Welcome.test.tsx
+++ b/frontend/src/react/components/sql-editor/Welcome.test.tsx
@@ -21,6 +21,7 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: mocks.useTranslation,
}));
@@ -36,15 +37,11 @@ vi.mock("@/react/hooks/useAppProject", () => ({
useAppProject: () => mocks.projectData,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: { push: mocks.routerPush },
}));
-vi.mock("@/router/dashboard/workspaceRoutes", () => ({
- INSTANCE_ROUTE_DASHBOARD: "workspace.instance",
- PROJECT_V1_ROUTE_DASHBOARD: "workspace.project",
-}));
-
vi.mock("@/store", () => ({
useProjectV1Store: vi.fn(),
}));
diff --git a/frontend/src/react/components/sql-editor/Welcome.tsx b/frontend/src/react/components/sql-editor/Welcome.tsx
index 903448345d..d0f1ae9467 100644
--- a/frontend/src/react/components/sql-editor/Welcome.tsx
+++ b/frontend/src/react/components/sql-editor/Welcome.tsx
@@ -3,9 +3,9 @@ import { useTranslation } from "react-i18next";
import { BytebaseLogo } from "@/react/components/BytebaseLogo";
import { usePermissionCheck } from "@/react/components/PermissionGuard";
import { useAppProject } from "@/react/hooks/useAppProject";
+import { router } from "@/react/router";
+import { INSTANCE_ROUTE_DASHBOARD } from "@/react/router/handles";
import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";
-import { router } from "@/router";
-import { INSTANCE_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";
import { WelcomeButton } from "./WelcomeButton";
export type WelcomeProps = {
diff --git a/frontend/src/react/components/sql-review/ResourceLink.tsx b/frontend/src/react/components/sql-review/ResourceLink.tsx
index 2ecdc1d93d..88d56c7213 100644
--- a/frontend/src/react/components/sql-review/ResourceLink.tsx
+++ b/frontend/src/react/components/sql-review/ResourceLink.tsx
@@ -1,9 +1,9 @@
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
+import { router } from "@/react/router";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
import {
environmentNamePrefix,
projectNamePrefix,
@@ -50,9 +50,7 @@ function ProjectResourceLink({ resource }: { resource: string }) {
}
}, [resource]);
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(resource)
- );
+ const project = useProjectByName(resource);
void projectsByName;
return (
diff --git a/frontend/src/react/components/sql-review/ReviewCreation.tsx b/frontend/src/react/components/sql-review/ReviewCreation.tsx
index 136bca8a50..87b5beed22 100644
--- a/frontend/src/react/components/sql-review/ReviewCreation.tsx
+++ b/frontend/src/react/components/sql-review/ReviewCreation.tsx
@@ -7,12 +7,12 @@ import { ResourceIdField } from "@/react/components/ResourceIdField";
import { Button } from "@/react/components/ui/button";
import { Input } from "@/react/components/ui/input";
import { getTemplateId } from "@/react/lib/sql-review/utils";
-import { useSQLReviewStore } from "@/react/stores/sqlReview";
-import { router } from "@/router";
+import { router } from "@/react/router";
import {
WORKSPACE_ROUTE_SQL_REVIEW,
WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,
-} from "@/router/dashboard/workspaceRoutes";
+} from "@/react/router/handles";
+import { useSQLReviewStore } from "@/react/stores/sqlReview";
import { pushNotification } from "@/store";
import {
getReviewConfigId,
diff --git a/frontend/src/react/components/sql-review/TemplateSelector.test.tsx b/frontend/src/react/components/sql-review/TemplateSelector.test.tsx
index 534993147d..91cf2afd18 100644
--- a/frontend/src/react/components/sql-review/TemplateSelector.test.tsx
+++ b/frontend/src/react/components/sql-review/TemplateSelector.test.tsx
@@ -23,7 +23,6 @@ const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({
t: (key: string) => key,
})),
- useVueState: vi.fn((getter: () => unknown) => getter()),
rulesToTemplate: vi.fn(() => reviewTemplate),
getOrFetchProjectByName: vi.fn(),
getProjectByName: vi.fn(() => undefined),
@@ -33,13 +32,10 @@ const mocks = vi.hoisted(() => ({
let TemplateSelector: typeof import("./TemplateSelector").TemplateSelector;
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
vi.mock("@/react/lib/sql-review/utils", () => ({
rulesToTemplate: mocks.rulesToTemplate,
}));
@@ -107,8 +103,6 @@ beforeEach(async () => {
mocks.useTranslation.mockReturnValue({
t: (key: string) => key,
});
- mocks.useVueState.mockReset();
- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
mocks.rulesToTemplate.mockReset();
mocks.rulesToTemplate.mockReturnValue(reviewTemplate);
mocks.getOrFetchProjectByName.mockReset();
diff --git a/frontend/src/react/components/sql-review/TemplateSelector.tsx b/frontend/src/react/components/sql-review/TemplateSelector.tsx
index 5e43b42ffb..41bc000bbb 100644
--- a/frontend/src/react/components/sql-review/TemplateSelector.tsx
+++ b/frontend/src/react/components/sql-review/TemplateSelector.tsx
@@ -4,7 +4,7 @@ import { useTranslation } from "react-i18next";
import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";
import { Badge } from "@/react/components/ui/badge";
import { Separator } from "@/react/components/ui/separator";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { rulesToTemplate } from "@/react/lib/sql-review/utils";
import { cn } from "@/react/lib/utils";
import { useAppStore } from "@/react/stores/app";
@@ -40,11 +40,10 @@ function ResourceBadge({ resource }: { resource: string }) {
}
}, [resource]);
- const projectTitle = useVueState(() =>
- resource.startsWith(projectNamePrefix)
- ? useAppStore.getState().getProjectByName(resource)?.title
- : undefined
- );
+ const projectFromResource = useProjectByName(resource);
+ const projectTitle = resource.startsWith(projectNamePrefix)
+ ? projectFromResource?.title
+ : undefined;
void projectsByName;
if (resource.startsWith(environmentNamePrefix)) {
@@ -79,7 +78,7 @@ export function TemplateSelector({
}: TemplateSelectorProps) {
const { t } = useTranslation();
const sqlReviewStore = useSQLReviewStore();
- const policyList = useVueState(() => [...sqlReviewStore.reviewPolicyList]);
+ const policyList = sqlReviewStore.reviewPolicyList;
useEffect(() => {
sqlReviewStore.fetchReviewPolicyList();
diff --git a/frontend/src/react/components/task-run-log/model.test.ts b/frontend/src/react/components/task-run-log/model.test.ts
index 15b2ed54ea..ba5ece80ac 100644
--- a/frontend/src/react/components/task-run-log/model.test.ts
+++ b/frontend/src/react/components/task-run-log/model.test.ts
@@ -31,10 +31,6 @@ vi.mock("@/connect", () => ({
sheetServiceClientConnect: {},
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: () => undefined,
-}));
-
vi.mock("@/react/stores/app", () => ({
useAppStore: () => vi.fn(),
}));
diff --git a/frontend/src/react/components/ui/feature-modal.test.tsx b/frontend/src/react/components/ui/feature-modal.test.tsx
index 103b572e2c..aec9b8df01 100644
--- a/frontend/src/react/components/ui/feature-modal.test.tsx
+++ b/frontend/src/react/components/ui/feature-modal.test.tsx
@@ -28,14 +28,11 @@ vi.mock("@/react/stores/app", () => ({
useAppStore: mocks.useAppStore,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: { push: vi.fn() },
}));
-vi.mock("@/router/dashboard/workspaceRoutes", () => ({
- INSTANCE_ROUTE_DASHBOARD: "workspace.instance",
-}));
-
vi.mock("@/types", () => ({
ENTERPRISE_INQUIRE_LINK: "https://enterprise",
}));
diff --git a/frontend/src/react/components/ui/feature-modal.tsx b/frontend/src/react/components/ui/feature-modal.tsx
index c7b464769f..724f6153c5 100644
--- a/frontend/src/react/components/ui/feature-modal.tsx
+++ b/frontend/src/react/components/ui/feature-modal.tsx
@@ -8,9 +8,9 @@ import {
DialogTitle,
} from "@/react/components/ui/dialog";
import { useSubscriptionState } from "@/react/hooks/useAppState";
+import { router } from "@/react/router";
+import { INSTANCE_ROUTE_DASHBOARD } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { INSTANCE_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";
import { ENTERPRISE_INQUIRE_LINK } from "@/types";
import type {
Instance,
diff --git a/frontend/src/react/hooks/useExecuteSQL.ts b/frontend/src/react/hooks/useExecuteSQL.ts
index b7a815ff9d..ffed255fa4 100644
--- a/frontend/src/react/hooks/useExecuteSQL.ts
+++ b/frontend/src/react/hooks/useExecuteSQL.ts
@@ -5,6 +5,7 @@ import { useCallback, useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { v4 as uuidv4 } from "uuid";
import { isConnectedSQLEditorTab } from "@/react/lib/sqlEditorConnection";
+import { getValidDataSourceByPolicy } from "@/react/lib/sqlEditorDataSource";
import { useAppStore } from "@/react/stores/app";
import { useSQLEditorStore as useSQLEditorReactStore } from "@/react/stores/sqlEditor";
import { getSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";
@@ -33,7 +34,6 @@ import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import {
getDatabaseProject,
getInstanceResource,
- getValidDataSourceByPolicy,
hasPermissionToCreateChangeDatabaseIssueInProject,
} from "@/utils";
import { flattenNoSQLResult } from "@/utils/sqlResult";
@@ -369,8 +369,8 @@ export const useExecuteSQL = () => {
// they had already loaded ("Load more"d), and the new entry just
// gets prepended. After the cache update lands, emit the event so
// the HistoryPane re-renders from it (store reactivity alone
- // doesn't reliably propagate into the React `useVueState`
- // subscriber, so we trigger the re-render explicitly).
+ // doesn't reliably propagate into the React subscriber, so we
+ // trigger the re-render explicitly).
useSQLEditorReactStore
.getState()
.mergeLatest({
diff --git a/frontend/src/react/hooks/usePiniaBridge.ts b/frontend/src/react/hooks/usePiniaBridge.ts
deleted file mode 100644
index 933bcfcd8f..0000000000
--- a/frontend/src/react/hooks/usePiniaBridge.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { type UseVueStateOptions, useVueState } from "./useVueState";
-
-/**
- * React-native bridge for reading Pinia store state (and any other Vue
- * reactive source) from React components. Functionally identical to
- * `useVueState` — the rename exists so the SQL editor migration's
- * acceptance grep (`useVueState\b` in `react/components/sql-editor/**`)
- * stays empty without requiring an out-of-scope migration of every
- * upstream Pinia store to Zustand.
- *
- * Use this for any Vue reactive read that lives outside the SQL editor's
- * own state stores (editor/tab Zustand). Examples:
- * - Pinia store reads: `usePiniaBridge(() => projectStore.getProjectByName(name))`
- * - Sheet-context Vue refs: `usePiniaBridge(() => sheetContext.filterChanged.value)`
- * - Feature flag helpers: `usePiniaBridge(() => hasFeature(PlanFeature.X))`
- * - Per-user `Ref<User>`: `usePiniaBridge(() => userRef.value)`
- *
- * Re-renders fire whenever Vue's reactivity detects a change in any
- * reactive dependency touched by the getter (including in-place
- * mutations on Pinia store proxies and `useCache` entity maps).
- *
- * Pass `{ deep: true }` only when the getter returns a collection
- * whose nested fields the getter doesn't read directly — see the
- * `useVueState` JSDoc for the full reactivity contract.
- */
-export function usePiniaBridge<T>(
- getter: () => T,
- options?: UseVueStateOptions
-): T {
- return useVueState(getter, options);
-}
diff --git a/frontend/src/react/hooks/useProjectByName.ts b/frontend/src/react/hooks/useProjectByName.ts
new file mode 100644
index 0000000000..cf070f4ad4
--- /dev/null
+++ b/frontend/src/react/hooks/useProjectByName.ts
@@ -0,0 +1,22 @@
+import { useMemo } from "react";
+import { useAppStore } from "@/react/stores/app";
+import type { Project } from "@/types/proto-es/v1/project_service_pb";
+
+/**
+ * Reactively resolve a project by resource name from the app store, always
+ * returning a non-null `Project` (the store synthesizes the unknown/default
+ * placeholder on a cache miss).
+ *
+ * `getProjectByName` returns a FRESH placeholder object on every cache miss, so
+ * it must NOT be used directly as a Zustand selector — `Object.is` would never
+ * match and the component would re-render forever. Instead we subscribe to the
+ * stable `projectsByName` map and recompute through `getProjectByName` only
+ * when the map (or the name) changes, yielding a stable reference per render.
+ */
+export function useProjectByName(name: string): Project {
+ const projectsByName = useAppStore((s) => s.projectsByName);
+ return useMemo(
+ () => useAppStore.getState().getProjectByName(name),
+ [projectsByName, name]
+ );
+}
diff --git a/frontend/src/react/hooks/useReactiveRoute.ts b/frontend/src/react/hooks/useReactiveRoute.ts
new file mode 100644
index 0000000000..c119dcf8a8
--- /dev/null
+++ b/frontend/src/react/hooks/useReactiveRoute.ts
@@ -0,0 +1,24 @@
+import { useSyncExternalStore } from "react";
+import type { ReactRoute } from "@/react/router";
+import { router } from "@/react/router";
+
+// `router.afterEach` returns its own unregister fn — wraps it as a React
+// `useSyncExternalStore` subscription so route changes trigger re-renders
+// off the react-router data router.
+const subscribe = (onChange: () => void): (() => void) =>
+ router.afterEach(() => onChange());
+
+// `router.currentRoute.value` is memoized at the router level — it returns a
+// referentially stable object between actual route changes — so it satisfies
+// `useSyncExternalStore`'s requirement that `getSnapshot` be cached (otherwise
+// React re-renders forever: "The result of getSnapshot should be cached").
+const getSnapshot = (): ReactRoute => router.currentRoute.value;
+
+/**
+ * Reactively reads the current route, re-rendering on navigation (URL
+ * changes, param updates). Backed by the react-router data router via the
+ * `@/react/router` shim.
+ */
+export const useReactiveRoute = (): ReactRoute => {
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+};
diff --git a/frontend/src/react/hooks/useRecentVisit.ts b/frontend/src/react/hooks/useRecentVisit.ts
new file mode 100644
index 0000000000..76797b6cb7
--- /dev/null
+++ b/frontend/src/react/hooks/useRecentVisit.ts
@@ -0,0 +1,79 @@
+import { useCallback } from "react";
+import { useAppStore } from "@/react/stores/app";
+import { projectNamePrefix } from "@/store/modules/v1/common";
+import { storageKeyRecentVisit, workspaceCacheScope } from "@/utils";
+
+const MAX_HISTORY = 10;
+
+// Two URLs are "the same" visit when their paths match (ignoring querystring
+// and hash) — usually just different tab-panes or filters on the same page.
+function getPath(url: string): string {
+ return url.replace(/[?#].*$/, "");
+}
+
+// React port of the Vue `@/router/useRecentVisit` composable. Maintains the
+// per-user recent-visit list in localStorage under the same scoped key + JSON
+// array format as the Vue version (`@vueuse` useStorage), so the two remain
+// interoperable during the migration.
+export function useRecentVisit() {
+ const isSaaSMode = useAppStore((s) => s.isSaaSMode());
+ const currentUser = useAppStore((s) => s.currentUser);
+ const storageKey = storageKeyRecentVisit(
+ workspaceCacheScope(isSaaSMode, currentUser?.workspace ?? ""),
+ currentUser?.email ?? ""
+ );
+
+ const read = useCallback((): string[] => {
+ try {
+ const raw = localStorage.getItem(storageKey);
+ const parsed = raw ? JSON.parse(raw) : [];
+ return Array.isArray(parsed) ? parsed : [];
+ } catch {
+ return [];
+ }
+ }, [storageKey]);
+
+ const write = useCallback(
+ (list: string[]) => {
+ localStorage.setItem(storageKey, JSON.stringify(list));
+ },
+ [storageKey]
+ );
+
+ const remove = useCallback(
+ (path: string) => {
+ const list = read();
+ const index = list.findIndex((item) => getPath(item) === getPath(path));
+ if (index >= 0) {
+ list.splice(index, 1);
+ write(list);
+ }
+ },
+ [read, write]
+ );
+
+ const record = useCallback(
+ (path: string) => {
+ const list = read();
+ // Pull out an existing entry for the current page before re-inserting.
+ const index = list.findIndex((item) => getPath(item) === getPath(path));
+ if (index >= 0) {
+ list.splice(index, 1);
+ }
+ // Current page is always first, so cap at MAX_HISTORY + 1.
+ while (list.length > MAX_HISTORY + 1) {
+ list.pop();
+ }
+ list.unshift(path);
+ write(list);
+ },
+ [read, write]
+ );
+
+ const list = read();
+ const lastVisit = list.length > 0 ? list[0] : undefined;
+ const lastVisitProjectPath =
+ list.find((visit) => visit.startsWith(`/${projectNamePrefix}`)) ?? "";
+
+ return { remove, record, lastVisit, lastVisitProjectPath };
+}
diff --git a/frontend/src/react/hooks/useUnsavedChangesGuard.ts b/frontend/src/react/hooks/useUnsavedChangesGuard.ts
index 06b352e85f..9ee7421751 100644
--- a/frontend/src/react/hooks/useUnsavedChangesGuard.ts
+++ b/frontend/src/react/hooks/useUnsavedChangesGuard.ts
@@ -1,6 +1,6 @@
import { useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
-import { router } from "@/router";
+import { router } from "@/react/router";
/**
* Warn the user before they lose unsaved edits.
diff --git a/frontend/src/react/hooks/useVueRoute.ts b/frontend/src/react/hooks/useVueRoute.ts
deleted file mode 100644
index 8206475a10..0000000000
--- a/frontend/src/react/hooks/useVueRoute.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { useCallback, useSyncExternalStore } from "react";
-import type { RouteLocationNormalizedLoaded } from "vue-router";
-import { router } from "@/router";
-
-// `router.afterEach` returns its own unregister fn — wraps it as a React
-// `useSyncExternalStore` subscription so route changes trigger re-renders
-// without dragging Vue's reactivity (`useVueState` / `usePiniaBridge`)
-// into the consumer.
-const subscribe = (onChange: () => void): (() => void) =>
- router.afterEach(() => onChange());
-
-const getSnapshot = (): RouteLocationNormalizedLoaded =>
- router.currentRoute.value;
-
-/**
- * Reactively reads the current Vue Router route. Use when a React
- * component needs to re-render on navigation (URL changes, param updates)
- * without subscribing to Vue's reactive system.
- */
-export const useVueRoute = (): RouteLocationNormalizedLoaded => {
- const subscribeFn = useCallback(subscribe, []);
- return useSyncExternalStore(subscribeFn, getSnapshot, getSnapshot);
-};
diff --git a/frontend/src/react/hooks/useVueState.ts b/frontend/src/react/hooks/useVueState.ts
deleted file mode 100644
index 363a332fed..0000000000
--- a/frontend/src/react/hooks/useVueState.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-import { type DependencyList, useEffect, useRef, useState } from "react";
-import { watch } from "vue";
-
-const EMPTY_DEPS: DependencyList = [];
-
-export interface UseVueStateOptions {
- /**
- * Force the watch to traverse nested reactive properties when
- * registering deps. Default `false`.
- *
- * Set this to `true` when the getter returns a reactive object/Map/
- * Set whose **nested fields** mutate in place (e.g. a collection
- * getter where consumers also read item fields). Without it, Vue's
- * watch only tracks the top-level reactive accesses the getter made
- * during evaluation.
- *
- * Note: this hook ALREADY surfaces in-place mutations of fields read
- * by the getter — those reads register Vue deps individually, and a
- * mutation to any of them triggers a re-render via the version
- * counter even when the getter's *return reference* is unchanged.
- * `deep: true` is only needed for collections whose contents the
- * getter doesn't read directly.
- */
- readonly deep?: boolean;
- /**
- * Re-subscribe the underlying `watch` whenever these values change.
- * Default `[]` (subscribe once on mount).
- *
- * The watch normally tracks only the Vue deps the getter touched on
- * its first run. When the getter's *target* changes identity through
- * a NON-Vue signal — e.g. the getter reads `chatInfo.list.value`
- * where `chatInfo` is selected from a Zustand store — Vue never sees
- * that swap, so the watch keeps tracking the previous target's refs
- * and misses in-place mutations of the new one. Pass the swapping
- * value(s) here so the watch tears down and re-tracks the current
- * target. The render-time `getter()` read is always fresh regardless;
- * `deps` is only about keeping the *subscription* pointed at the
- * right reactive source between renders.
- *
- * Length must stay constant across renders (React's rules of hooks).
- */
- readonly deps?: DependencyList;
-}
-
-/**
- * Subscribe a React component to a Vue reactive getter.
- *
- * Re-renders whenever:
- * 1. Vue's `watch` fires (any reactive dep accessed by the getter
- * changed — including in-place field mutations of objects the
- * getter reads), OR
- * 2. The getter's closure variables (props, local state, etc.)
- * change in a way that produces a different return value.
- *
- * Why a version counter rather than `useSyncExternalStore`'s snapshot
- * compare: Pinia stores typically mutate proxy objects in place via
- * `Object.assign(tab, payload)` or per-field writes. A getter that
- * returns the proxy itself (e.g. `() => tabStore.currentTab`) keeps
- * returning the same reference across mutations, and a snapshot
- * comparison via `Object.is` would skip the re-render even though Vue
- * detected a change. The version counter forces React to commit a new
- * render whenever Vue's watch callback fires, regardless of the
- * snapshot reference.
- *
- * @example
- * // Reads a primitive — version bump and value change agree.
- * const url = useVueState(() => actuatorStore.serverInfo?.externalUrl ?? "");
- *
- * @example
- * // Reads a proxy object that mutates in place — the version bump
- * // is what makes consumers see the new field values.
- * const tab = useVueState(() => tabStore.currentTab);
- * const isEmpty = !tab || tab.statement === "";
- *
- * @example
- * // Deep-tracks nested collections the getter doesn't read directly.
- * const queryList = useVueState(
- * () => webTerminalStore.getQueryStateByTab(tab).queryItemList.value,
- * { deep: true }
- * );
- */
-export function useVueState<T>(
- getter: () => T,
- options?: UseVueStateOptions
-): T {
- // Always read the latest getter from the closure (props, local state,
- // etc. may have updated since mount).
- const getterRef = useRef(getter);
- getterRef.current = getter;
-
- // Pulling the deep flag through a ref keeps the watch wiring stable
- // across re-renders. Flipping it post-mount isn't supported — that
- // would require resubscribing.
- const deepRef = useRef(!!options?.deep);
-
- // Version bumps from the watch callback; React's `useState` setter
- // triggers a re-render even when the underlying Pinia object's
- // reference is unchanged (in-place mutation case).
- const [, setVersion] = useState(0);
-
- useEffect(() => {
- const stop = watch(
- () => getterRef.current(),
- () => setVersion((v) => v + 1),
- { flush: "sync", deep: deepRef.current }
- );
- return () => {
- stop();
- };
- // `deps` (default []) lets callers force re-subscription when the
- // getter's reactive target is swapped via a non-Vue signal.
- }, options?.deps ?? EMPTY_DEPS);
-
- // Read the live value at render time. The watch above guarantees a
- // re-render fires after every Vue mutation, so this read sees the
- // freshly-mutated state on the next render.
- return getter();
-}
diff --git a/frontend/src/react/lib/plan/issue.ts b/frontend/src/react/lib/plan/issue.ts
index c56dac9f50..74cb8603a3 100644
--- a/frontend/src/react/lib/plan/issue.ts
+++ b/frontend/src/react/lib/plan/issue.ts
@@ -1,6 +1,6 @@
+import { router } from "@/react/router";
+import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";
import { isValidDatabaseGroupName, isValidDatabaseName } from "@/types";
import {
extractDatabaseGroupName,
diff --git a/frontend/src/react/lib/sqlEditorDataSource.ts b/frontend/src/react/lib/sqlEditorDataSource.ts
new file mode 100644
index 0000000000..7e006c8b2c
--- /dev/null
+++ b/frontend/src/react/lib/sqlEditorDataSource.ts
@@ -0,0 +1,39 @@
+import { head } from "lodash-es";
+import { useAppStore } from "@/react/stores/app";
+import type { QueryDataSourceType } from "@/types";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import { DataSourceType } from "@/types/proto-es/v1/instance_service_pb";
+import { PolicyType } from "@/types/proto-es/v1/org_policy_service_pb";
+import { getInstanceResource } from "@/utils/v1/database";
+
+// Picks the data-source id for a query, honoring the workspace DATA_QUERY
+// policy's `allowAdminDataSource`. Reads the React app store directly (the
+// legacy `@/utils/sqlEditor` version used the Pinia `useQueryDataPolicy`
+// composable, whose store is not populated in the React shell — so admin data
+// sources were never selectable). `allowAdminDataSource` is a workspace-level
+// flag (the legacy policy getter took it from the workspace policy only).
+export const getValidDataSourceByPolicy = async (
+ database: Database,
+ type?: QueryDataSourceType
+): Promise<string> => {
+ const instanceResource = getInstanceResource(database);
+ const adminDataSource = instanceResource.dataSources.find(
+ (ds) => ds.type === DataSourceType.ADMIN
+ )!;
+ const readonlyDataSources = instanceResource.dataSources.filter(
+ (ds) => ds.type === DataSourceType.READ_ONLY
+ );
+
+ const store = useAppStore.getState();
+ const workspace = store.workspaceResourceName();
+ await store.getOrFetchPolicyByParentAndType({
+ parentPath: workspace,
+ policyType: PolicyType.DATA_QUERY,
+ });
+ const { allowAdminDataSource } = store.getQueryDataPolicyByParent(workspace);
+
+ if (allowAdminDataSource && type === DataSourceType.ADMIN) {
+ return adminDataSource.id;
+ }
+ return head(readonlyDataSources)?.id ?? adminDataSource.id;
+};
diff --git a/frontend/src/react/lib/workspace.ts b/frontend/src/react/lib/workspace.ts
new file mode 100644
index 0000000000..e0f69395b6
--- /dev/null
+++ b/frontend/src/react/lib/workspace.ts
@@ -0,0 +1,21 @@
+import { useAppStore } from "@/react/stores/app";
+
+/**
+ * Resolve the active workspace resource name for auth flows (signin, MFA,
+ * password reset/forgot, OAuth callback). Prefers the app store's resolved
+ * workspace (from server info); falls back to the `?workspace=<id>` URL query.
+ *
+ * Lives in the React layer (not `@/utils`) because it reads the Zustand app
+ * store — keeping the app-store import out of the low-level `@/utils` barrel,
+ * which app-store slices themselves import (avoids a load-time cycle).
+ */
+export const resolveWorkspaceName = (): string | undefined => {
+ const workspaceID =
+ new URLSearchParams(window.location.search).get("workspace") ?? undefined;
+ const workspaceNameFromQuery = workspaceID
+ ? `workspaces/${workspaceID}`
+ : undefined;
+ return (
+ useAppStore.getState().workspaceResourceName() || workspaceNameFromQuery
+ );
+};
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index 4150524666..6366e941ca 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -113,6 +113,10 @@
"stay-signed-in": "Stay signed in",
"title": "Your session is about to end"
},
+ "login-as-another": {
+ "content": "We will redirect you to the home page.",
+ "title": "You have logged in as another user"
+ },
"oauth-callback": {
"invalid-state": "Authentication failed: Invalid callback state. Please try again.",
"opener-failed": "Authentication completed, but failed to communicate with the parent window. Please close this window and try again.",
@@ -157,6 +161,7 @@
"existing-user": "Already have an account?",
"title": "Register your account"
},
+ "token-expired-description": "Token has expired, please login again",
"token-expired-title": "Token expired"
},
"banner": {
@@ -228,6 +233,7 @@
"back-to-workspace": "Back to workspace",
"bypassed": "Bypassed",
"cancel": "Cancel",
+ "canceled": "Canceled",
"cannot-undo-this-action": "You cannot undo this action",
"catalog": "Catalog",
"changelog": "Changelog",
@@ -272,8 +278,10 @@
"deselect-all": "Deselect all",
"detail": "Detail",
"detailed-guide": "detailed guide",
+ "dingtalk": "DingTalk",
"disable": "Disable",
"discard-changes": "Discard changes",
+ "discord": "Discord",
"dismiss": "Dismiss",
"done": "Done",
"download": "Download",
@@ -295,6 +303,7 @@
"expired": "Expired",
"export": "Export",
"failed": "Failed",
+ "feishu": "Feishu",
"file-selector": {
"size-limit": "File size should less than {{size}} MiB",
"type-limit": "Only support {{extension}} file"
@@ -305,6 +314,7 @@
"from": "From",
"general": "General",
"go-back": "Go back",
+ "google-chat": "Google Chat",
"group": "Group",
"groups": "Groups",
"history": "History",
@@ -322,6 +332,7 @@
"key": "Key",
"labels": "Labels",
"language": "Language",
+ "lark": "Lark",
"learn-more": "Learn more",
"leave-without-saving": "Leave without saving?",
"license": "License",
@@ -347,6 +358,7 @@
"next": "Next",
"no": "No",
"no-data": "No data",
+ "no-license": "No license",
"not-started": "Not started",
"ok": "OK",
"only-creator-allowed-export": "Only the creator is allowed to export",
@@ -421,6 +433,7 @@
"sign-up": "Sign up",
"skip": "Skip",
"skipped": "Skipped",
+ "slack": "Slack",
"snapshot": "Snapshot",
"sql": "SQL",
"stage": "Stage",
@@ -433,6 +446,7 @@
"system": "System",
"table": "Table",
"task": "Task",
+ "teams": "Teams",
"text-wrap": "Text Wrap",
"tips": "Tips",
"title": "Title",
@@ -465,6 +479,7 @@
"want-help": "Want help",
"warning": "Warning",
"webhooks": "Webhooks",
+ "wecom": "WeCom",
"write-only": "write only",
"yes": "Yes",
"you": "you"
@@ -563,6 +578,7 @@
},
"data-source": {
"additional-node-addresses": "Additional Node Addresses",
+ "admin": "Admin",
"automatic-query-data-source": "Automatic",
"connection-string-schema": "Connection String Schema",
"connection-type": "Connection Type",
@@ -576,6 +592,7 @@
"private-key-passphrase": "Private Key Passphrase",
"private-key-passphrase-placeholder": "Leave empty if your private key is not encrypted",
"private-key-passphrase-tip": "Optional passphrase for encrypted private keys",
+ "read-only": "RO",
"read-replica-host": "Read-replica Host",
"read-replica-port": "Read-replica Port",
"replica-set": "Replica Set",
@@ -1328,6 +1345,7 @@
"change-database": "Change database",
"change-from-sql-editor": "Change from SQL Editor",
"edit-schema": "Edit schema",
+ "export-data": "Export data",
"request-role": "Request role",
"request-specific-role": "Request \"{{role}}\" role"
},
@@ -1382,6 +1400,7 @@
},
"recovery-code": "Recovery code"
},
+ "oauth": {},
"oauth2": {
"consent": {
"description": "{{clientName}} is requesting access to your account",
@@ -1712,6 +1731,32 @@
"name": "Name"
},
"webhook": {
+ "activity-item": {
+ "issue-approval-notify": {
+ "label": "When issue is pending approval",
+ "title": "Issue approval needed"
+ },
+ "issue-approved": {
+ "label": "Notify when all approval steps are completed",
+ "title": "Issue approved"
+ },
+ "issue-creation": {
+ "label": "When new issue has been created",
+ "title": "Issue creation"
+ },
+ "issue-sent-back": {
+ "label": "When issue is sent back by an approver",
+ "title": "Issue sent back"
+ },
+ "pipeline-completed": {
+ "label": "When pipeline completes successfully",
+ "title": "Pipeline completed"
+ },
+ "pipeline-failed": {
+ "label": "When pipeline tasks fail",
+ "title": "Pipeline failed"
+ }
+ },
"activity-support-direct-message": "Support send direct messages to related users",
"creation": {
"desc": "Create the corresponding webhook for the {{destination}} channel receiving the message.",
@@ -1758,6 +1803,7 @@
"visit-member": "Visit Member | Members",
"visit-project": "Visit Projects"
},
+ "refresh-remind": {},
"release": {
"and-n-more-files": "and {{count}} more files",
"change-tip": "This change is linked to a release artifact.",
@@ -1806,10 +1852,30 @@
"custom-roles": {
"self": "Custom roles"
},
+ "gitops-service-agent": {
+ "description": "Permissions for automated CI/CD workflows to create and execute database changes via GitOps.",
+ "self": "GitOps Service Agent"
+ },
"import-from-role": "Import from role",
+ "project-developer": {
+ "description": "All viewer permissions, plus permissions for requesting database changes.",
+ "self": "Project Developer"
+ },
+ "project-owner": {
+ "description": "All permissions within the project",
+ "self": "Project Owner"
+ },
+ "project-releaser": {
+ "description": "All viewer permissions, plus permission for reviewing database change requests for release purposes.",
+ "self": "Project Releaser"
+ },
"project-roles": {
"self": "Project roles"
},
+ "project-viewer": {
+ "description": "Read-only permissions for viewing basic project and database information; users may self-initiate tickets to request data queries and exports.",
+ "self": "Project Viewer"
+ },
"select-role": "Select role",
"self": "Role",
"setting": {
@@ -1817,7 +1883,27 @@
"description-placeholder": "Input role description",
"title-placeholder": "Input role title"
},
+ "sql-editor-read-user": {
+ "description": "Read-only permissions for querying database data, without DDL or DML access.",
+ "self": "SQL Editor Read User"
+ },
+ "sql-editor-user": {
+ "description": "Permissions for querying database data.",
+ "self": "SQL Editor User"
+ },
"title": "Title",
+ "workspace-admin": {
+ "description": "Workspace Admin has all permissions within the workspace.",
+ "self": "Workspace Admin"
+ },
+ "workspace-dba": {
+ "description": "Workspace DBA has all permissions within the workspace except for managing workspace members.",
+ "self": "Workspace DBA"
+ },
+ "workspace-member": {
+ "description": "Workspace Member is the most basic role within the workspace.",
+ "self": "Workspace Member"
+ },
"workspace-roles": {
"self": "Workspace roles"
}
@@ -2516,11 +2602,13 @@
"non-empty-folder-content": "Do you want to move all worksheets into the root folder or just delete them?",
"non-empty-folder-title": "Non-empty folder"
},
+ "mine": "Mine",
"move-worksheets": "Move worksheets",
"notifications": {
"duplicate-success": "Successfully duplicate the worksheet"
},
- "search-sheets": "Search Sheets"
+ "search-sheets": "Search Sheets",
+ "shared": "Shared"
},
"sql-editor": {
"access-grants": "Access Grants",
@@ -3665,6 +3753,7 @@
"skip-task": "Skip task | Skip tasks",
"started": "Started",
"status": {
+ "available": "Available",
"canceled": "Canceled",
"done": "Done",
"failed": "Failed",
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index e9ef6c5119..607ef857d7 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -113,6 +113,10 @@
"stay-signed-in": "Permanecer conectado",
"title": "Tu sesión está a punto de terminar"
},
+ "login-as-another": {
+ "content": "Lo redirigiremos a la página de inicio.",
+ "title": "Has iniciado sesión como otro usuario"
+ },
"oauth-callback": {
"invalid-state": "La autenticación falló: estado de devolución de llamada no válido. Inténtalo de nuevo.",
"opener-failed": "La autenticación se completó, pero no se pudo comunicar con la ventana principal. Cierra esta ventana e inténtalo de nuevo.",
@@ -157,6 +161,7 @@
"existing-user": "¿Ya tienes una cuenta?",
"title": "Registre su cuenta"
},
+ "token-expired-description": "El token ha expirado, por favor inicia sesión nuevamente",
"token-expired-title": "Token expirado"
},
"banner": {
@@ -228,6 +233,7 @@
"back-to-workspace": "Volver al espacio de trabajo",
"bypassed": "Omitido",
"cancel": "Cancelar",
+ "canceled": "Cancelado",
"cannot-undo-this-action": "No se puede deshacer esta acción",
"catalog": "Catálogo",
"changelog": "Changelog",
@@ -272,8 +278,10 @@
"deselect-all": "Deseleccionar todo",
"detail": "Detalle",
"detailed-guide": "guía detallada",
+ "dingtalk": "DingTalk",
"disable": "Deshabilitar",
"discard-changes": "Descartar cambios",
+ "discord": "Discord",
"dismiss": "Descartar",
"done": "Hecho",
"download": "Descargar",
@@ -295,6 +303,7 @@
"expired": "Expirado",
"export": "Exportar",
"failed": "Error",
+ "feishu": "Feishu",
"file-selector": {
"size-limit": "El tamaño del archivo debe ser menor que {{size}} MiB",
"type-limit": "Solo se admiten archivos {{extension}}"
@@ -305,6 +314,7 @@
"from": "Desde",
"general": "General",
"go-back": "Volver",
+ "google-chat": "Google Chat",
"group": "Grupo",
"groups": "Grupos",
"history": "Historial",
@@ -322,6 +332,7 @@
"key": "Clave",
"labels": "Etiquetas",
"language": "Idioma",
+ "lark": "Lark",
"learn-more": "Aprender más",
"leave-without-saving": "¿Salir sin guardar?",
"license": "Licencia",
@@ -347,6 +358,7 @@
"next": "Siguiente",
"no": "No",
"no-data": "Sin datos",
+ "no-license": "Sin licencia",
"not-started": "No iniciado",
"ok": "OK",
"only-creator-allowed-export": "Solo el creador puede exportar",
@@ -421,6 +433,7 @@
"sign-up": "Registrarse",
"skip": "Omitir",
"skipped": "Omitido",
+ "slack": "Slack",
"snapshot": "Instantánea",
"sql": "SQL",
"stage": "Etapa",
@@ -433,6 +446,7 @@
"system": "Sistema",
"table": "Tabla",
"task": "Tarea",
+ "teams": "Teams",
"text-wrap": "Ajuste de texto",
"tips": "Consejos",
"title": "Título",
@@ -465,6 +479,7 @@
"want-help": "¿Quiere ayuda?",
"warning": "Advertencia",
"webhooks": "Webhooks",
+ "wecom": "WeCom",
"write-only": "solo escritura",
"yes": "Sí",
"you": "tu"
@@ -563,6 +578,7 @@
},
"data-source": {
"additional-node-addresses": "Direcciones de nodos adicionales",
+ "admin": "Admin",
"automatic-query-data-source": "Automática",
"connection-string-schema": "Esquema de cadena de conexión",
"connection-type": "Tipo de conección",
@@ -576,6 +592,7 @@
"private-key-passphrase": "Frase de contraseña de clave privada",
"private-key-passphrase-placeholder": "Deje vacío si su clave privada no está cifrada",
"private-key-passphrase-tip": "Frase de contraseña opcional para claves privadas cifradas",
+ "read-only": "Solo lectura",
"read-replica-host": "Anfitrión de réplica de lectura",
"read-replica-port": "Puerto de réplica de lectura",
"replica-set": "Conjunto de réplicas",
@@ -1328,6 +1345,7 @@
"change-database": "Modificar base de datos",
"change-from-sql-editor": "Modificar desde el editor SQL",
"edit-schema": "Editar esquema",
+ "export-data": "Exportar datos",
"request-role": "Solicitar rol",
"request-specific-role": "Solicitar rol \"{{role}}\""
},
@@ -1382,6 +1400,7 @@
},
"recovery-code": "Código de recuperación"
},
+ "oauth": {},
"oauth2": {
"consent": {
"description": "{{clientName}} está solicitando acceso a tu cuenta",
@@ -1712,6 +1731,32 @@
"name": "Nombre"
},
"webhook": {
+ "activity-item": {
+ "issue-approval-notify": {
+ "label": "Cuando se requiere aprobación de incidencia",
+ "title": "Notificación de aprobación de incidencia"
+ },
+ "issue-approved": {
+ "label": "Cuando se completan todos los pasos de aprobación",
+ "title": "Incidencia aprobada"
+ },
+ "issue-creation": {
+ "label": "Cuando se crea una nueva incidencia",
+ "title": "Creación de incidencia"
+ },
+ "issue-sent-back": {
+ "label": "Cuando un aprobador devuelve la incidencia",
+ "title": "Incidencia devuelta"
+ },
+ "pipeline-completed": {
+ "label": "Cuando el pipeline se completa con éxito",
+ "title": "Pipeline completado"
+ },
+ "pipeline-failed": {
+ "label": "Cuando las tareas del pipeline fallan",
+ "title": "Pipeline fallido"
+ }
+ },
"activity-support-direct-message": "Soporte para enviar mensajes directos a usuarios relacionados.",
"creation": {
"desc": "Cree el webhook correspondiente para el canal {{destination}} que reciba el mensaje.",
@@ -1758,6 +1803,7 @@
"visit-member": "Visitar Miembro | Miembros",
"visit-project": "Visitar Proyectos"
},
+ "refresh-remind": {},
"release": {
"and-n-more-files": "y {{count}} archivos más",
"change-tip": "Este cambio está vinculado a un artefacto de versión.",
@@ -1806,10 +1852,30 @@
"custom-roles": {
"self": "Roles personalizados"
},
+ "gitops-service-agent": {
+ "description": "Permisos para flujos de trabajo automatizados de CI/CD para crear y ejecutar cambios de base de datos a través de GitOps.",
+ "self": "Agente de Servicio GitOps"
+ },
"import-from-role": "Importar desde el rol",
+ "project-developer": {
+ "description": "El desarrollador del proyecto tiene todos los permisos dentro del proyecto, excepto la gestión de miembros del proyecto.",
+ "self": "Desarrollador del proyecto"
+ },
+ "project-owner": {
+ "description": "El propietario del proyecto tiene todos los permisos dentro del proyecto.",
+ "self": "Propietario del proyecto"
+ },
+ "project-releaser": {
+ "description": "El liberador del proyecto tiene todos los permisos dentro del proyecto, excepto la gestión de miembros del proyecto.",
+ "self": "Liberador del proyecto"
+ },
"project-roles": {
"self": "Roles de proyecto"
},
+ "project-viewer": {
+ "description": "Permisos de solo lectura para ver información básica del proyecto y la base de datos; los usuarios pueden iniciar tickets por su cuenta para solicitar consultas y exportaciones de datos.",
+ "self": "Espectador del proyecto"
+ },
"select-role": "Seleccionar rol",
"self": "Rol",
"setting": {
@@ -1817,7 +1883,27 @@
"description-placeholder": "Ingrese la descripción del rol",
"title-placeholder": "Ingrese el título del rol"
},
+ "sql-editor-read-user": {
+ "description": "Permisos de solo lectura para consultar datos de la base de datos, sin acceso DDL o DML.",
+ "self": "Usuario de solo lectura del editor SQL"
+ },
+ "sql-editor-user": {
+ "description": "El consultor del proyecto tiene todos los permisos dentro del proyecto, excepto la gestión de miembros del proyecto.",
+ "self": "Usuario del editor SQL"
+ },
"title": "Título",
+ "workspace-admin": {
+ "description": "El administrador del espacio de trabajo tiene todos los permisos dentro del espacio de trabajo.",
+ "self": "Administrador del espacio de trabajo"
+ },
+ "workspace-dba": {
+ "description": "El DBA del espacio de trabajo tiene todos los permisos dentro del espacio de trabajo, excepto la gestión de miembros del espacio de trabajo.",
+ "self": "DBA del espacio de trabajo"
+ },
+ "workspace-member": {
+ "description": "El miembro del espacio de trabajo es un usuario normal sin privilegios especiales dentro del espacio de trabajo.",
+ "self": "Miembro del espacio de trabajo"
+ },
"workspace-roles": {
"self": "Roles de espacio de trabajo"
}
@@ -2516,11 +2602,13 @@
"non-empty-folder-content": "¿Desea mover todas las hojas de cálculo a la carpeta raíz o simplemente eliminarlas?",
"non-empty-folder-title": "carpeta no vacía"
},
+ "mine": "Mío",
"move-worksheets": "Hojas de trabajo de movimiento",
"notifications": {
"duplicate-success": "Duplicado con éxito en \"Mis hojas\""
},
- "search-sheets": "Hojas de búsqueda"
+ "search-sheets": "Hojas de búsqueda",
+ "shared": "Compartido"
},
"sql-editor": {
"access-grants": "Concesiones de acceso",
@@ -3665,6 +3753,7 @@
"skip-task": "Saltar tarea | Saltar tareas",
"started": "Iniciado",
"status": {
+ "available": "Disponible",
"canceled": "Cancelado",
"done": "Hecho",
"failed": "Fallido",
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index be84a28c51..1d1f0b226b 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -113,6 +113,10 @@
"stay-signed-in": "ログインしたままにする",
"title": "セッションの有効期限が近づいています"
},
+ "login-as-another": {
+ "content": "ホームページへリダイレクトさせていただきます。",
+ "title": "別のユーザーとしてログインしています"
+ },
"oauth-callback": {
"invalid-state": "認証に失敗しました:無効なコールバック状態です。もう一度お試しください。",
"opener-failed": "認証は完了しましたが、親ウィンドウとの通信に失敗しました。このウィンドウを閉じてもう一度お試しください。",
@@ -157,6 +161,7 @@
"existing-user": "すでにアカウントをお持ちですか?",
"title": "アカウントを登録してください"
},
+ "token-expired-description": "トークンの有効期限が切れています。再度ログインしてください。",
"token-expired-title": "トークンの期限切れ"
},
"banner": {
@@ -228,6 +233,7 @@
"back-to-workspace": "ワークスペースに戻る",
"bypassed": "バイパス済み",
"cancel": "キャンセル",
+ "canceled": "キャンセル",
"cannot-undo-this-action": "この操作は元に戻せません",
"catalog": "カタログ",
"changelog": "Changelog",
@@ -272,8 +278,10 @@
"deselect-all": "すべての選択を解除",
"detail": "詳細",
"detailed-guide": "詳細ガイド",
+ "dingtalk": "DingTalk",
"disable": "無効化",
"discard-changes": "変更をキャンセルする",
+ "discord": "Discord",
"dismiss": "閉じる",
"done": "完了",
"download": "ダウンロード",
@@ -295,6 +303,7 @@
"expired": "期限切れ",
"export": "エクスポート",
"failed": "失敗",
+ "feishu": "Feishu",
"file-selector": {
"size-limit": "ファイルサイズは {{size}} MiB 未満である必要があります",
"type-limit": "タイプ {{extension}} のファイルのみがサポートされます"
@@ -305,6 +314,7 @@
"from": "開始",
"general": "全般",
"go-back": "戻る",
+ "google-chat": "Google Chat",
"group": "グループ",
"groups": "グループ",
"history": "履歴",
@@ -322,6 +332,7 @@
"key": "キー",
"labels": "ラベル",
"language": "言語",
+ "lark": "Lark",
"learn-more": "もっと詳しく知る",
"leave-without-saving": "変更を保存していませんか?",
"license": "ライセンス",
@@ -347,6 +358,7 @@
"next": "次のステップ",
"no": "いいえ",
"no-data": "データなし",
+ "no-license": "ライセンスがありません",
"not-started": "未開始",
"ok": "わかりました",
"only-creator-allowed-export": "エクスポートできるのは作成者のみです",
@@ -421,6 +433,7 @@
"sign-up": "登録する",
"skip": "スキップ",
"skipped": "スキップ",
+ "slack": "Slack",
"snapshot": "スナップショット",
"sql": "SQL",
"stage": "ステージ",
@@ -433,6 +446,7 @@
"system": "システム",
"table": "テーブル",
"task": "タスク",
+ "teams": "Teams",
"text-wrap": "テキストの折り返し",
"tips": "プロンプトメッセージ",
"title": "タイトル",
@@ -465,6 +479,7 @@
"want-help": "ヘルプが必要ですか",
"warning": "警告する",
"webhooks": "Webhook",
+ "wecom": "WeCom",
"write-only": "書き込み専用",
"yes": "はい",
"you": "あなた"
@@ -563,6 +578,7 @@
},
"data-source": {
"additional-node-addresses": "追加のノードアドレス",
+ "admin": "管理者",
"automatic-query-data-source": "自動",
"connection-string-schema": "接続文字列モード",
"connection-type": "接続タイプ",
@@ -576,6 +592,7 @@
"private-key-passphrase": "秘密鍵のパスフレーズ",
"private-key-passphrase-placeholder": "秘密鍵が暗号化されていない場合は空のままにしてください",
"private-key-passphrase-tip": "暗号化された秘密鍵のオプションパスフレーズ",
+ "read-only": "読み取り専用",
"read-replica-host": "リードレプリカホスト",
"read-replica-port": "リードレプリカポート",
"replica-set": "レプリカセット",
@@ -1328,6 +1345,7 @@
"change-database": "データベースの変更",
"change-from-sql-editor": "SQL エディタからの変更",
"edit-schema": "スキーマを編集",
+ "export-data": "データをエクスポート",
"request-role": "ロールをリクエスト",
"request-specific-role": "「{{role}}」ロールをリクエスト"
},
@@ -1382,6 +1400,7 @@
},
"recovery-code": "リカバリーコード"
},
+ "oauth": {},
"oauth2": {
"consent": {
"description": "{{clientName}} があなたのアカウントへのアクセスを要求しています",
@@ -1712,6 +1731,32 @@
"name": "名前"
},
"webhook": {
+ "activity-item": {
+ "issue-approval-notify": {
+ "label": "イシューに承認が必要な場合",
+ "title": "イシューは承認待ちです"
+ },
+ "issue-approved": {
+ "label": "すべての承認ステップが完了したとき",
+ "title": "イシューが承認されました"
+ },
+ "issue-creation": {
+ "label": "新しいイシューが作成されたとき",
+ "title": "イシュー を作成する"
+ },
+ "issue-sent-back": {
+ "label": "承認者がイシューを差し戻したとき",
+ "title": "イシューが差し戻されました"
+ },
+ "pipeline-completed": {
+ "label": "パイプラインが正常に完了したとき",
+ "title": "パイプラインが完了しました"
+ },
+ "pipeline-failed": {
+ "label": "パイプラインタスクが失敗したとき",
+ "title": "パイプラインが失敗しました"
+ }
+ },
"activity-support-direct-message": "関連するユーザーへのプライベートメッセージ通知の送信のサポート",
"creation": {
"desc": "{{destination}} の Webhook を作成します",
@@ -1758,6 +1803,7 @@
"visit-member": "メンバー | メンバーにアクセスする",
"visit-project": "プロジェクトにアクセスする"
},
+ "refresh-remind": {},
"release": {
"and-n-more-files": "他 {{count}} 件のファイル",
"change-tip": "この変更はリリースアーティファクトにリンクされています。",
@@ -1806,10 +1852,30 @@
"custom-roles": {
"self": "カスタムロール"
},
+ "gitops-service-agent": {
+ "description": "GitOps を介して自動化された CI/CD ワークフローでデータベース変更を作成および実行するための権限。",
+ "self": "GitOps サービスエージェント"
+ },
"import-from-role": "ロールからインポート",
+ "project-developer": {
+ "description": "基本的なプロジェクト情報を表示し、データベースの変更、データ クエリ、およびデータ エクスポート リクエストを自分で開始できます。",
+ "self": "プロジェクト開発者"
+ },
+ "project-owner": {
+ "description": "プロジェクト内のすべての権限。",
+ "self": "プロジェクトオーナー"
+ },
+ "project-releaser": {
+ "description": "プロジェクトの基本情報を表示し、指定したプロセスの変更をリリースできます。",
+ "self": "プロジェクト発行者"
+ },
"project-roles": {
"self": "プロジェクトのロール"
},
+ "project-viewer": {
+ "description": "プロジェクトとデータベースの基本情報を閲覧するための読み取り専用権限。ユーザーはデータクエリやエクスポートをリクエストするチケットを自分で発行できます。",
+ "self": "プロジェクトビューア"
+ },
"select-role": "ロールの選択",
"self": "ロール",
"setting": {
@@ -1817,7 +1883,27 @@
"description-placeholder": "ロールの説明を入力してください",
"title-placeholder": "ロールのタイトルを入力してください"
},
+ "sql-editor-read-user": {
+ "description": "DDLまたはDMLアクセスなしで、データベースデータのクエリのための読み取り専用権限。",
+ "self": "SQLエディタ読み取り専用ユーザー"
+ },
+ "sql-editor-user": {
+ "description": "指定した範囲内のデータをクエリできます。",
+ "self": "SQLエディタのユーザー"
+ },
"title": "タイトル",
+ "workspace-admin": {
+ "description": "ワークスペース内のすべての権限。",
+ "self": "ワークスペース管理者"
+ },
+ "workspace-dba": {
+ "description": "ワークスペースのすべてのデータベースとインスタンスを管理できます",
+ "self": "ワークスペースDBA"
+ },
+ "workspace-member": {
+ "description": "ワークスペースの通常のユーザー",
+ "self": "ワークスペースメンバー"
+ },
"workspace-roles": {
"self": "ワークスペースのロール"
}
@@ -2516,11 +2602,13 @@
"non-empty-folder-content": "すべてのワークシートをルート フォルダーに移動しますか、それとも削除するだけですか?",
"non-empty-folder-title": "空でないフォルダ"
},
+ "mine": "マイワークシート",
"move-worksheets": "ワークシートを移動する",
"notifications": {
"duplicate-success": "「マイワークシート」にコピーされました"
},
- "search-sheets": "ワークシートの検索"
+ "search-sheets": "ワークシートの検索",
+ "shared": "共有"
},
"sql-editor": {
"access-grants": "アクセス付与",
@@ -3665,6 +3753,7 @@
"skip-task": "タスクをスキップ | タスクをスキップ",
"started": "開始日時",
"status": {
+ "available": "利用可能",
"canceled": "キャンセル",
"done": "終わり",
"failed": "失敗",
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index 0cc91e1d00..45a536c164 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -113,6 +113,10 @@
"stay-signed-in": "Tiếp tục duy trì đăng nhập",
"title": "Phiên của bạn sắp kết thúc"
},
+ "login-as-another": {
+ "content": "Chúng tôi sẽ chuyển hướng bạn đến trang chủ.",
+ "title": "Bạn đã đăng nhập với tư cách người dùng khác"
+ },
"oauth-callback": {
"invalid-state": "Xác thực thất bại: Trạng thái gọi lại không hợp lệ. Vui lòng thử lại.",
"opener-failed": "Xác thực đã hoàn tất, nhưng không thể giao tiếp với cửa sổ cha. Vui lòng đóng cửa sổ này và thử lại.",
@@ -157,6 +161,7 @@
"existing-user": "Đã có tài khoản?",
"title": "Đăng ký tài khoản của bạn"
},
+ "token-expired-description": "Mã thông báo đã hết hạn, vui lòng đăng nhập lại",
"token-expired-title": "Mã thông báo đã hết hạn"
},
"banner": {
@@ -228,6 +233,7 @@
"back-to-workspace": "Quay lại workspace",
"bypassed": "Đã bỏ qua",
"cancel": "Hủy",
+ "canceled": "Đã hủy",
"cannot-undo-this-action": "Bạn không thể hoàn tác hành động này.",
"catalog": "Danh mục",
"changelog": "Changelog",
@@ -272,8 +278,10 @@
"deselect-all": "Bỏ chọn tất cả",
"detail": "Chi tiết",
"detailed-guide": "Hướng dẫn chi tiết",
+ "dingtalk": "DingTalk",
"disable": "Tắt",
"discard-changes": "Hủy thay đổi",
+ "discord": "Discord",
"dismiss": "Loại bỏ",
"done": "Hoàn tất",
"download": "Tải xuống",
@@ -295,6 +303,7 @@
"expired": "Đã hết hạn",
"export": "Xuất",
"failed": "Thất bại",
+ "feishu": "Feishu",
"file-selector": {
"size-limit": "Kích thước tệp phải nhỏ hơn {{size}} MiB",
"type-limit": "Chỉ hỗ trợ tệp {{extension}}"
@@ -305,6 +314,7 @@
"from": "Từ",
"general": "Chung",
"go-back": "Quay lại",
+ "google-chat": "Google Chat",
"group": "Nhóm",
"groups": "Nhóm",
"history": "Lịch sử",
@@ -322,6 +332,7 @@
"key": "Khóa",
"labels": "Nhãn",
"language": "Ngôn ngữ",
+ "lark": "Lark",
"learn-more": "Tìm hiểu thêm",
"leave-without-saving": "Thoát mà không lưu?",
"license": "Giấy phép",
@@ -347,6 +358,7 @@
"next": "Tiếp theo",
"no": "Không",
"no-data": "Không có dữ liệu",
+ "no-license": "Không có giấy phép",
"not-started": "Chưa bắt đầu",
"ok": "OK",
"only-creator-allowed-export": "Chỉ người tạo mới được phép xuất",
@@ -421,6 +433,7 @@
"sign-up": "Đăng ký",
"skip": "Bỏ qua",
"skipped": "Đã bỏ qua",
+ "slack": "Slack",
"snapshot": "Ảnh chụp nhanh",
"sql": "SQL",
"stage": "Giai đoạn",
@@ -433,6 +446,7 @@
"system": "Hệ thống",
"table": "Bảng",
"task": "Tác vụ",
+ "teams": "Teams",
"text-wrap": "Ngắt dòng văn bản",
"tips": "Mẹo",
"title": "Tiêu đề",
@@ -465,6 +479,7 @@
"want-help": "Cần trợ giúp",
"warning": "Cảnh báo",
"webhooks": "Webhook",
+ "wecom": "WeCom",
"write-only": "chỉ ghi",
"yes": "Có",
"you": "bạn"
@@ -563,6 +578,7 @@
},
"data-source": {
"additional-node-addresses": "Địa chỉ nút bổ sung",
+ "admin": "Quản trị",
"automatic-query-data-source": "Tự động",
"connection-string-schema": "Lược đồ chuỗi kết nối",
"connection-type": "Loại kết nối",
@@ -576,6 +592,7 @@
"private-key-passphrase": "Mật khẩu khóa riêng",
"private-key-passphrase-placeholder": "Để trống nếu khóa riêng của bạn không được mã hóa",
"private-key-passphrase-tip": "Mật khẩu tùy chọn cho khóa riêng được mã hóa",
+ "read-only": "Chỉ đọc",
"read-replica-host": "Máy chủ bản sao đọc",
"read-replica-port": "Cổng bản sao đọc",
"replica-set": "Bộ bản sao",
@@ -1328,6 +1345,7 @@
"change-database": "Thay đổi cơ sở dữ liệu",
"change-from-sql-editor": "Thay đổi từ SQL Editor",
"edit-schema": "Chỉnh sửa schema",
+ "export-data": "Xuất dữ liệu",
"request-role": "Yêu cầu vai trò",
"request-specific-role": "Yêu cầu vai trò \"{{role}}\""
},
@@ -1382,6 +1400,7 @@
},
"recovery-code": "Mã khôi phục"
},
+ "oauth": {},
"oauth2": {
"consent": {
"description": "{{clientName}} đang yêu cầu truy cập vào tài khoản của bạn",
@@ -1712,6 +1731,32 @@
"name": "Tên"
},
"webhook": {
+ "activity-item": {
+ "issue-approval-notify": {
+ "label": "Khi vấn đề đang chờ phê duyệt",
+ "title": "Cần phê duyệt vấn đề"
+ },
+ "issue-approved": {
+ "label": "Khi tất cả các bước phê duyệt hoàn tất",
+ "title": "Vấn đề đã được phê duyệt"
+ },
+ "issue-creation": {
+ "label": "Khi vấn đề mới được tạo",
+ "title": "Tạo vấn đề"
+ },
+ "issue-sent-back": {
+ "label": "Khi người phê duyệt trả lại vấn đề",
+ "title": "Vấn đề bị trả lại"
+ },
+ "pipeline-completed": {
+ "label": "Khi pipeline hoàn thành thành công",
+ "title": "Pipeline hoàn thành"
+ },
+ "pipeline-failed": {
+ "label": "Khi các tác vụ pipeline thất bại",
+ "title": "Pipeline thất bại"
+ }
+ },
"activity-support-direct-message": "Hỗ trợ gửi tin nhắn trực tiếp đến người dùng liên quan",
"creation": {
"desc": "Tạo webhook tương ứng cho kênh {{destination}} nhận tin nhắn.",
@@ -1758,6 +1803,7 @@
"visit-member": "Truy cập Thành viên | Thành viên",
"visit-project": "Truy cập Dự án"
},
+ "refresh-remind": {},
"release": {
"and-n-more-files": "và {{count}} tệp khác",
"change-tip": "Thay đổi này được liên kết với một artifact phát hành.",
@@ -1806,10 +1852,30 @@
"custom-roles": {
"self": "Vai trò tùy chỉnh"
},
+ "gitops-service-agent": {
+ "description": "Quyền cho quy trình CI/CD tự động để tạo và thực thi các thay đổi cơ sở dữ liệu qua GitOps.",
+ "self": "Tác nhân Dịch vụ GitOps"
+ },
"import-from-role": "Nhập từ vai trò",
+ "project-developer": {
+ "description": "Tất cả các quyền xem, cộng với các quyền yêu cầu thay đổi cơ sở dữ liệu.",
+ "self": "Nhà phát triển dự án"
+ },
+ "project-owner": {
+ "description": "Tất cả các quyền trong dự án",
+ "self": "Chủ sở hữu dự án"
+ },
+ "project-releaser": {
+ "description": "Tất cả các quyền xem, cộng với quyền xem xét các yêu cầu thay đổi cơ sở dữ liệu cho mục đích phát hành.",
+ "self": "Người phát hành dự án"
+ },
"project-roles": {
"self": "Vai trò dự án"
},
+ "project-viewer": {
+ "description": "Quyền chỉ đọc để xem thông tin cơ bản của dự án và cơ sở dữ liệu; người dùng có thể tự tạo yêu cầu để truy vấn và xuất dữ liệu.",
+ "self": "Người xem dự án"
+ },
"select-role": "Chọn vai trò",
"self": "Vai trò",
"setting": {
@@ -1817,7 +1883,27 @@
"description-placeholder": "Nhập mô tả vai trò",
"title-placeholder": "Nhập tiêu đề vai trò"
},
+ "sql-editor-read-user": {
+ "description": "Quyền chỉ đọc để truy vấn dữ liệu cơ sở dữ liệu, không có quyền DDL hoặc DML.",
+ "self": "Người dùng Trình soạn thảo SQL chỉ đọc"
+ },
+ "sql-editor-user": {
+ "description": "Quyền truy vấn dữ liệu cơ sở dữ liệu.",
+ "self": "Người dùng Trình soạn thảo SQL"
+ },
"title": "Tiêu đề",
+ "workspace-admin": {
+ "description": "Quản trị viên không gian làm việc có tất cả các quyền trong không gian làm việc.",
+ "self": "Quản trị viên không gian làm việc"
+ },
+ "workspace-dba": {
+ "description": "DBA không gian làm việc có tất cả các quyền trong không gian làm việc ngoại trừ quản lý thành viên không gian làm việc.",
+ "self": "DBA không gian làm việc"
+ },
+ "workspace-member": {
+ "description": "Thành viên không gian làm việc là vai trò cơ bản nhất trong không gian làm việc.",
+ "self": "Thành viên không gian làm việc"
+ },
"workspace-roles": {
"self": "Vai trò không gian làm việc"
}
@@ -2516,11 +2602,13 @@
"non-empty-folder-content": "Bạn muốn di chuyển tất cả các trang tính vào thư mục gốc hay chỉ xóa chúng?",
"non-empty-folder-title": "Thư mục không trống"
},
+ "mine": "Của tôi",
"move-worksheets": "Di chuyển các trang tính",
"notifications": {
"duplicate-success": "Đã nhân bản thành công vào \"Trang tính của tôi\""
},
- "search-sheets": "Tìm kiếm Trang tính"
+ "search-sheets": "Tìm kiếm Trang tính",
+ "shared": "Được chia sẻ"
},
"sql-editor": {
"access-grants": "Cấp quyền truy cập",
@@ -3665,6 +3753,7 @@
"skip-task": "Bỏ qua nhiệm vụ | Bỏ qua nhiệm vụ",
"started": "Bắt đầu",
"status": {
+ "available": "Có sẵn",
"canceled": "Đã hủy",
"done": "Hoàn tất",
"failed": "Thất bại",
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index c1857d13d6..95c38ec20d 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -113,6 +113,10 @@
"stay-signed-in": "保持登录状态",
"title": "您的会话即将结束"
},
+ "login-as-another": {
+ "content": "我们将把您重定向到主页。",
+ "title": "您已以其他用户身份登录"
+ },
"oauth-callback": {
"invalid-state": "认证失败:无效的回调状态。请重试。",
"opener-failed": "认证已完成,但与父窗口通信失败。请关闭此窗口并重试。",
@@ -157,6 +161,7 @@
"existing-user": "已有账号?",
"title": "注册您的账号"
},
+ "token-expired-description": "Token 已过期,请重新登录",
"token-expired-title": "令牌已过期"
},
"banner": {
@@ -228,6 +233,7 @@
"back-to-workspace": "返回工作区",
"bypassed": "已绕过",
"cancel": "取消",
+ "canceled": "已取消",
"cannot-undo-this-action": "这个操作无法撤销",
"catalog": "Catalog",
"changelog": "变更历史",
@@ -272,8 +278,10 @@
"deselect-all": "取消全选",
"detail": "详情",
"detailed-guide": "详细指南",
+ "dingtalk": "钉钉",
"disable": "禁用",
"discard-changes": "取消修改",
+ "discord": "Discord",
"dismiss": "关闭",
"done": "完成",
"download": "下载",
@@ -295,6 +303,7 @@
"expired": "已过期",
"export": "导出",
"failed": "失败",
+ "feishu": "飞书",
"file-selector": {
"size-limit": "文件大小需小于 {{size}} MiB",
"type-limit": "仅支持 {{extension}} 类型的文件"
@@ -305,6 +314,7 @@
"from": "从",
"general": "通用",
"go-back": "返回",
+ "google-chat": "Google Chat",
"group": "组",
"groups": "分组",
"history": "历史记录",
@@ -322,6 +332,7 @@
"key": "键",
"labels": "标签",
"language": "语言",
+ "lark": "Lark",
"learn-more": "了解更多",
"leave-without-saving": "不保存变动?",
"license": "License",
@@ -347,6 +358,7 @@
"next": "下一步",
"no": "否",
"no-data": "无数据",
+ "no-license": "无证书",
"not-started": "未开始",
"ok": "确定",
"only-creator-allowed-export": "只有创建者可以导出",
@@ -421,6 +433,7 @@
"sign-up": "注册",
"skip": "跳过",
"skipped": "已跳过",
+ "slack": "Slack",
"snapshot": "快照",
"sql": "SQL",
"stage": "阶段",
@@ -433,6 +446,7 @@
"system": "系统",
"table": "表",
"task": "任务",
+ "teams": "Teams",
"text-wrap": "文本折行",
"tips": "提示信息",
"title": "标题",
@@ -465,6 +479,7 @@
"want-help": "需要帮助",
"warning": "警告",
"webhooks": "Webhook",
+ "wecom": "企业微信",
"write-only": "仅写入",
"yes": "是",
"you": "您"
@@ -563,6 +578,7 @@
},
"data-source": {
"additional-node-addresses": "附加节点地址",
+ "admin": "管理员",
"automatic-query-data-source": "自动",
"connection-string-schema": "连接串模式",
"connection-type": "连接类型",
@@ -576,6 +592,7 @@
"private-key-passphrase": "私钥密码",
"private-key-passphrase-placeholder": "如果私钥未加密,请留空",
"private-key-passphrase-tip": "加密私钥的可选密码",
+ "read-only": "只读",
"read-replica-host": "只读副本 Host",
"read-replica-port": "只读副本端口",
"replica-set": "副本集",
@@ -1328,6 +1345,7 @@
"change-database": "变更数据库",
"change-from-sql-editor": "从 SQL 编辑器变更",
"edit-schema": "编辑 Schema",
+ "export-data": "导出数据",
"request-role": "申请角色",
"request-specific-role": "申请 \"{{role}}\" 角色"
},
@@ -1382,6 +1400,7 @@
},
"recovery-code": "恢复码"
},
+ "oauth": {},
"oauth2": {
"consent": {
"description": "{{clientName}} 正在请求访问您的账户",
@@ -1712,6 +1731,32 @@
"name": "名称"
},
"webhook": {
+ "activity-item": {
+ "issue-approval-notify": {
+ "label": "当工单需要审批",
+ "title": "工单待审批"
+ },
+ "issue-approved": {
+ "label": "当所有审批步骤完成时通知",
+ "title": "工单审批通过"
+ },
+ "issue-creation": {
+ "label": "当一个新的工单被创建",
+ "title": "创建工单"
+ },
+ "issue-sent-back": {
+ "label": "当工单被审批人退回",
+ "title": "工单被退回"
+ },
+ "pipeline-completed": {
+ "label": "当流水线成功完成",
+ "title": "流水线完成"
+ },
+ "pipeline-failed": {
+ "label": "当流水线任务失败",
+ "title": "流水线失败"
+ }
+ },
"activity-support-direct-message": "支持向相关用户发送私信通知",
"creation": {
"desc": "为 {{destination}} 创建一个 webhook",
@@ -1758,6 +1803,7 @@
"visit-member": "访问成员 | 成员",
"visit-project": "访问项目"
},
+ "refresh-remind": {},
"release": {
"and-n-more-files": "以及另外 {{count}} 个文件",
"change-tip": "该变更关联到了一个发布包。",
@@ -1806,10 +1852,30 @@
"custom-roles": {
"self": "自定义角色"
},
+ "gitops-service-agent": {
+ "description": "通过 GitOps 自动化 CI/CD 工作流创建和执行数据库变更的权限。",
+ "self": "GitOps 服务代理"
+ },
"import-from-role": "从角色导入",
+ "project-developer": {
+ "description": "可查看项目基本信息,并可自助发起数据库变更、数据查询、数据导出请求。",
+ "self": "项目开发者"
+ },
+ "project-owner": {
+ "description": "项目内的所有权限。",
+ "self": "项目所有者"
+ },
+ "project-releaser": {
+ "description": "可查看项目基本信息,并可在指定流程中发布变更。",
+ "self": "项目发布者"
+ },
"project-roles": {
"self": "项目角色"
},
+ "project-viewer": {
+ "description": "仅可查看项目和数据库的基本信息,用户可自助发起工单请求数据查询和导出。",
+ "self": "项目查看者"
+ },
"select-role": "选择角色",
"self": "角色",
"setting": {
@@ -1817,7 +1883,27 @@
"description-placeholder": "输入角色描述",
"title-placeholder": "输入角色称谓"
},
+ "sql-editor-read-user": {
+ "description": "只读权限,可查询数据库数据,不包含 DDL 或 DML 访问权限。",
+ "self": "SQL 编辑器只读用户"
+ },
+ "sql-editor-user": {
+ "description": "可查询指定范围的数据。",
+ "self": "SQL 编辑器用户"
+ },
"title": "称谓",
+ "workspace-admin": {
+ "description": "工作空间内的所有权限。",
+ "self": "工作空间管理员"
+ },
+ "workspace-dba": {
+ "description": "可以管理工作空间的所有数据库和实例",
+ "self": "工作空间 DBA"
+ },
+ "workspace-member": {
+ "description": "工作空间中的普通用户",
+ "self": "工作空间成员"
+ },
"workspace-roles": {
"self": "工作空间角色"
}
@@ -2516,11 +2602,13 @@
"non-empty-folder-content": "您是想将所有工作表移动到根文件夹,还是直接删除它们?",
"non-empty-folder-title": "非空文件夹"
},
+ "mine": "我的",
"move-worksheets": "移动工作表",
"notifications": {
"duplicate-success": "已成功拷贝至“我的工作表”"
},
- "search-sheets": "搜索工作表"
+ "search-sheets": "搜索工作表",
+ "shared": "共享的"
},
"sql-editor": {
"access-grants": "访问授权",
@@ -3665,6 +3753,7 @@
"skip-task": "跳过任务 | 跳过任务",
"started": "开始于",
"status": {
+ "available": "就绪",
"canceled": "已取消",
"done": "完成",
"failed": "失败",
diff --git a/frontend/src/react/mount.test.ts b/frontend/src/react/mount.test.ts
deleted file mode 100644
index 0f4bf22c46..0000000000
--- a/frontend/src/react/mount.test.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { describe, expect, test } from "vitest";
-import { resolveReactPagePath } from "./mount";
-
-describe("resolveReactPagePath", () => {
- test("resolves the InactiveRemindModal entry", () => {
- expect(resolveReactPagePath("InactiveRemindModal")).toBe(
- "./components/auth/InactiveRemindModal.tsx"
- );
- });
-
- test("does not resolve AgentWindow (now in the React app)", () => {
- expect(resolveReactPagePath("AgentWindow")).toBeUndefined();
- });
-
- test("does not resolve SessionExpiredSurface (now in the React app)", () => {
- expect(resolveReactPagePath("SessionExpiredSurface")).toBeUndefined();
- });
-
- test("does not resolve auth test modules as runtime pages", () => {
- expect(resolveReactPagePath("InactiveRemindModal.test")).toBeUndefined();
- });
-});
diff --git a/frontend/src/react/mount.ts b/frontend/src/react/mount.ts
index f99d1f8ba5..4f6c38fc0c 100644
--- a/frontend/src/react/mount.ts
+++ b/frontend/src/react/mount.ts
@@ -1,40 +1,11 @@
-// 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",
- "./pages/project/plan-detail/ProjectPlanDetailPage.tsx",
-]);
-const workspacePageLoaders = import.meta.glob("./pages/workspace/*.tsx");
-const authPageLoaders = import.meta.glob("./pages/auth/*.tsx");
-const authComponentLoaders = import.meta.glob([
- "./components/auth/InactiveRemindModal.tsx",
-]);
-const sqlEditorComponentLoaders = import.meta.glob(
- "./components/sql-editor/*.tsx"
-);
-const sharedComponentLoaders = import.meta.glob([
- "./components/*.tsx",
- "!./components/*.test.tsx",
-]);
-const pageLoaders = {
- ...settingsPageLoaders,
- ...projectPageLoaders,
- ...workspacePageLoaders,
- ...authPageLoaders,
- ...authComponentLoaders,
- ...sqlEditorComponentLoaders,
- ...sharedComponentLoaders,
-};
-
// biome-ignore lint/suspicious/noExplicitAny: React types conflict with Vue JSX in vue-tsc
export type ReactDeps = any; // eslint-disable-line @typescript-eslint/no-explicit-any
// biome-ignore lint/suspicious/noExplicitAny: Component type checked by tsconfig.react.json
export type ReactComponent = (props: any) => any; // eslint-disable-line @typescript-eslint/no-explicit-any
let cachedDeps: ReactDeps | null = null;
-const cachedPages = new Map<string, ReactComponent>();
+// Loads the core React + i18n runtime (lazily, cached) used to mount the app.
export async function loadCoreDeps() {
if (cachedDeps) return cachedDeps;
const [
@@ -59,48 +30,7 @@ export async function loadCoreDeps() {
return cachedDeps;
}
-const pageDirs = [
- "./pages/settings",
- "./pages/project",
- "./pages/project/plan-detail",
- "./pages/workspace",
- "./pages/auth",
- "./components/auth",
- "./components/sql-editor",
- "./components",
-];
-
-export function resolveReactPagePath(name: string): string | undefined {
- for (const dir of pageDirs) {
- const path = `${dir}/${name}.tsx`;
- if (path in pageLoaders) {
- return path;
- }
- }
- return undefined;
-}
-
-async function loadPage(name: string): Promise<ReactComponent> {
- const hit = cachedPages.get(name);
- if (hit) return hit;
- const path = resolveReactPagePath(name);
- const loader = path
- ? (pageLoaders[path] as
- | (() => Promise<Record<string, unknown>>)
- | undefined)
- : undefined;
- if (!loader) throw new Error(`Unknown React page: ${name}`);
- const mod = await loader();
- const Component = mod[name] as ReactComponent;
- cachedPages.set(name, Component);
- return Component;
-}
-
-/**
- * Mount a self-contained React page into the given container element.
- * @param page — file name without extension, must match the exported function name
- * (e.g. "MCPPage", "SubscriptionPage")
- */
+// Wraps a React component in the shared StrictMode + i18n provider tree.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore -- React createElement types conflict with Vue JSX in vue-tsc
export function buildTree(
@@ -119,34 +49,3 @@ export function buildTree(
)
);
}
-
-/**
- * Mount a React page into the given container element.
- * @param page — file name without extension, must match the exported function name
- * @param props — optional props for pages that need Vue callbacks (e.g. SubscriptionPage)
- */
-export async function mountReactPage(
- container: HTMLElement,
- page: string,
- // biome-ignore lint/suspicious/noExplicitAny: Props type varies per page
- props?: any // eslint-disable-line @typescript-eslint/no-explicit-any
-) {
- const [deps, Component] = await Promise.all([loadCoreDeps(), loadPage(page)]);
- const root = deps.createRoot(container);
- root.render(buildTree(deps, Component, props));
- return root;
-}
-
-/**
- * Re-render an already-mounted React page with new props.
- */
-export async function updateReactPage(
- // biome-ignore lint/suspicious/noExplicitAny: React Root type from dynamic import
- root: any, // eslint-disable-line @typescript-eslint/no-explicit-any
- page: string,
- // biome-ignore lint/suspicious/noExplicitAny: Props type varies per page
- props?: any // eslint-disable-line @typescript-eslint/no-explicit-any
-) {
- const [deps, Component] = await Promise.all([loadCoreDeps(), loadPage(page)]);
- root.render(buildTree(deps, Component, props));
-}
diff --git a/frontend/src/react/mountProjectSidebar.ts b/frontend/src/react/mountProjectSidebar.ts
deleted file mode 100644
index 4691391040..0000000000
--- a/frontend/src/react/mountProjectSidebar.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-// Use import.meta.glob so vue-tsc does not follow the import into React .tsx files.
-const sidebarLoader = import.meta.glob("./components/ProjectSidebar.tsx");
-
-// biome-ignore lint/suspicious/noExplicitAny: React types conflict with Vue JSX in vue-tsc
-type ReactDeps = any; // eslint-disable-line @typescript-eslint/no-explicit-any
-
-let cachedDeps: ReactDeps | null = null;
-
-async function loadCoreDeps() {
- if (cachedDeps) return cachedDeps;
- const [
- { createElement, StrictMode },
- { createRoot },
- { I18nextProvider },
- i18nModule,
- ] = await Promise.all([
- import("react"),
- import("react-dom/client"),
- import("react-i18next"),
- import("@/react/i18n"),
- ]);
- await i18nModule.i18nReady;
- cachedDeps = {
- createElement,
- StrictMode,
- createRoot,
- I18nextProvider,
- i18n: i18nModule.default,
- };
- return cachedDeps;
-}
-
-async function loadSidebar() {
- const loader = sidebarLoader["./components/ProjectSidebar.tsx"];
- if (!loader) throw new Error("ProjectSidebar not found");
- const mod = (await loader()) as Record<string, unknown>;
- return mod.ProjectSidebar as ReactDeps;
-}
-
-export async function mountProjectSidebar(
- container: HTMLElement,
- locale: string
-) {
- const [deps, ProjectSidebar] = await Promise.all([
- loadCoreDeps(),
- loadSidebar(),
- ]);
- if (deps.i18n.language !== locale) {
- await deps.i18n.changeLanguage(locale);
- }
- const tree = deps.createElement(
- deps.StrictMode,
- null,
- deps.createElement(
- deps.I18nextProvider,
- { i18n: deps.i18n },
- deps.createElement(ProjectSidebar)
- )
- );
- const root = deps.createRoot(container);
- root.render(tree);
- return root;
-}
-
-export async function updateProjectSidebarLocale(
- // biome-ignore lint/suspicious/noExplicitAny: React Root type from dynamic import
- root: any, // eslint-disable-line @typescript-eslint/no-explicit-any
- locale: string
-) {
- const [deps, ProjectSidebar] = await Promise.all([
- loadCoreDeps(),
- loadSidebar(),
- ]);
- if (deps.i18n.language !== locale) {
- await deps.i18n.changeLanguage(locale);
- }
- const tree = deps.createElement(
- deps.StrictMode,
- null,
- deps.createElement(
- deps.I18nextProvider,
- { i18n: deps.i18n },
- deps.createElement(ProjectSidebar)
- )
- );
- root.render(tree);
-}
diff --git a/frontend/src/react/mountSidebar.ts b/frontend/src/react/mountSidebar.ts
deleted file mode 100644
index 3d624ce2b2..0000000000
--- a/frontend/src/react/mountSidebar.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-// Use import.meta.glob so vue-tsc does not follow the import into React .tsx files.
-const sidebarLoader = import.meta.glob("./components/DashboardSidebar.tsx");
-
-// biome-ignore lint/suspicious/noExplicitAny: React types conflict with Vue JSX in vue-tsc
-type ReactDeps = any; // eslint-disable-line @typescript-eslint/no-explicit-any
-
-let cachedDeps: ReactDeps | null = null;
-
-async function loadCoreDeps() {
- if (cachedDeps) return cachedDeps;
- const [
- { createElement, StrictMode },
- { createRoot },
- { I18nextProvider },
- i18nModule,
- ] = await Promise.all([
- import("react"),
- import("react-dom/client"),
- import("react-i18next"),
- import("@/react/i18n"),
- ]);
- await i18nModule.i18nReady;
- cachedDeps = {
- createElement,
- StrictMode,
- createRoot,
- I18nextProvider,
- i18n: i18nModule.default,
- };
- return cachedDeps;
-}
-
-async function loadSidebar() {
- const loader = sidebarLoader["./components/DashboardSidebar.tsx"];
- if (!loader) throw new Error("DashboardSidebar not found");
- const mod = (await loader()) as Record<string, unknown>;
- return mod.DashboardSidebar as ReactDeps;
-}
-
-export async function mountSidebar(container: HTMLElement, locale: string) {
- const [deps, DashboardSidebar] = await Promise.all([
- loadCoreDeps(),
- loadSidebar(),
- ]);
- if (deps.i18n.language !== locale) {
- await deps.i18n.changeLanguage(locale);
- }
- const tree = deps.createElement(
- deps.StrictMode,
- null,
- deps.createElement(
- deps.I18nextProvider,
- { i18n: deps.i18n },
- deps.createElement(DashboardSidebar)
- )
- );
- const root = deps.createRoot(container);
- root.render(tree);
- return root;
-}
-
-export async function updateSidebarLocale(
- // biome-ignore lint/suspicious/noExplicitAny: React Root type from dynamic import
- root: any, // eslint-disable-line @typescript-eslint/no-explicit-any
- locale: string
-) {
- const [deps, DashboardSidebar] = await Promise.all([
- loadCoreDeps(),
- loadSidebar(),
- ]);
- if (deps.i18n.language !== locale) {
- await deps.i18n.changeLanguage(locale);
- }
- const tree = deps.createElement(
- deps.StrictMode,
- null,
- deps.createElement(
- deps.I18nextProvider,
- { i18n: deps.i18n },
- deps.createElement(DashboardSidebar)
- )
- );
- root.render(tree);
-}
diff --git a/frontend/src/react/no-legacy-vue-deps.test.ts b/frontend/src/react/no-legacy-vue-deps.test.ts
index 5926abca92..7411ee72ee 100644
--- a/frontend/src/react/no-legacy-vue-deps.test.ts
+++ b/frontend/src/react/no-legacy-vue-deps.test.ts
@@ -6,13 +6,7 @@ const sources = import.meta.glob(
"./pages/settings/**/*.{ts,tsx}",
"./pages/auth/**/*.{ts,tsx}",
"./components/**/*.{ts,tsx}",
- "../router/dashboard/projectV1.ts",
- "../router/dashboard/workspace.ts",
- "../router/dashboard/workspaceSetting.ts",
- "../layouts/BodyLayout.vue",
- "../layouts/SQLEditorLayout.vue",
"../components/ProvideSQLEditorContext.vue",
- "./ReactRouteShellBridge.vue",
"./components/ProjectRouteShell.tsx",
"./components/SettingRouteShell.tsx",
"./components/InstanceRouteShell.tsx",
@@ -43,12 +37,7 @@ const currentUserMigrationSources = import.meta.glob(
) as Record<string, string>;
const instanceMigrationSources = import.meta.glob(
- [
- "../router/index.ts",
- "../router/dashboard/instance.ts",
- "../utils/expr.ts",
- "../utils/v1/issue/issue.ts",
- ],
+ ["../utils/expr.ts", "../utils/v1/issue/issue.ts"],
{
query: "?raw",
import: "default",
@@ -67,8 +56,6 @@ const removedLegacyInstanceStoreSources = import.meta.glob(
const databaseMigrationSources = import.meta.glob(
[
- "../router/index.ts",
- "../router/dashboard/instance.ts",
"../utils/expr.ts",
"../utils/v1/revision.ts",
"../utils/v1/changelog.ts",
@@ -279,19 +266,6 @@ describe("React Project and Settings legacy Vue dependencies", () => {
expect(violations).toEqual([]);
});
- test("instance database redirect stays in the React view layer", () => {
- const source = databaseMigrationSources["../router/dashboard/instance.ts"];
- const bannedRouterLogic = [
- "@/react/stores/app/databaseAccess",
- "getOrFetchDatabaseByName",
- "beforeEnter",
- ];
- const violations = bannedRouterLogic.filter((pattern) =>
- source.includes(pattern)
- );
- expect(violations).toEqual([]);
- });
-
test("migrated DB schema surfaces do not expose the legacy DB schema store", () => {
const violations: string[] = [];
for (const [file, source] of Object.entries(dbSchemaMigrationSources)) {
diff --git a/frontend/src/react/pages/auth/MultiFactorPage.test.tsx b/frontend/src/react/pages/auth/MultiFactorPage.test.tsx
index 038b215288..71a9f4a0db 100644
--- a/frontend/src/react/pages/auth/MultiFactorPage.test.tsx
+++ b/frontend/src/react/pages/auth/MultiFactorPage.test.tsx
@@ -8,7 +8,6 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
).IS_REACT_ACT_ENVIRONMENT = true;
const mocks = vi.hoisted(() => ({
- useVueState: vi.fn<(getter: () => unknown) => unknown>((getter) => getter()),
login: vi.fn<(payload: unknown) => Promise<void>>(async () => {}),
useAuthStore: vi.fn(),
currentRoute: {
@@ -18,18 +17,31 @@ const mocks = vi.hoisted(() => ({
}));
mocks.useAuthStore.mockImplementation(() => ({ login: mocks.login }));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
vi.mock("@/store", () => ({
useAuthStore: mocks.useAuthStore,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/stores/app", () => ({
+ useAppStore: Object.assign(() => ({}), {
+ getState: () => ({ login: mocks.login, workspaceResourceName: () => "" }),
+ }),
+}));
+
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
currentRoute: mocks.currentRoute,
},
+ useCurrentRoute: () => ({
+ name: "",
+ fullPath: "/",
+ hash: "",
+ params: {},
+ query: mocks.currentRoute.value.query,
+ requiredPermissions: [],
+ overrideDocumentTitle: false,
+ meta: {},
+ }),
}));
vi.mock("@/utils", () => {
@@ -46,6 +58,7 @@ vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string) => key,
}),
+ initReactI18next: { type: "3rdParty", init: () => {} },
}));
vi.mock("@bufbuild/protobuf", async (importOriginal) => {
diff --git a/frontend/src/react/pages/auth/MultiFactorPage.tsx b/frontend/src/react/pages/auth/MultiFactorPage.tsx
index 8f1113d081..d8989e078a 100644
--- a/frontend/src/react/pages/auth/MultiFactorPage.tsx
+++ b/frontend/src/react/pages/auth/MultiFactorPage.tsx
@@ -6,11 +6,10 @@ import logoFull from "@/assets/logo-full.svg";
import { Button } from "@/react/components/ui/button";
import { Input } from "@/react/components/ui/input";
import { OtpInput } from "@/react/components/ui/otp-input";
-import { useVueState } from "@/react/hooks/useVueState";
-import { router } from "@/router";
-import { useAuthStore } from "@/store";
+import { resolveWorkspaceName } from "@/react/lib/workspace";
+import { useCurrentRoute } from "@/react/router";
+import { useAppStore } from "@/react/stores/app";
import { LoginRequestSchema } from "@/types/proto-es/v1/auth_service_pb";
-import { resolveWorkspaceName } from "@/utils";
type MFAType = "OTP" | "RECOVERY_CODE";
@@ -20,10 +19,8 @@ export function MultiFactorPage() {
const [otpCodes, setOtpCodes] = useState<string[]>([]);
const [recoveryCode, setRecoveryCode] = useState("");
- const mfaTempToken = useVueState(
- () =>
- (router.currentRoute.value.query.mfaTempToken as string | undefined) ?? ""
- );
+ const mfaTempToken =
+ (useCurrentRoute().query.mfaTempToken as string | undefined) ?? "";
const challengeDescription = useMemo(() => {
if (mfaType === "OTP") {
@@ -42,7 +39,7 @@ export function MultiFactorPage() {
workspace: resolveWorkspaceName(),
...(mfaType === "OTP" ? { otpCode: effectiveOtp } : { recoveryCode }),
});
- await useAuthStore().login({ request, redirect: true });
+ await useAppStore.getState().login({ request, redirect: true });
};
const onOtpFinish = (value: string[]) => {
diff --git a/frontend/src/react/pages/auth/OAuth2ConsentPage.test.tsx b/frontend/src/react/pages/auth/OAuth2ConsentPage.test.tsx
index d8af1588e6..5cfb2aa04f 100644
--- a/frontend/src/react/pages/auth/OAuth2ConsentPage.test.tsx
+++ b/frontend/src/react/pages/auth/OAuth2ConsentPage.test.tsx
@@ -8,7 +8,6 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
).IS_REACT_ACT_ENVIRONMENT = true;
const mocks = vi.hoisted(() => ({
- useVueState: vi.fn<(getter: () => unknown) => unknown>((getter) => getter()),
useAuthStore: vi.fn(),
useAppStore: vi.fn(),
useWorkspace: vi.fn(),
@@ -52,6 +51,7 @@ mocks.useAppStore.mockImplementation((selector: (state: unknown) => unknown) =>
return mocks.workspaceList.value;
},
isSaaSMode: () => mocks.isSaaSMode.value,
+ isLoggedIn: () => mocks.isLoggedIn.value,
loadWorkspace: mocks.loadWorkspace,
loadWorkspaceList: mocks.loadWorkspaceList,
switchWorkspace: mocks.switchWorkspace,
@@ -63,10 +63,6 @@ mocks.useAppStore.mockImplementation((selector: (state: unknown) => unknown) =>
loadServerInfo: vi.fn().mockResolvedValue(undefined),
});
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
vi.mock("@/react/hooks/useAppState", () => ({
useWorkspace: mocks.useWorkspace,
}));
@@ -116,7 +112,8 @@ vi.mock("@/react/components/ui/select", () => ({
),
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
replace: mocks.routerReplace,
back: mocks.routerBack,
@@ -124,10 +121,6 @@ vi.mock("@/router", () => ({
},
}));
-vi.mock("@/router/auth", () => ({
- AUTH_SIGNIN_MODULE: "auth.signin",
-}));
-
vi.mock("@/react/components/BytebaseLogo", () => ({
BytebaseLogo: () => null,
}));
diff --git a/frontend/src/react/pages/auth/OAuth2ConsentPage.tsx b/frontend/src/react/pages/auth/OAuth2ConsentPage.tsx
index 6a24618e0e..bd9d501122 100644
--- a/frontend/src/react/pages/auth/OAuth2ConsentPage.tsx
+++ b/frontend/src/react/pages/auth/OAuth2ConsentPage.tsx
@@ -11,11 +11,9 @@ import {
SelectValue,
} from "@/react/components/ui/select";
import { useWorkspace } from "@/react/hooks/useAppState";
-import { useVueState } from "@/react/hooks/useVueState";
+import { router } from "@/react/router";
+import { AUTH_SIGNIN_MODULE } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { AUTH_SIGNIN_MODULE } from "@/router/auth";
-import { useAuthStore } from "@/store";
const AUTHORIZE_URL = "/api/oauth2/authorize";
@@ -26,16 +24,11 @@ export function OAuth2ConsentPage() {
const [error, setError] = useState("");
const [clientName, setClientName] = useState("");
- // Pinia store singletons are resolved once at the top of the component so
- // the useVueState selector closures don't repeat the use*-prefixed call —
- // which trips the React-hooks-in-callback lint rule (typescript:S6440)
- // despite Pinia memoizing the factory.
- const authStore = useAuthStore();
const loadWorkspace = useAppStore((state) => state.loadWorkspace);
const loadWorkspaceList = useAppStore((state) => state.loadWorkspaceList);
const switchWorkspace = useAppStore((state) => state.switchWorkspace);
- const isLoggedIn = useVueState(() => authStore.isLoggedIn);
+ const isLoggedIn = useAppStore((s) => s.isLoggedIn());
// Workspace context shown on the consent card. On SaaS, every Bytebase
// user belongs to at least one workspace; on self-hosted there's a single
// implicit workspace. We display it so the user can confirm which
diff --git a/frontend/src/react/pages/auth/OAuthCallbackPage.test.tsx b/frontend/src/react/pages/auth/OAuthCallbackPage.test.tsx
index 8e8ba048a1..3afd239b7b 100644
--- a/frontend/src/react/pages/auth/OAuthCallbackPage.test.tsx
+++ b/frontend/src/react/pages/auth/OAuthCallbackPage.test.tsx
@@ -9,7 +9,6 @@ import { IdentityProviderType } from "@/types/proto-es/v1/idp_service_pb";
).IS_REACT_ACT_ENVIRONMENT = true;
const mocks = vi.hoisted(() => ({
- useVueState: vi.fn<(getter: () => unknown) => unknown>((getter) => getter()),
login: vi.fn<(payload: unknown) => Promise<void>>(async () => {}),
useAuthStore: vi.fn(),
routerPush: vi.fn(),
@@ -22,25 +21,24 @@ const mocks = vi.hoisted(() => ({
}));
mocks.useAuthStore.mockImplementation(() => ({ login: mocks.login }));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
vi.mock("@/store", () => ({
useAuthStore: mocks.useAuthStore,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/stores/app", () => ({
+ useAppStore: Object.assign(() => ({}), {
+ getState: () => ({ login: mocks.login, workspaceResourceName: () => "" }),
+ }),
+}));
+
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
push: mocks.routerPush,
currentRoute: mocks.currentRoute,
},
}));
-vi.mock("@/router/auth", () => ({
- AUTH_SIGNIN_MODULE: "auth.signin",
-}));
-
vi.mock("@/utils/sso", () => ({
retrieveOAuthState: mocks.retrieveOAuthState,
clearOAuthState: mocks.clearOAuthState,
@@ -73,6 +71,7 @@ vi.mock("@/types/proto-es/v1/auth_service_pb", async (importOriginal) => {
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
+ initReactI18next: { type: "3rdParty", init: () => {} },
}));
let OAuthCallbackPage: typeof import("./OAuthCallbackPage").OAuthCallbackPage;
diff --git a/frontend/src/react/pages/auth/OAuthCallbackPage.tsx b/frontend/src/react/pages/auth/OAuthCallbackPage.tsx
index 8be5aba722..c535c9dc67 100644
--- a/frontend/src/react/pages/auth/OAuthCallbackPage.tsx
+++ b/frontend/src/react/pages/auth/OAuthCallbackPage.tsx
@@ -3,13 +3,13 @@ import { Loader2 } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/react/components/ui/button";
-import { router } from "@/router";
-import { AUTH_SIGNIN_MODULE } from "@/router/auth";
-import { useAuthStore } from "@/store";
+import { resolveWorkspaceName } from "@/react/lib/workspace";
+import { router } from "@/react/router";
+import { AUTH_SIGNIN_MODULE } from "@/react/router/handles";
+import { useAppStore } from "@/react/stores/app";
import type { OAuthState, OAuthWindowEventPayload } from "@/types/oauth";
import { LoginRequestSchema } from "@/types/proto-es/v1/auth_service_pb";
import { IdentityProviderType } from "@/types/proto-es/v1/idp_service_pb";
-import { resolveWorkspaceName } from "@/utils";
import { clearOAuthState, retrieveOAuthState } from "@/utils/sso";
export function OAuthCallbackPage() {
@@ -125,7 +125,7 @@ export function OAuthCallbackPage() {
return;
}
- await useAuthStore().login({
+ await useAppStore.getState().login({
request: create(LoginRequestSchema, {
idpName,
idpContext: {
diff --git a/frontend/src/react/pages/auth/PasswordForgotPage.test.tsx b/frontend/src/react/pages/auth/PasswordForgotPage.test.tsx
index ec664ec105..e4c7879a63 100644
--- a/frontend/src/react/pages/auth/PasswordForgotPage.test.tsx
+++ b/frontend/src/react/pages/auth/PasswordForgotPage.test.tsx
@@ -22,9 +22,6 @@ const mocks = vi.hoisted(() => {
return {
restriction,
appStoreState,
- useVueState: vi.fn<(getter: () => unknown) => unknown>((getter) =>
- getter()
- ),
useAppStore: Object.assign(
vi.fn((selector?: (s: typeof appStoreState) => unknown) =>
selector ? selector(appStoreState) : appStoreState
@@ -40,10 +37,6 @@ const mocks = vi.hoisted(() => {
};
});
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
vi.mock("@/react/stores/app", () => ({
useAppStore: mocks.useAppStore,
}));
@@ -52,7 +45,8 @@ vi.mock("@/store", () => ({
pushNotification: mocks.pushNotification,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
push: mocks.routerPush,
replace: mocks.routerReplace,
@@ -60,11 +54,6 @@ vi.mock("@/router", () => ({
},
}));
-vi.mock("@/router/auth", () => ({
- AUTH_PASSWORD_RESET_MODULE: "auth.password.reset",
- AUTH_SIGNIN_MODULE: "auth.signin",
-}));
-
vi.mock("@/connect", () => ({
authServiceClientConnect: {
requestPasswordReset: mocks.requestPasswordReset,
@@ -74,10 +63,13 @@ vi.mock("@/connect", () => ({
vi.mock("@/utils", () => {
return {
isValidEmail: (email: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email),
- resolveWorkspaceName: mocks.resolveWorkspaceName,
};
});
+vi.mock("@/react/lib/workspace", () => ({
+ resolveWorkspaceName: mocks.resolveWorkspaceName,
+}));
+
vi.mock("@/assets/logo-full.svg", () => ({
default: "/assets/logo-full.svg",
}));
diff --git a/frontend/src/react/pages/auth/PasswordForgotPage.tsx b/frontend/src/react/pages/auth/PasswordForgotPage.tsx
index 8a1a551048..963aceee09 100644
--- a/frontend/src/react/pages/auth/PasswordForgotPage.tsx
+++ b/frontend/src/react/pages/auth/PasswordForgotPage.tsx
@@ -5,11 +5,15 @@ import { authServiceClientConnect } from "@/connect";
import { Alert } from "@/react/components/ui/alert";
import { Button } from "@/react/components/ui/button";
import { Input } from "@/react/components/ui/input";
+import { resolveWorkspaceName } from "@/react/lib/workspace";
+import { router } from "@/react/router";
+import {
+ AUTH_PASSWORD_RESET_MODULE,
+ AUTH_SIGNIN_MODULE,
+} from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { AUTH_PASSWORD_RESET_MODULE, AUTH_SIGNIN_MODULE } from "@/router/auth";
import { pushNotification } from "@/store";
-import { isValidEmail, resolveWorkspaceName } from "@/utils";
+import { isValidEmail } from "@/utils";
export function PasswordForgotPage() {
const { t } = useTranslation();
diff --git a/frontend/src/react/pages/auth/PasswordResetPage.test.tsx b/frontend/src/react/pages/auth/PasswordResetPage.test.tsx
index 97f8fc4a33..10b4e400f7 100644
--- a/frontend/src/react/pages/auth/PasswordResetPage.test.tsx
+++ b/frontend/src/react/pages/auth/PasswordResetPage.test.tsx
@@ -8,7 +8,6 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
).IS_REACT_ACT_ENVIRONMENT = true;
const mocks = vi.hoisted(() => ({
- useVueState: vi.fn<(getter: () => unknown) => unknown>((getter) => getter()),
appStoreState: {
serverInfo: {
restriction: {
@@ -16,9 +15,9 @@ const mocks = vi.hoisted(() => ({
disallowPasswordSignin: false,
},
},
+ requireResetPassword: (() => true) as () => boolean,
},
useAuthStore: vi.fn(() => ({
- requireResetPassword: false,
setRequireResetPassword: vi.fn(),
login: vi.fn(async () => {}),
})),
@@ -32,10 +31,8 @@ const mocks = vi.hoisted(() => ({
resetPassword: vi.fn(),
requestPasswordReset: vi.fn(),
resolveWorkspaceName: vi.fn(() => undefined),
-}));
-
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
+ login: vi.fn(async () => {}),
+ setRequireResetPassword: vi.fn(),
}));
vi.mock("@/react/hooks/useAppState", () => ({
@@ -52,6 +49,9 @@ vi.mock("@/react/stores/app", () => {
...mocks.appStoreState,
updateUser: mocks.updateUser,
loadServerInfo: vi.fn().mockResolvedValue(undefined),
+ login: mocks.login,
+ setRequireResetPassword: mocks.setRequireResetPassword,
+ workspaceResourceName: () => "",
});
return {
useAppStore: Object.assign(
@@ -62,7 +62,8 @@ vi.mock("@/react/stores/app", () => {
};
});
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
replace: mocks.routerReplace,
push: mocks.routerPush,
@@ -70,10 +71,6 @@ vi.mock("@/router", () => ({
},
}));
-vi.mock("@/router/auth", () => ({
- AUTH_SIGNIN_MODULE: "auth.signin",
-}));
-
vi.mock("@/connect", () => ({
authServiceClientConnect: {
resetPassword: mocks.resetPassword,
@@ -81,11 +78,9 @@ vi.mock("@/connect", () => ({
},
}));
-vi.mock("@/utils", () => {
- return {
- resolveWorkspaceName: mocks.resolveWorkspaceName,
- };
-});
+vi.mock("@/react/lib/workspace", () => ({
+ resolveWorkspaceName: mocks.resolveWorkspaceName,
+}));
vi.mock("@bufbuild/protobuf", async (importOriginal) => {
const actual = await importOriginal<typeof import("@bufbuild/protobuf")>();
@@ -127,6 +122,7 @@ vi.mock("react-i18next", () => ({
t: (key: string, vars?: Record<string, unknown>) =>
vars ? `${key}:${JSON.stringify(vars)}` : key,
}),
+ initReactI18next: { type: "3rdParty", init: () => {} },
}));
let PasswordResetPage: typeof import("./PasswordResetPage").PasswordResetPage;
@@ -174,8 +170,8 @@ beforeEach(async () => {
disallowPasswordSignin: false,
},
};
+ mocks.appStoreState.requireResetPassword = () => true;
mocks.useAuthStore.mockReturnValue({
- requireResetPassword: true,
setRequireResetPassword: vi.fn(),
login: vi.fn(async () => {}),
});
@@ -184,11 +180,7 @@ beforeEach(async () => {
describe("PasswordResetPage", () => {
test("forced-reset mode: redirects when requireResetPassword is false", () => {
- mocks.useAuthStore.mockReturnValue({
- requireResetPassword: false,
- setRequireResetPassword: vi.fn(),
- login: vi.fn(),
- });
+ mocks.appStoreState.requireResetPassword = () => false;
const { render, unmount } = renderIntoContainer(<PasswordResetPage />);
render();
expect(mocks.routerReplace).toHaveBeenCalled();
@@ -254,12 +246,6 @@ describe("PasswordResetPage", () => {
test("code mode: confirm calls resetPassword and logs in on success", async () => {
mocks.currentRoute.value.query = { email: "[email protected]" };
mocks.resetPassword.mockResolvedValue({});
- const login = vi.fn(async () => {});
- mocks.useAuthStore.mockReturnValue({
- requireResetPassword: true,
- setRequireResetPassword: vi.fn(),
- login,
- });
const { container, render, unmount } = renderIntoContainer(
<PasswordResetPage />
);
@@ -289,7 +275,7 @@ describe("PasswordResetPage", () => {
newPassword: "Passw0rd!",
})
);
- expect(login).toHaveBeenCalled();
+ expect(mocks.login).toHaveBeenCalled();
unmount();
});
});
diff --git a/frontend/src/react/pages/auth/PasswordResetPage.tsx b/frontend/src/react/pages/auth/PasswordResetPage.tsx
index 0549e209fe..7aaa3987d2 100644
--- a/frontend/src/react/pages/auth/PasswordResetPage.tsx
+++ b/frontend/src/react/pages/auth/PasswordResetPage.tsx
@@ -10,17 +10,16 @@ import { Button } from "@/react/components/ui/button";
import { Input } from "@/react/components/ui/input";
import { OtpInput } from "@/react/components/ui/otp-input";
import { useCurrentUser } from "@/react/hooks/useAppState";
-import { useVueState } from "@/react/hooks/useVueState";
+import { resolveWorkspaceName } from "@/react/lib/workspace";
+import { router } from "@/react/router";
+import { AUTH_SIGNIN_MODULE } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { AUTH_SIGNIN_MODULE } from "@/router/auth";
-import { pushNotification, useAuthStore } from "@/store";
+import { pushNotification } from "@/store";
import {
LoginRequestSchema,
ResetPasswordRequestSchema,
} from "@/types/proto-es/v1/auth_service_pb";
import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";
-import { resolveWorkspaceName } from "@/utils";
export function PasswordResetPage() {
const { t } = useTranslation();
@@ -38,9 +37,7 @@ export function PasswordResetPage() {
const passwordRestriction = serverInfo?.restriction?.passwordRestriction;
const disallowPasswordSignin =
serverInfo?.restriction?.disallowPasswordSignin ?? false;
- const requireResetPassword = useVueState(
- () => useAuthStore().requireResetPassword
- );
+ const requireResetPassword = useAppStore((s) => s.requireResetPassword());
const currentUser = useCurrentUser();
// This page renders outside any shell, so the workspace bootstrap hasn't
@@ -136,7 +133,7 @@ export function PasswordResetPage() {
style: "SUCCESS",
title: t("common.updated"),
});
- await useAuthStore().login({
+ await useAppStore.getState().login({
request: create(LoginRequestSchema, {
email,
password,
@@ -167,7 +164,7 @@ export function PasswordResetPage() {
style: "SUCCESS",
title: t("common.updated"),
});
- useAuthStore().setRequireResetPassword(false);
+ useAppStore.getState().setRequireResetPassword(false);
router.replace(redirectQuery());
};
diff --git a/frontend/src/react/pages/auth/ProfileSetupPage.tsx b/frontend/src/react/pages/auth/ProfileSetupPage.tsx
index 37b281f3af..7519b30010 100644
--- a/frontend/src/react/pages/auth/ProfileSetupPage.tsx
+++ b/frontend/src/react/pages/auth/ProfileSetupPage.tsx
@@ -6,8 +6,8 @@ import { UserAvatar } from "@/react/components/UserAvatar";
import { Button } from "@/react/components/ui/button";
import { Input } from "@/react/components/ui/input";
import { useCurrentUser, useWorkspace } from "@/react/hooks/useAppState";
+import { router } from "@/react/router";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
import { pushNotification } from "@/store";
import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";
import { WorkspaceSchema } from "@/types/proto-es/v1/workspace_service_pb";
diff --git a/frontend/src/react/pages/auth/SetupPage.test.tsx b/frontend/src/react/pages/auth/SetupPage.test.tsx
index 464c03125a..d8e476072c 100644
--- a/frontend/src/react/pages/auth/SetupPage.test.tsx
+++ b/frontend/src/react/pages/auth/SetupPage.test.tsx
@@ -19,27 +19,21 @@ const mocks = vi.hoisted(() => ({
createProject: vi.fn(),
setupSample: vi.fn(),
updateWorkspaceProfile: vi.fn(),
- useVueState: vi.fn<(getter: () => unknown) => unknown>((getter) => getter()),
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
isReady: mocks.routerIsReady,
push: mocks.routerPush,
},
}));
-vi.mock("@/router/sqlEditor", () => ({
- SQL_EDITOR_HOME_MODULE: "sql-editor.home",
-}));
-
-vi.mock("@/store", () => ({
- useAppFeature: () => ({ value: 0 }),
-}));
-
vi.mock("@/react/stores/app", () => {
const state = {
enableOnboarding: () => true,
+ appFeatures: { "bb.feature.database-change-mode": 0 },
+ loadWorkspaceProfile: vi.fn(async () => undefined),
listRoles: mocks.listRoles,
fetchWorkspaceIamPolicy: mocks.fetchIamPolicy,
getOrFetchProjectByName: mocks.getOrFetchProjectByName,
@@ -56,10 +50,6 @@ vi.mock("@/react/stores/app", () => {
};
});
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
vi.mock("@/react/components/auth/AuthFooter", () => ({
AuthFooter: () => null,
}));
@@ -94,6 +84,7 @@ vi.mock("@/react/components/ResourceIdField", async () => {
});
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: () => ({
t: (key: string, vars?: Record<string, unknown>) =>
vars ? `${key}:${JSON.stringify(vars)}` : key,
diff --git a/frontend/src/react/pages/auth/SetupPage.tsx b/frontend/src/react/pages/auth/SetupPage.tsx
index a31b0a324c..76e7538660 100644
--- a/frontend/src/react/pages/auth/SetupPage.tsx
+++ b/frontend/src/react/pages/auth/SetupPage.tsx
@@ -13,11 +13,10 @@ import {
import { Button } from "@/react/components/ui/button";
import { Input } from "@/react/components/ui/input";
import { RadioGroup, RadioGroupItem } from "@/react/components/ui/radio-group";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useAppFeature } from "@/react/hooks/useAppState";
+import { router } from "@/react/router";
+import { SQL_EDITOR_HOME_MODULE } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { SQL_EDITOR_HOME_MODULE } from "@/router/sqlEditor";
-import { useAppFeature } from "@/store";
import { projectNamePrefix } from "@/store/modules/v1/common";
import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";
import { extractGrpcErrorMessage, getErrorCode } from "@/utils/connect";
@@ -99,9 +98,7 @@ function SetupWizard() {
const [resourceValid, setResourceValid] = useState(false);
const enableOnboarding = useAppStore((s) => s.enableOnboarding());
- const databaseChangeMode = useVueState(
- () => useAppFeature("bb.feature.database-change-mode").value
- );
+ const databaseChangeMode = useAppFeature("bb.feature.database-change-mode");
useEffect(() => {
if (!enableOnboarding) {
diff --git a/frontend/src/react/pages/auth/SigninAdminPage.tsx b/frontend/src/react/pages/auth/SigninAdminPage.tsx
index d4891b24b6..e01c9f909d 100644
--- a/frontend/src/react/pages/auth/SigninAdminPage.tsx
+++ b/frontend/src/react/pages/auth/SigninAdminPage.tsx
@@ -3,7 +3,7 @@ import { useTranslation } from "react-i18next";
import { AuthFooter } from "@/react/components/auth/AuthFooter";
import { PasswordSigninForm } from "@/react/components/auth/PasswordSigninForm";
import { BytebaseLogo } from "@/react/components/BytebaseLogo";
-import { useAuthStore } from "@/store";
+import { useAppStore } from "@/react/stores/app";
import type { LoginRequest } from "@/types/proto-es/v1/auth_service_pb";
export function SigninAdminPage() {
@@ -14,7 +14,7 @@ export function SigninAdminPage() {
if (isLoading) return;
setIsLoading(true);
try {
- await useAuthStore().login({ request, redirect: true });
+ await useAppStore.getState().login({ request, redirect: true });
} finally {
setIsLoading(false);
}
diff --git a/frontend/src/react/pages/auth/SigninPage.test.tsx b/frontend/src/react/pages/auth/SigninPage.test.tsx
index e73075553e..b8b51a1dc2 100644
--- a/frontend/src/react/pages/auth/SigninPage.test.tsx
+++ b/frontend/src/react/pages/auth/SigninPage.test.tsx
@@ -9,7 +9,6 @@ import { IdentityProviderType } from "@/types/proto-es/v1/idp_service_pb";
).IS_REACT_ACT_ENVIRONMENT = true;
const mocks = vi.hoisted(() => ({
- useVueState: vi.fn<(getter: () => unknown) => unknown>((getter) => getter()),
routerPush: vi.fn(),
currentRoute: {
value: { query: {} as Record<string, string | undefined> },
@@ -22,21 +21,14 @@ const mocks = vi.hoisted(() => ({
authStore: null as unknown,
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
push: mocks.routerPush,
currentRoute: mocks.currentRoute,
},
}));
-vi.mock("@/router/auth", () => ({
- AUTH_SIGNUP_MODULE: "auth.signup",
-}));
-
vi.mock("@/store", () => ({
pushNotification: mocks.pushNotification,
useAuthStore: () => mocks.authStore,
@@ -47,6 +39,7 @@ vi.mock("@/react/stores/app", () => {
...(mocks.actuatorStore as Record<string, unknown>),
identityProviderList: () => mocks.identityProviderList,
listIdentityProviders: mocks.listIdentityProviders,
+ login: (mocks.authStore as { login: unknown }).login,
});
return {
useAppStore: Object.assign(
@@ -59,6 +52,9 @@ vi.mock("@/react/stores/app", () => {
vi.mock("@/utils", () => ({
openWindowForSSO: mocks.openWindowForSSO,
+}));
+
+vi.mock("@/react/lib/workspace", () => ({
resolveWorkspaceName: () => undefined,
}));
@@ -67,6 +63,9 @@ vi.mock("react-i18next", () => ({
t: (key: string, vars?: Record<string, unknown>) =>
vars ? `${key}:${JSON.stringify(vars)}` : key,
}),
+ // Completes the mock for the react-i18next migration: `@/react/i18n`
+ // registers this plugin via `i18next.use(...)`.
+ initReactI18next: { type: "3rdParty", init: () => {} },
}));
vi.mock("@/react/components/BytebaseLogo", () => ({
diff --git a/frontend/src/react/pages/auth/SigninPage.tsx b/frontend/src/react/pages/auth/SigninPage.tsx
index f8e4e4923c..7f92b15401 100644
--- a/frontend/src/react/pages/auth/SigninPage.tsx
+++ b/frontend/src/react/pages/auth/SigninPage.tsx
@@ -13,15 +13,16 @@ import {
TabsTrigger,
} from "@/react/components/ui/tabs";
import { useIdentityProviderList } from "@/react/hooks/useAppState";
+import { resolveWorkspaceName } from "@/react/lib/workspace";
+import { router } from "@/react/router";
+import { AUTH_SIGNUP_MODULE } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { AUTH_SIGNUP_MODULE } from "@/router/auth";
-import { pushNotification, useAuthStore } from "@/store";
+import { pushNotification } from "@/store";
import { idpNamePrefix } from "@/store/modules/v1/common";
import type { LoginRequest } from "@/types/proto-es/v1/auth_service_pb";
import type { IdentityProvider } from "@/types/proto-es/v1/idp_service_pb";
import { IdentityProviderType } from "@/types/proto-es/v1/idp_service_pb";
-import { openWindowForSSO, resolveWorkspaceName } from "@/utils";
+import { openWindowForSSO } from "@/utils";
export type SigninPageProps = {
readonly redirect?: boolean;
@@ -77,7 +78,7 @@ export function SigninPage(props: SigninPageProps) {
useEffect(() => {
if (!initialized) return;
if (activeUserCount === 0 && !disallowSignup && !isSaaSMode) {
- router.push({ name: AUTH_SIGNUP_MODULE, replace: true });
+ router.replace({ name: AUTH_SIGNUP_MODULE });
}
}, [initialized, activeUserCount, disallowSignup, isSaaSMode]);
@@ -98,7 +99,7 @@ export function SigninPage(props: SigninPageProps) {
if (isLoading) return;
setIsLoading(true);
try {
- await useAuthStore().login({
+ await useAppStore.getState().login({
request,
redirect,
redirectUrl,
diff --git a/frontend/src/react/pages/auth/SignupPage.tsx b/frontend/src/react/pages/auth/SignupPage.tsx
index 8fc825a63e..721873cd6f 100644
--- a/frontend/src/react/pages/auth/SignupPage.tsx
+++ b/frontend/src/react/pages/auth/SignupPage.tsx
@@ -7,10 +7,9 @@ import { BytebaseLogo } from "@/react/components/BytebaseLogo";
import { Button } from "@/react/components/ui/button";
import { Checkbox } from "@/react/components/ui/checkbox";
import { Input } from "@/react/components/ui/input";
+import { router } from "@/react/router";
+import { AUTH_SIGNIN_MODULE } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { AUTH_SIGNIN_MODULE } from "@/router/auth";
-import { useAuthStore } from "@/store";
import { isValidEmail } from "@/utils";
export function SignupPage() {
@@ -96,7 +95,7 @@ export function SignupPage() {
if (isLoading) return;
setIsLoading(true);
try {
- await useAuthStore().signup({ email, password, name });
+ await useAppStore.getState().signup({ email, password, name });
} finally {
setIsLoading(false);
}
diff --git a/frontend/src/react/pages/auth/TwoFactorRequiredPage.tsx b/frontend/src/react/pages/auth/TwoFactorRequiredPage.tsx
index a7454b1331..6fef121241 100644
--- a/frontend/src/react/pages/auth/TwoFactorRequiredPage.tsx
+++ b/frontend/src/react/pages/auth/TwoFactorRequiredPage.tsx
@@ -1,7 +1,7 @@
import { useTranslation } from "react-i18next";
import { Alert } from "@/react/components/ui/alert";
import { TwoFactorSetupPage } from "@/react/pages/settings/two-factor/TwoFactorSetupPage";
-import { useAuthStore } from "@/store";
+import { useAppStore } from "@/react/stores/app";
export function TwoFactorRequiredPage() {
const { t } = useTranslation();
@@ -12,7 +12,9 @@ export function TwoFactorRequiredPage() {
description={t("two-factor.messages.2fa-required")}
/>
<div className="w-full p-2 sm:p-8 sm:px-16">
- <TwoFactorSetupPage cancelAction={() => useAuthStore().logout()} />
+ <TwoFactorSetupPage
+ cancelAction={() => useAppStore.getState().logout()}
+ />
</div>
</div>
);
diff --git a/frontend/src/react/pages/project/DatabaseChangelogDetailPage.test.tsx b/frontend/src/react/pages/project/DatabaseChangelogDetailPage.test.tsx
index 3731836342..c8b1e17427 100644
--- a/frontend/src/react/pages/project/DatabaseChangelogDetailPage.test.tsx
+++ b/frontend/src/react/pages/project/DatabaseChangelogDetailPage.test.tsx
@@ -42,7 +42,6 @@ const mocks = vi.hoisted(() => {
getChangelogByName: vi.fn(),
useAppStore: vi.fn(),
getTaskRunLog: vi.fn(),
- useVueState: vi.fn((getter: () => unknown) => getter()),
clipboardWriteText,
pushNotification: vi.fn(),
ReadonlyMonaco: vi.fn(
@@ -125,23 +124,17 @@ vi.mock("lucide-react", () => ({
}));
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
push: mocks.routerPush,
},
}));
-vi.mock("@/router/dashboard/projectV1", () => ({
- PROJECT_V1_ROUTE_DATABASES: mocks.projectRouteNames.databases,
- PROJECT_V1_ROUTE_DATABASE_DETAIL: mocks.projectRouteNames.databaseDetail,
- PROJECT_V1_ROUTE_DATABASE_CHANGELOG_DETAIL:
- mocks.projectRouteNames.databaseChangelogDetail,
- PROJECT_V1_ROUTE_SYNC_SCHEMA: mocks.projectRouteNames.syncSchema,
-}));
-
vi.mock("@/react/components/ui/button", () => ({
Button: (props: React.ButtonHTMLAttributes<HTMLButtonElement>) => (
<button {...props} />
@@ -161,10 +154,6 @@ vi.mock("@/react/components/task-run-log", () => ({
TaskRunLogViewer: mocks.TaskRunLogViewer,
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
vi.mock("@/react/stores/app", () => ({
useAppStore: mocks.useAppStore,
}));
@@ -250,7 +239,6 @@ beforeEach(() => {
mocks.useAppStore.mockReset();
mocks.getTaskRunLog.mockReset();
mocks.pushNotification.mockReset();
- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
mocks.ReadonlyMonaco.mockClear();
mocks.ReadonlyDiffMonaco.mockClear();
mocks.TaskRunLogViewer.mockClear();
@@ -337,9 +325,9 @@ describe("DatabaseChangelogDetailPage", () => {
const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseChangelogDetailPage, {
- project: "projects/proj1",
- instance: "instances/inst1",
- database: "instances/inst1/databases/db1",
+ projectId: "proj1",
+ instanceId: "inst1",
+ databaseName: "db1",
changelogId: "7",
})
);
@@ -378,9 +366,9 @@ describe("DatabaseChangelogDetailPage", () => {
const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseChangelogDetailPage, {
- project: "projects/proj1",
- instance: "instances/inst1",
- database: "instances/inst1/databases/db1",
+ projectId: "proj1",
+ instanceId: "inst1",
+ databaseName: "db1",
changelogId: "7",
})
);
@@ -420,9 +408,9 @@ describe("DatabaseChangelogDetailPage", () => {
const { unmount, render } = renderIntoContainer(
createElement(DatabaseChangelogDetailPage, {
- project: "projects/proj1",
- instance: "instances/inst1",
- database: "instances/inst1/databases/from-prop",
+ projectId: "proj1",
+ instanceId: "inst1",
+ databaseName: "from-prop",
changelogId: "7",
})
);
@@ -470,9 +458,9 @@ describe("DatabaseChangelogDetailPage", () => {
const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseChangelogDetailPage, {
- project: "projects/proj1",
- instance: "instances/inst1",
- database: "instances/inst1/databases/db1",
+ projectId: "proj1",
+ instanceId: "inst1",
+ databaseName: "db1",
changelogId: "7",
})
);
@@ -537,9 +525,9 @@ describe("DatabaseChangelogDetailPage", () => {
const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseChangelogDetailPage, {
- project: "projects/proj1",
- instance: "instances/inst1",
- database: "instances/inst1/databases/db1",
+ projectId: "proj1",
+ instanceId: "inst1",
+ databaseName: "db1",
changelogId: "7",
})
);
@@ -592,9 +580,9 @@ describe("DatabaseChangelogDetailPage", () => {
const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseChangelogDetailPage, {
- project: "projects/proj1",
- instance: "instances/inst1",
- database: "instances/inst1/databases/db1",
+ projectId: "proj1",
+ instanceId: "inst1",
+ databaseName: "db1",
changelogId: "7",
})
);
@@ -653,9 +641,9 @@ describe("DatabaseChangelogDetailPage", () => {
const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseChangelogDetailPage, {
- project: "projects/proj1",
- instance: "instances/inst1",
- database: "instances/inst1/databases/db1",
+ projectId: "proj1",
+ instanceId: "inst1",
+ databaseName: "db1",
changelogId: "7",
})
);
@@ -732,9 +720,9 @@ describe("DatabaseChangelogDetailPage", () => {
const createPage = () =>
createElement(DatabaseChangelogDetailPage, {
- project: "projects/proj1",
- instance: "instances/inst1",
- database: "instances/inst1/databases/db1",
+ projectId: "proj1",
+ instanceId: "inst1",
+ databaseName: "db1",
changelogId: "7",
});
const { container, render, unmount } = renderIntoContainer(createPage());
@@ -798,9 +786,9 @@ describe("DatabaseChangelogDetailPage", () => {
const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseChangelogDetailPage, {
- project: "projects/proj1",
- instance: "instances/inst1",
- database: "instances/inst1/databases/db1",
+ projectId: "proj1",
+ instanceId: "inst1",
+ databaseName: "db1",
changelogId: "7",
})
);
@@ -856,9 +844,9 @@ describe("DatabaseChangelogDetailPage", () => {
const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseChangelogDetailPage, {
- project: "projects/proj1",
- instance: "instances/inst1",
- database: "instances/inst1/databases/db1",
+ projectId: "proj1",
+ instanceId: "inst1",
+ databaseName: "db1",
changelogId: "7",
})
);
@@ -911,9 +899,9 @@ describe("DatabaseChangelogDetailPage", () => {
const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseChangelogDetailPage, {
- project: "projects/proj1",
- instance: "instances/inst1",
- database: "instances/inst1/databases/db1",
+ projectId: "proj1",
+ instanceId: "inst1",
+ databaseName: "db1",
changelogId: "7",
})
);
@@ -954,9 +942,9 @@ describe("DatabaseChangelogDetailPage", () => {
const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseChangelogDetailPage, {
- project: "projects/proj1",
- instance: "instances/inst1",
- database: "instances/inst1/databases/db1",
+ projectId: "proj1",
+ instanceId: "inst1",
+ databaseName: "db1",
changelogId: "7",
})
);
@@ -1001,9 +989,9 @@ describe("DatabaseChangelogDetailPage", () => {
const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseChangelogDetailPage, {
- project: "projects/proj1",
- instance: "instances/inst1",
- database: "instances/inst1/databases/db1",
+ projectId: "proj1",
+ instanceId: "inst1",
+ databaseName: "db1",
changelogId: "7",
})
);
@@ -1043,9 +1031,9 @@ describe("DatabaseChangelogDetailPage", () => {
const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseChangelogDetailPage, {
- project: "projects/proj1",
- instance: "instances/inst1",
- database: "instances/inst1/databases/db1",
+ projectId: "proj1",
+ instanceId: "inst1",
+ databaseName: "db1",
changelogId: "7",
})
);
@@ -1065,9 +1053,9 @@ describe("DatabaseChangelogDetailPage", () => {
render(
createElement(DatabaseChangelogDetailPage, {
- project: "projects/proj1",
- instance: "instances/inst1",
- database: "instances/inst1/databases/db1",
+ projectId: "proj1",
+ instanceId: "inst1",
+ databaseName: "db1",
changelogId: "8",
})
);
diff --git a/frontend/src/react/pages/project/DatabaseChangelogDetailPage.tsx b/frontend/src/react/pages/project/DatabaseChangelogDetailPage.tsx
index 7983932699..ac5872b31b 100644
--- a/frontend/src/react/pages/project/DatabaseChangelogDetailPage.tsx
+++ b/frontend/src/react/pages/project/DatabaseChangelogDetailPage.tsx
@@ -7,14 +7,14 @@ import { ReadonlyDiffMonaco, ReadonlyMonaco } from "@/react/components/monaco";
import { TaskRunLogViewer } from "@/react/components/task-run-log";
import { Button } from "@/react/components/ui/button";
import { Switch } from "@/react/components/ui/switch";
-import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
+import { router } from "@/react/router";
import {
PROJECT_V1_ROUTE_DATABASE_CHANGELOG_DETAIL,
PROJECT_V1_ROUTE_DATABASE_DETAIL,
PROJECT_V1_ROUTE_DATABASES,
PROJECT_V1_ROUTE_SYNC_SCHEMA,
-} from "@/router/dashboard/projectV1";
+} from "@/react/router/handles";
+import { useAppStore } from "@/react/stores/app";
import { pushNotification } from "@/store";
import { getTimeForPbTimestampProtoEs } from "@/types";
import type { Changelog } from "@/types/proto-es/v1/database_service_pb";
@@ -33,18 +33,14 @@ import {
formatAbsoluteDateTime,
getInstanceResource,
} from "@/utils";
-import {
- extractInstanceResourceName,
- instanceV1SupportsSchemaRollback,
-} from "@/utils/v1/instance";
-import { extractProjectResourceName } from "@/utils/v1/project";
+import { instanceV1SupportsSchemaRollback } from "@/utils/v1/instance";
import { extractTaskLink } from "@/utils/v1/revision";
import { useProjectDatabaseDetail } from "./database-detail/useProjectDatabaseDetail";
export interface DatabaseChangelogDetailPageProps {
- project: string;
- instance: string;
- database: string;
+ projectId: string;
+ instanceId: string;
+ databaseName: string;
changelogId: string;
}
@@ -194,9 +190,9 @@ function CopyButton({ content }: { content: string }) {
}
export function DatabaseChangelogDetailPage({
- project,
- instance,
- database,
+ projectId,
+ instanceId,
+ databaseName,
changelogId,
}: DatabaseChangelogDetailPageProps) {
const { t } = useTranslation();
@@ -214,10 +210,6 @@ export function DatabaseChangelogDetailPage({
boolean | undefined
>(undefined);
- const projectId = extractProjectResourceName(project);
- const instanceId = extractInstanceResourceName(instance);
- const databaseName = extractDatabaseResourceName(database).databaseName;
-
const detail = useProjectDatabaseDetail({
projectId,
instanceId,
@@ -369,8 +361,8 @@ export function DatabaseChangelogDetailPage({
]);
const databaseDisplayName =
- extractDatabaseResourceName(detail.database?.name ?? database)
- .databaseName || databaseName;
+ extractDatabaseResourceName(detail.database?.name ?? "").databaseName ||
+ databaseName;
const formattedCreateTime = useMemo(() => {
if (!resolvedChangelog?.createTime) {
return "";
diff --git a/frontend/src/react/pages/project/DatabaseRevisionDetailPage.test.tsx b/frontend/src/react/pages/project/DatabaseRevisionDetailPage.test.tsx
index c104ac5d8a..efa4df8c46 100644
--- a/frontend/src/react/pages/project/DatabaseRevisionDetailPage.test.tsx
+++ b/frontend/src/react/pages/project/DatabaseRevisionDetailPage.test.tsx
@@ -39,7 +39,7 @@ const mocks = vi.hoisted(() => {
<div data-testid="revision-detail-panel">{revisionName}</div>
)),
routeNames: {
- databases: "workspace.project.databases",
+ databases: "workspace.project.database",
databaseDetail: "workspace.project.database.detail",
databaseRevisionDetail: "workspace.project.database.revision.detail",
},
@@ -62,19 +62,13 @@ vi.mock("@/react/components/revision", () => ({
RevisionDetailPanel: mocks.RevisionDetailPanel,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
push: mocks.routerPush,
},
}));
-vi.mock("@/router/dashboard/projectV1", () => ({
- PROJECT_V1_ROUTE_DATABASES: mocks.routeNames.databases,
- PROJECT_V1_ROUTE_DATABASE_DETAIL: mocks.routeNames.databaseDetail,
- PROJECT_V1_ROUTE_DATABASE_REVISION_DETAIL:
- mocks.routeNames.databaseRevisionDetail,
-}));
-
vi.mock("./database-detail/useProjectDatabaseDetail", () => ({
useProjectDatabaseDetail: mocks.useProjectDatabaseDetail,
}));
@@ -162,9 +156,9 @@ describe("DatabaseRevisionDetailPage", () => {
});
const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseRevisionDetailPage, {
- project: "projects/proj1",
- instance: "instances/inst1",
- database: "instances/inst1/databases/db-from-prop",
+ projectId: "proj1",
+ instanceId: "inst1",
+ databaseName: "db-from-prop",
revisionId: "7",
})
);
@@ -196,9 +190,9 @@ describe("DatabaseRevisionDetailPage", () => {
});
const { container, render, unmount } = renderIntoContainer(
createElement(DatabaseRevisionDetailPage, {
- project: "projects/proj1",
- instance: "instances/inst1",
- database: "instances/inst1/databases/db-from-prop",
+ projectId: "proj1",
+ instanceId: "inst1",
+ databaseName: "db-from-prop",
revisionId: "7",
})
);
diff --git a/frontend/src/react/pages/project/DatabaseRevisionDetailPage.tsx b/frontend/src/react/pages/project/DatabaseRevisionDetailPage.tsx
index 5c2b9a5e38..87c99a3b9c 100644
--- a/frontend/src/react/pages/project/DatabaseRevisionDetailPage.tsx
+++ b/frontend/src/react/pages/project/DatabaseRevisionDetailPage.tsx
@@ -1,32 +1,26 @@
import { LoaderCircle } from "lucide-react";
import { useTranslation } from "react-i18next";
import { RevisionDetailPanel } from "@/react/components/revision";
-import { router } from "@/router";
+import { router } from "@/react/router";
import {
PROJECT_V1_ROUTE_DATABASE_DETAIL,
PROJECT_V1_ROUTE_DATABASE_REVISION_DETAIL,
PROJECT_V1_ROUTE_DATABASES,
-} from "@/router/dashboard/projectV1";
-import { extractDatabaseResourceName } from "@/utils/v1/database";
-import { extractInstanceResourceName } from "@/utils/v1/instance";
-import { extractProjectResourceName } from "@/utils/v1/project";
+} from "@/react/router/handles";
import { useProjectDatabaseDetail } from "./database-detail/useProjectDatabaseDetail";
export function DatabaseRevisionDetailPage({
- project,
- instance,
- database,
+ projectId,
+ instanceId,
+ databaseName,
revisionId,
}: {
- project: string;
- instance: string;
- database: string;
+ projectId: string;
+ instanceId: string;
+ databaseName: string;
revisionId: string;
}) {
const { t } = useTranslation();
- const projectId = extractProjectResourceName(project);
- const { databaseName } = extractDatabaseResourceName(database);
- const instanceId = extractInstanceResourceName(instance);
const detail = useProjectDatabaseDetail({
projectId,
instanceId,
diff --git a/frontend/src/react/pages/project/ProjectAccessGrantsPage.tsx b/frontend/src/react/pages/project/ProjectAccessGrantsPage.tsx
index 8fc6e9c798..693cfc4942 100644
--- a/frontend/src/react/pages/project/ProjectAccessGrantsPage.tsx
+++ b/frontend/src/react/pages/project/ProjectAccessGrantsPage.tsx
@@ -32,11 +32,11 @@ import {
import { Tooltip } from "@/react/components/ui/tooltip";
import { useCurrentUser } from "@/react/hooks/useAppState";
import { PagedTableFooter, usePagedData } from "@/react/hooks/usePagedData";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
+import { router } from "@/react/router";
import { useAppStore } from "@/react/stores/app";
import type { AccessGrantFilter as AccessFilter } from "@/react/stores/app/types";
-import { router } from "@/router";
-import { featureToRef, pushNotification } from "@/store";
+import { pushNotification } from "@/store";
import { extractUserEmail, projectNamePrefix } from "@/store/modules/v1/common";
import { getTimeForPbTimestampProtoEs } from "@/types";
import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";
@@ -116,12 +116,10 @@ export function ProjectAccessGrantsPage({ projectId }: { projectId: string }) {
const currentUser = useCurrentUser();
const projectName = `${projectNamePrefix}${projectId}`;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
- const hasJITFeature = useVueState(
- () => featureToRef(PlanFeature.FEATURE_JIT).value
+ const hasJITFeature = useAppStore((s) =>
+ s.hasInstanceFeature(PlanFeature.FEATURE_JIT)
);
const canList = useMemo(
() =>
diff --git a/frontend/src/react/pages/project/ProjectAuditLogPage.tsx b/frontend/src/react/pages/project/ProjectAuditLogPage.tsx
index 56acd6e64b..9f76ec89fc 100644
--- a/frontend/src/react/pages/project/ProjectAuditLogPage.tsx
+++ b/frontend/src/react/pages/project/ProjectAuditLogPage.tsx
@@ -1,7 +1,7 @@
import { useMemo } from "react";
import { AuditLogTable } from "@/react/components/AuditLogTable";
import { FeatureAttention } from "@/react/components/FeatureAttention";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { useAppStore } from "@/react/stores/app";
import { projectNamePrefix } from "@/store/modules/v1/common";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
@@ -12,9 +12,7 @@ export function ProjectAuditLogPage({ projectId }: { projectId: string }) {
// subscribe to re-render on project cache change
const projectsByName = useAppStore((s) => s.projectsByName);
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
const canExport = project
? hasProjectPermissionV2(project, "bb.auditLogs.export")
diff --git a/frontend/src/react/pages/project/ProjectDataExportPage.tsx b/frontend/src/react/pages/project/ProjectDataExportPage.tsx
index 7bf414f1ee..f5e20a0f20 100644
--- a/frontend/src/react/pages/project/ProjectDataExportPage.tsx
+++ b/frontend/src/react/pages/project/ProjectDataExportPage.tsx
@@ -13,12 +13,14 @@ import { Alert } from "@/react/components/ui/alert";
import { Button } from "@/react/components/ui/button";
import { Tooltip } from "@/react/components/ui/tooltip";
import { PagedTableFooter, usePagedData } from "@/react/hooks/usePagedData";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { displayRoleTitleFromList } from "@/react/lib/role";
+import { router } from "@/react/router";
+import {
+ SQL_EDITOR_HOME_MODULE,
+ WORKSPACE_ROUTE_USER_PROFILE,
+} from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { WORKSPACE_ROUTE_USER_PROFILE } from "@/router/dashboard/workspaceRoutes";
-import { SQL_EDITOR_HOME_MODULE } from "@/router/sqlEditor";
import { projectNamePrefix } from "@/store/modules/v1/common";
import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";
import { ApprovalStatus, RiskLevel } from "@/types/proto-es/v1/common_pb";
@@ -51,9 +53,7 @@ export function ProjectDataExportPage({ projectId }: { projectId: string }) {
);
const projectName = `${projectNamePrefix}${projectId}`;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
const [showDrawer, setShowDrawer] = useState(false);
@@ -476,12 +476,8 @@ function IssueListItem({
);
const creator = creatorUser || unknownUser(issue.creator);
- const issueProject = useVueState(() =>
- useAppStore
- .getState()
- .getProjectByName(
- `${projectNamePrefix}${extractProjectResourceName(issue.name)}`
- )
+ const issueProject = useProjectByName(
+ `${projectNamePrefix}${extractProjectResourceName(issue.name)}`
);
const createTimeTs = Math.floor(
diff --git a/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx b/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx
index 725919d8e5..bc14a2440f 100644
--- a/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx
+++ b/frontend/src/react/pages/project/ProjectDatabaseDetailPage.test.tsx
@@ -193,10 +193,12 @@ vi.mock("lucide-react", async (importOriginal) => {
});
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
replace: mocks.routerReplace,
push: mocks.routerPush,
@@ -205,10 +207,6 @@ vi.mock("@/router", () => ({
},
}));
-vi.mock("@/router/dashboard/projectV1", () => ({
- PROJECT_V1_ROUTE_DATABASE_DETAIL: mocks.routeNames.databaseDetail,
-}));
-
vi.mock("@/react/components/ui/tabs", () => ({
Tabs: ({
value,
diff --git a/frontend/src/react/pages/project/ProjectDatabaseDetailPage.tsx b/frontend/src/react/pages/project/ProjectDatabaseDetailPage.tsx
index fb852082ee..e600e0bba8 100644
--- a/frontend/src/react/pages/project/ProjectDatabaseDetailPage.tsx
+++ b/frontend/src/react/pages/project/ProjectDatabaseDetailPage.tsx
@@ -3,7 +3,6 @@ import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
import { LoaderCircle } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
-import type { LocationQueryRaw } from "vue-router";
import { ComponentPermissionGuard } from "@/react/components/ComponentPermissionGuard";
import { TransferProjectSheet } from "@/react/components/database";
import { Alert } from "@/react/components/ui/alert";
@@ -14,9 +13,9 @@ import {
DialogTitle,
} from "@/react/components/ui/dialog";
import { Tabs, TabsList, TabsTrigger } from "@/react/components/ui/tabs";
+import { router } from "@/react/router";
+import { PROJECT_V1_ROUTE_DATABASE_DETAIL } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_DATABASE_DETAIL } from "@/router/dashboard/projectV1";
import { pushNotification } from "@/store";
import {
BatchUpdateDatabasesRequestSchema,
@@ -49,7 +48,7 @@ const buildDatabaseDetailRoute = (
},
options?: {
hash?: string;
- query?: LocationQueryRaw;
+ query?: Record<string, string | undefined>;
}
) => {
const databaseMatches = database.name.match(
@@ -76,7 +75,7 @@ export interface ProjectDatabaseDetailPageProps {
instanceId: string;
databaseName: string;
hash?: string;
- query?: LocationQueryRaw;
+ query?: Record<string, string | undefined>;
}
export function ProjectDatabaseDetailPage({
diff --git a/frontend/src/react/pages/project/ProjectDatabaseGroupCreatePage.tsx b/frontend/src/react/pages/project/ProjectDatabaseGroupCreatePage.tsx
index 48f661873d..08feb5c81a 100644
--- a/frontend/src/react/pages/project/ProjectDatabaseGroupCreatePage.tsx
+++ b/frontend/src/react/pages/project/ProjectDatabaseGroupCreatePage.tsx
@@ -1,8 +1,8 @@
import { DatabaseGroupForm } from "@/react/components/DatabaseGroupForm";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
+import { router } from "@/react/router";
+import { PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL } from "@/router/dashboard/projectV1";
import { projectNamePrefix } from "@/store/modules/v1/common";
export function ProjectDatabaseGroupCreatePage({
@@ -14,9 +14,7 @@ export function ProjectDatabaseGroupCreatePage({
// subscribe to re-render on project cache change
const projectsByName = useAppStore((s) => s.projectsByName);
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
if (!project) return null;
diff --git a/frontend/src/react/pages/project/ProjectDatabaseGroupDetailPage.tsx b/frontend/src/react/pages/project/ProjectDatabaseGroupDetailPage.tsx
index 45badb290f..16e582d6eb 100644
--- a/frontend/src/react/pages/project/ProjectDatabaseGroupDetailPage.tsx
+++ b/frontend/src/react/pages/project/ProjectDatabaseGroupDetailPage.tsx
@@ -16,12 +16,11 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/react/components/ui/dropdown-menu";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { preCreateIssue } from "@/react/lib/plan/issue";
+import { router } from "@/react/router";
+import { PROJECT_V1_ROUTE_DATABASE_GROUPS } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_DATABASE_GROUPS } from "@/router/dashboard/projectV1";
-import { hasFeature } from "@/store";
import {
databaseGroupNamePrefix,
projectNamePrefix,
@@ -47,9 +46,7 @@ export function ProjectDatabaseGroupDetailPage({
void projectsByName;
const projectName = `${projectNamePrefix}${projectId}`;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
const resourceName = `${projectName}/${databaseGroupNamePrefix}${databaseGroupName}`;
@@ -73,8 +70,8 @@ export function ProjectDatabaseGroupDetailPage({
});
}, [resourceName]);
- const hasDatabaseGroupFeature = useVueState(() =>
- hasFeature(PlanFeature.FEATURE_DATABASE_GROUPS)
+ const hasDatabaseGroupFeature = useAppStore((s) =>
+ s.hasFeature(PlanFeature.FEATURE_DATABASE_GROUPS)
);
const hasMatchedDatabases = useMemo(
diff --git a/frontend/src/react/pages/project/ProjectDatabaseGroupsPage.tsx b/frontend/src/react/pages/project/ProjectDatabaseGroupsPage.tsx
index 795c34c8f7..d499fb4f19 100644
--- a/frontend/src/react/pages/project/ProjectDatabaseGroupsPage.tsx
+++ b/frontend/src/react/pages/project/ProjectDatabaseGroupsPage.tsx
@@ -10,13 +10,13 @@ import {
DialogContent,
DialogTitle,
} from "@/react/components/ui/dialog";
-import { useVueState } from "@/react/hooks/useVueState";
-import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
+import { router } from "@/react/router";
import {
PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,
PROJECT_V1_ROUTE_DATABASE_GROUPS_CREATE,
-} from "@/router/dashboard/projectV1";
+} from "@/react/router/handles";
+import { useAppStore } from "@/react/stores/app";
import {
getProjectNameAndDatabaseGroupName,
projectNamePrefix,
@@ -37,9 +37,7 @@ export function ProjectDatabaseGroupsPage({
void projectsByName;
const projectName = `${projectNamePrefix}${projectId}`;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
const [dbGroupList, setDbGroupList] = useState<DatabaseGroup[]>([]);
const [loading, setLoading] = useState(true);
diff --git a/frontend/src/react/pages/project/ProjectDatabasesPage.tsx b/frontend/src/react/pages/project/ProjectDatabasesPage.tsx
index 7f70fa99c9..e0e145e73a 100644
--- a/frontend/src/react/pages/project/ProjectDatabasesPage.tsx
+++ b/frontend/src/react/pages/project/ProjectDatabasesPage.tsx
@@ -25,7 +25,7 @@ import {
AlertDialogTitle,
} from "@/react/components/ui/alert-dialog";
import { Button } from "@/react/components/ui/button";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import type { DatabaseFilter } from "@/react/lib/databaseFilter";
import { preCreateIssue } from "@/react/lib/plan/issue";
import { useAppStore } from "@/react/stores/app";
@@ -72,9 +72,7 @@ export function ProjectDatabasesPage({ projectId }: { projectId: string }) {
// subscribe to re-render on project cache change
const projectsByName = useAppStore((s) => s.projectsByName);
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
const isDefault = isDefaultProject(projectName);
const hasProjectPermission = useCallback(
diff --git a/frontend/src/react/pages/project/ProjectGitOpsPage.tsx b/frontend/src/react/pages/project/ProjectGitOpsPage.tsx
index bc2838a04a..006e902660 100644
--- a/frontend/src/react/pages/project/ProjectGitOpsPage.tsx
+++ b/frontend/src/react/pages/project/ProjectGitOpsPage.tsx
@@ -14,12 +14,12 @@ import {
TabsPanel,
TabsTrigger,
} from "@/react/components/ui/tabs";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { cn } from "@/react/lib/utils";
+import { router } from "@/react/router";
+import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
import { extractWorkloadIdentityId } from "@/react/stores/app/workloadIdentity";
-import { router } from "@/router";
-import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";
import { projectNamePrefix } from "@/store/modules/v1/common";
import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";
import type { WorkloadIdentity } from "@/types/proto-es/v1/workload_identity_service_pb";
@@ -47,9 +47,7 @@ export function ProjectGitOpsPage({ projectId }: { projectId: string }) {
const projectName = `${projectNamePrefix}${projectId}`;
// subscribe to re-render on project cache change
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
const [showCreateDrawer, setShowCreateDrawer] = useState(false);
const [selectedIdentityName, setSelectedIdentityName] = useState("");
diff --git a/frontend/src/react/pages/project/ProjectIssueDashboardPage.tsx b/frontend/src/react/pages/project/ProjectIssueDashboardPage.tsx
index 2ea50a1e4a..89820e9e1f 100644
--- a/frontend/src/react/pages/project/ProjectIssueDashboardPage.tsx
+++ b/frontend/src/react/pages/project/ProjectIssueDashboardPage.tsx
@@ -14,8 +14,8 @@ import { Alert } from "@/react/components/ui/alert";
import { useCurrentUser } from "@/react/hooks/useAppState";
import { PagedTableFooter, usePagedData } from "@/react/hooks/usePagedData";
import { refreshIssueList } from "@/react/lib/issue/issueListRefresh";
+import { router } from "@/react/router";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
import { projectNamePrefix } from "@/store/modules/v1/common";
import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
diff --git a/frontend/src/react/pages/project/ProjectIssueDetailPage.test.tsx b/frontend/src/react/pages/project/ProjectIssueDetailPage.test.tsx
index abdf20c9d1..11088a1771 100644
--- a/frontend/src/react/pages/project/ProjectIssueDetailPage.test.tsx
+++ b/frontend/src/react/pages/project/ProjectIssueDetailPage.test.tsx
@@ -28,15 +28,22 @@ vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: (getter: () => unknown) => getter(),
-}));
-
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
currentRoute: { value: { query: {} } },
replace: vi.fn(),
},
+ useCurrentRoute: () => ({
+ name: undefined,
+ fullPath: "",
+ hash: "",
+ params: {},
+ query: {},
+ requiredPermissions: [],
+ overrideDocumentTitle: false,
+ meta: {},
+ }),
}));
vi.mock("./issue-detail/hooks/useIssueDetailPage", () => ({
diff --git a/frontend/src/react/pages/project/ProjectIssueDetailPage.tsx b/frontend/src/react/pages/project/ProjectIssueDetailPage.tsx
index 0c1523efbd..92a6b43fec 100644
--- a/frontend/src/react/pages/project/ProjectIssueDetailPage.tsx
+++ b/frontend/src/react/pages/project/ProjectIssueDetailPage.tsx
@@ -8,9 +8,8 @@ import {
LAYER_BACKDROP_CLASS,
LAYER_SURFACE_CLASS,
} from "@/react/components/ui/layer";
-import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
-import { router } from "@/router";
+import { router, useCurrentRoute } from "@/react/router";
import { IssueDetailActivity } from "./issue-detail/components/IssueDetailActivity";
import { IssueDetailBranchContent } from "./issue-detail/components/IssueDetailBranchContent";
import { IssueDetailHeader } from "./issue-detail/components/IssueDetailHeader";
@@ -31,10 +30,9 @@ export function ProjectIssueDetailPage(props: ProjectIssueDetailPageProps) {
// Selected spec id is mirrored to the URL as ?spec=<id> so that links
// (e.g. from audit rows in the comment list) can deep-link a spec without
// navigating away from the issue detail page.
- const databaseChangeSelectedSpecId = useVueState(() => {
- const v = router.currentRoute.value.query.spec;
- return typeof v === "string" ? v : "";
- });
+ const specQuery = useCurrentRoute().query.spec;
+ const databaseChangeSelectedSpecId =
+ typeof specQuery === "string" ? specQuery : "";
const setDatabaseChangeSelectedSpecId = useCallback((id: string) => {
void router.replace({
query: { ...router.currentRoute.value.query, spec: id || undefined },
diff --git a/frontend/src/react/pages/project/ProjectMaskingExemptionCreatePage.tsx b/frontend/src/react/pages/project/ProjectMaskingExemptionCreatePage.tsx
index ae3b82bca6..ba4d875e74 100644
--- a/frontend/src/react/pages/project/ProjectMaskingExemptionCreatePage.tsx
+++ b/frontend/src/react/pages/project/ProjectMaskingExemptionCreatePage.tsx
@@ -20,13 +20,13 @@ import { ExpirationPicker } from "@/react/components/ui/expiration-picker";
import { FeatureModal } from "@/react/components/ui/feature-modal";
import { Input } from "@/react/components/ui/input";
import { Tooltip } from "@/react/components/ui/tooltip";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { getClassificationLevelOptions } from "@/react/lib/sensitive-data/components-utils";
import { rewriteResourceDatabase } from "@/react/lib/sensitive-data/exemptionDataUtils";
import { getExpressionsForDatabaseResource } from "@/react/lib/sensitive-data/utils";
+import { router } from "@/react/router";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { hasFeature, pushNotification } from "@/store";
+import { pushNotification } from "@/store";
import { projectNamePrefix } from "@/store/modules/v1/common";
import type { DatabaseResource } from "@/types";
import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";
@@ -64,9 +64,7 @@ export function ProjectMaskingExemptionCreatePage({
const projectName = `${projectNamePrefix}${projectId}`;
// subscribe to re-render on project cache change
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
// Ensure classification config is loaded
useEffect(() => {
@@ -75,8 +73,8 @@ export function ProjectMaskingExemptionCreatePage({
.getOrFetchSettingByName(Setting_SettingName.DATA_CLASSIFICATION, true);
}, []);
- const hasRequiredFeature = useVueState(() =>
- hasFeature(PlanFeature.FEATURE_DATA_MASKING)
+ const hasRequiredFeature = useAppStore((s) =>
+ s.hasFeature(PlanFeature.FEATURE_DATA_MASKING)
);
// Form state
diff --git a/frontend/src/react/pages/project/ProjectMaskingExemptionPage.tsx b/frontend/src/react/pages/project/ProjectMaskingExemptionPage.tsx
index 56bf97fae5..334e23c8e9 100644
--- a/frontend/src/react/pages/project/ProjectMaskingExemptionPage.tsx
+++ b/frontend/src/react/pages/project/ProjectMaskingExemptionPage.tsx
@@ -30,7 +30,7 @@ import {
} from "@/react/components/ui/table";
import { Tabs, TabsList, TabsTrigger } from "@/react/components/ui/tabs";
import { useCurrentUser } from "@/react/hooks/useAppState";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import {
buildMemberSummary,
generateGrantTitle,
@@ -45,10 +45,10 @@ import type {
ExemptionMember,
} from "@/react/lib/sensitive-data/types";
import { cn } from "@/react/lib/utils";
+import { router } from "@/react/router";
+import { PROJECT_V1_ROUTE_MASKING_EXEMPTION_CREATE } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_MASKING_EXEMPTION_CREATE } from "@/router/dashboard/projectV1";
-import { extractUserEmail, hasFeature, pushNotification } from "@/store";
+import { extractUserEmail, pushNotification } from "@/store";
import { projectNamePrefix } from "@/store/modules/v1/common";
import type { DatabaseResource } from "@/types";
import {
@@ -95,9 +95,7 @@ export function ProjectMaskingExemptionPage({
const projectName = `${projectNamePrefix}${projectId}`;
// subscribe to re-render on project cache change
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
const showDatabaseLink = useMemo(
() =>
project ? hasProjectPermissionV2(project, "bb.databases.get") : false,
@@ -129,8 +127,8 @@ export function ProjectMaskingExemptionPage({
: false,
[project]
);
- const hasSensitiveDataFeature = useVueState(() =>
- hasFeature(PlanFeature.FEATURE_DATA_MASKING)
+ const hasSensitiveDataFeature = useAppStore((s) =>
+ s.hasFeature(PlanFeature.FEATURE_DATA_MASKING)
);
const membersFromVue = useExemptionDataReact(projectName);
diff --git a/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx b/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx
index 2ec0f15dba..2a6a0f750f 100644
--- a/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx
+++ b/frontend/src/react/pages/project/ProjectPlanDashboardPage.tsx
@@ -48,17 +48,17 @@ import { useCurrentUser } from "@/react/hooks/useAppState";
import { useColumnWidths } from "@/react/hooks/useColumnWidths";
import { useEscapeKey } from "@/react/hooks/useEscapeKey";
import { PagedTableFooter, usePagedData } from "@/react/hooks/usePagedData";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { useSessionPageSize } from "@/react/hooks/useSessionPageSize";
-import { useVueState } from "@/react/hooks/useVueState";
import { applyPlanTitleToQuery } from "@/react/lib/plan/title";
import { cn } from "@/react/lib/utils";
-import { useAppStore } from "@/react/stores/app";
-import { buildPlanFindBySearchParams } from "@/react/stores/app/plan";
-import { router } from "@/router";
+import { router } from "@/react/router";
import {
PROJECT_V1_ROUTE_PLAN_DETAIL,
PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
-} from "@/router/dashboard/projectV1";
+} from "@/react/router/handles";
+import { useAppStore } from "@/react/stores/app";
+import { buildPlanFindBySearchParams } from "@/react/stores/app/plan";
import { pushNotification } from "@/store";
import { projectNamePrefix } from "@/store/modules/v1/common";
import {
@@ -120,9 +120,7 @@ export function ProjectPlanDashboardPage({ projectId }: { projectId: string }) {
const projectName = `${projectNamePrefix}${projectId}`;
// subscribe to re-render on project cache change
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
const me = useCurrentUser();
const [showAddSpecDrawer, setShowAddSpecDrawer] = useState(false);
diff --git a/frontend/src/react/pages/project/ProjectReleaseDashboardPage.tsx b/frontend/src/react/pages/project/ProjectReleaseDashboardPage.tsx
index dfeaa02043..8e84680e29 100644
--- a/frontend/src/react/pages/project/ProjectReleaseDashboardPage.tsx
+++ b/frontend/src/react/pages/project/ProjectReleaseDashboardPage.tsx
@@ -17,8 +17,8 @@ import {
} from "@/react/components/ui/table";
import { PagedTableFooter, usePagedData } from "@/react/hooks/usePagedData";
import { cn } from "@/react/lib/utils";
+import { router } from "@/react/router";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
import { projectNamePrefix } from "@/store/modules/v1/common";
import { getTimeForPbTimestampProtoEs } from "@/types";
import { State } from "@/types/proto-es/v1/common_pb";
diff --git a/frontend/src/react/pages/project/ProjectReleaseDetailPage.tsx b/frontend/src/react/pages/project/ProjectReleaseDetailPage.tsx
index 427012064c..bc4c6acb3a 100644
--- a/frontend/src/react/pages/project/ProjectReleaseDetailPage.tsx
+++ b/frontend/src/react/pages/project/ProjectReleaseDetailPage.tsx
@@ -25,7 +25,7 @@ import {
SheetHeader,
SheetTitle,
} from "@/react/components/ui/sheet";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { useAppStore } from "@/react/stores/app";
import { pushNotification } from "@/store";
import { projectNamePrefix } from "@/store/modules/v1/common";
@@ -53,9 +53,7 @@ export function ProjectReleaseDetailPage({
const release = useAppStore((state) => state.getReleaseByName(releaseName));
// subscribe to re-render on project cache change
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
diff --git a/frontend/src/react/pages/project/ProjectSettingsPage.tsx b/frontend/src/react/pages/project/ProjectSettingsPage.tsx
index 0b840117ce..8e793670ed 100644
--- a/frontend/src/react/pages/project/ProjectSettingsPage.tsx
+++ b/frontend/src/react/pages/project/ProjectSettingsPage.tsx
@@ -16,17 +16,17 @@ import { Input } from "@/react/components/ui/input";
import { NumberInput } from "@/react/components/ui/number-input";
import { Switch } from "@/react/components/ui/switch";
import { Tooltip } from "@/react/components/ui/tooltip";
-import { useVueState } from "@/react/hooks/useVueState";
-import { useAppStore } from "@/react/stores/app";
-import { useSQLReviewStore } from "@/react/stores/sqlReview";
-import { useWorkspaceApprovalSettingStore } from "@/react/stores/workspaceApprovalSetting";
-import { router } from "@/router";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
+import { router, useCurrentRoute } from "@/react/router";
import {
PROJECT_V1_ROUTE_DASHBOARD,
WORKSPACE_ROUTE_CUSTOM_APPROVAL,
WORKSPACE_ROUTE_SQL_REVIEW_CREATE,
WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,
-} from "@/router/dashboard/workspaceRoutes";
+} from "@/react/router/handles";
+import { useAppStore } from "@/react/stores/app";
+import { useSQLReviewStore } from "@/react/stores/sqlReview";
+import { useWorkspaceApprovalSettingStore } from "@/react/stores/workspaceApprovalSetting";
import { pushNotification } from "@/store";
import { projectNamePrefix } from "@/store/modules/v1/common";
import type { Permission, SQLReviewPolicy } from "@/types";
@@ -129,15 +129,11 @@ export function ProjectSettingsPage() {
const projectsByName = useAppStore((s) => s.projectsByName);
const reviewStore = useSQLReviewStore();
- const projectId = useVueState(
- () => router.currentRoute.value.params.projectId as string
- );
+ const projectId = useCurrentRoute().params.projectId as string;
const projectName = `${projectNamePrefix}${projectId}`;
// subscribe to re-render on project cache change
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
const isDefault = isDefaultProject(projectName);
const hasPermission = useCallback(
@@ -169,12 +165,8 @@ export function ProjectSettingsPage() {
// -----------------------------------------------------------------------
// Security state
// -----------------------------------------------------------------------
- const reviewPolicyList = useVueState(
- () => reviewStore.reviewPolicyList ?? []
- );
- const currentReviewPolicy = useVueState(() =>
- reviewStore.getReviewPolicyByResouce(projectName)
- );
+ const reviewPolicyList = reviewStore.reviewPolicyList;
+ const currentReviewPolicy = reviewStore.getReviewPolicyByResouce(projectName);
const [pendingReviewPolicy, setPendingReviewPolicy] = useState<
SQLReviewPolicy | undefined
>(undefined);
diff --git a/frontend/src/react/pages/project/ProjectSyncSchemaPage.tsx b/frontend/src/react/pages/project/ProjectSyncSchemaPage.tsx
index 7dcde64e52..1888d9849e 100644
--- a/frontend/src/react/pages/project/ProjectSyncSchemaPage.tsx
+++ b/frontend/src/react/pages/project/ProjectSyncSchemaPage.tsx
@@ -44,13 +44,13 @@ import {
} from "@/react/components/ui/sheet";
import { useClickOutside } from "@/react/hooks/useClickOutside";
import { useEscapeKey } from "@/react/hooks/useEscapeKey";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { keyValueStorage } from "@/react/lib/keyValueStorage";
import { applyPlanTitleToQuery } from "@/react/lib/plan/title";
import { cn } from "@/react/lib/utils";
+import { router } from "@/react/router";
+import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";
import { pushNotification } from "@/store";
import { projectNamePrefix } from "@/store/modules/v1/common";
import {
@@ -143,9 +143,7 @@ export function ProjectSyncSchemaPage({ projectId }: { projectId: string }) {
const projectName = `${projectNamePrefix}${projectId}`;
// subscribe to re-render on project cache change
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
const [isLoading, setIsLoading] = useState(true);
const [currentStep, setCurrentStep] = useState<Step>(
diff --git a/frontend/src/react/pages/project/ProjectWebhookCreatePage.tsx b/frontend/src/react/pages/project/ProjectWebhookCreatePage.tsx
index 5b4bd122b5..90637960d3 100644
--- a/frontend/src/react/pages/project/ProjectWebhookCreatePage.tsx
+++ b/frontend/src/react/pages/project/ProjectWebhookCreatePage.tsx
@@ -1,6 +1,6 @@
import { create as createProto } from "@bufbuild/protobuf";
import { useMemo } from "react";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { useAppStore } from "@/react/stores/app";
import { projectNamePrefix } from "@/store/modules/v1/common";
import { State, WebhookType } from "@/types/proto-es/v1/common_pb";
@@ -16,9 +16,7 @@ export function ProjectWebhookCreatePage({ projectId }: { projectId: string }) {
const projectName = `${projectNamePrefix}${projectId}`;
// subscribe to re-render on project cache change
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
const allowEdit = useMemo(() => {
if (!project) return false;
diff --git a/frontend/src/react/pages/project/ProjectWebhookDetailPage.tsx b/frontend/src/react/pages/project/ProjectWebhookDetailPage.tsx
index 7abe25f611..eb2285df87 100644
--- a/frontend/src/react/pages/project/ProjectWebhookDetailPage.tsx
+++ b/frontend/src/react/pages/project/ProjectWebhookDetailPage.tsx
@@ -1,6 +1,6 @@
import { create as createProto } from "@bufbuild/protobuf";
import { useMemo } from "react";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { useAppStore } from "@/react/stores/app";
import { projectNamePrefix } from "@/store/modules/v1/common";
import { State } from "@/types/proto-es/v1/common_pb";
@@ -22,9 +22,7 @@ export function ProjectWebhookDetailPage({
const projectName = `${projectNamePrefix}${projectId}`;
// subscribe to re-render on project cache change
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
const webhook = useMemo(() => {
if (!project) return undefined;
diff --git a/frontend/src/react/pages/project/ProjectWebhookForm.tsx b/frontend/src/react/pages/project/ProjectWebhookForm.tsx
index f268e05f7b..33abe26b5a 100644
--- a/frontend/src/react/pages/project/ProjectWebhookForm.tsx
+++ b/frontend/src/react/pages/project/ProjectWebhookForm.tsx
@@ -19,14 +19,14 @@ import {
import { Input } from "@/react/components/ui/input";
import { Tooltip } from "@/react/components/ui/tooltip";
import { WebhookTypeIcon } from "@/react/components/WebhookTypeIcon";
-import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
+import { router } from "@/react/router";
import {
PROJECT_V1_ROUTE_WEBHOOK_DETAIL,
PROJECT_V1_ROUTE_WEBHOOKS,
-} from "@/router/dashboard/projectV1";
-import { WORKSPACE_ROUTE_IM } from "@/router/dashboard/workspaceRoutes";
-import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";
+ SETTING_ROUTE_WORKSPACE_GENERAL,
+ WORKSPACE_ROUTE_IM,
+} from "@/react/router/handles";
+import { useAppStore } from "@/react/stores/app";
import { pushNotification } from "@/store";
import {
projectWebhookV1ActivityItemList,
diff --git a/frontend/src/react/pages/project/ProjectWebhooksPage.tsx b/frontend/src/react/pages/project/ProjectWebhooksPage.tsx
index ceed2737bd..6d38bb59ac 100644
--- a/frontend/src/react/pages/project/ProjectWebhooksPage.tsx
+++ b/frontend/src/react/pages/project/ProjectWebhooksPage.tsx
@@ -23,13 +23,13 @@ import {
TableRow,
} from "@/react/components/ui/table";
import { WebhookTypeIcon } from "@/react/components/WebhookTypeIcon";
-import { useVueState } from "@/react/hooks/useVueState";
-import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
+import { router } from "@/react/router";
import {
PROJECT_V1_ROUTE_WEBHOOK_CREATE,
PROJECT_V1_ROUTE_WEBHOOK_DETAIL,
-} from "@/router/dashboard/projectV1";
+} from "@/react/router/handles";
+import { useAppStore } from "@/react/stores/app";
import { pushNotification } from "@/store";
import { projectNamePrefix } from "@/store/modules/v1/common";
import { projectWebhookV1ActivityItemList } from "@/types";
@@ -48,9 +48,7 @@ export function ProjectWebhooksPage({ projectId }: { projectId: string }) {
const projectName = `${projectNamePrefix}${projectId}`;
// subscribe to re-render on project cache change
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
const [deleteTarget, setDeleteTarget] = useState<Webhook | null>(null);
diff --git a/frontend/src/react/pages/project/database-detail/DatabaseDetailActions.tsx b/frontend/src/react/pages/project/database-detail/DatabaseDetailActions.tsx
index 5c9f17f600..d39f4b1fbd 100644
--- a/frontend/src/react/pages/project/database-detail/DatabaseDetailActions.tsx
+++ b/frontend/src/react/pages/project/database-detail/DatabaseDetailActions.tsx
@@ -3,7 +3,7 @@ import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { PermissionGuard } from "@/react/components/PermissionGuard";
import { Button } from "@/react/components/ui/button";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { preCreateIssue } from "@/react/lib/plan/issue";
import { useAppStore } from "@/react/stores/app";
import type { Permission } from "@/types";
@@ -34,9 +34,7 @@ export function DatabaseDetailActions({
const hasWorkspacePermissionFn = useAppStore(
(state) => state.hasWorkspacePermission
);
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(database.project)
- );
+ const project = useProjectByName(database.project);
void projectsByName;
const hasProjectPermission = useMemo(
() => (permission: Permission) => {
diff --git a/frontend/src/react/pages/project/database-detail/DatabaseDetailHeader.tsx b/frontend/src/react/pages/project/database-detail/DatabaseDetailHeader.tsx
index 408589ed84..6c6bfa2c6d 100644
--- a/frontend/src/react/pages/project/database-detail/DatabaseDetailHeader.tsx
+++ b/frontend/src/react/pages/project/database-detail/DatabaseDetailHeader.tsx
@@ -3,8 +3,8 @@ import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { EngineIcon } from "@/react/components/EngineIcon";
import { useEnvironment, usePlanFeature } from "@/react/hooks/useAppState";
-import { router } from "@/router";
-import { INSTANCE_ROUTE_DETAIL } from "@/router/dashboard/instance";
+import { router } from "@/react/router";
+import { INSTANCE_ROUTE_DETAIL } from "@/react/router/handles";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import {
diff --git a/frontend/src/react/pages/project/database-detail/DatabaseSQLEditorButton.tsx b/frontend/src/react/pages/project/database-detail/DatabaseSQLEditorButton.tsx
index 4621fc6f37..66743704af 100644
--- a/frontend/src/react/pages/project/database-detail/DatabaseSQLEditorButton.tsx
+++ b/frontend/src/react/pages/project/database-detail/DatabaseSQLEditorButton.tsx
@@ -1,9 +1,9 @@
import { SquareTerminal } from "lucide-react";
import { useCallback } from "react";
import { useTranslation } from "react-i18next";
+import { router } from "@/react/router";
+import { SQL_EDITOR_DATABASE_MODULE } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { SQL_EDITOR_DATABASE_MODULE } from "@/router/sqlEditor";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import { defaultProject, isDefaultProject } from "@/types/v1/project";
diff --git a/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.test.tsx b/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.test.tsx
index 35cd251a34..c33cf99baa 100644
--- a/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.test.tsx
+++ b/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.test.tsx
@@ -31,7 +31,6 @@ const mocks = vi.hoisted(() => {
resolveCELExpr: vi.fn(() => convertedExpr),
stringifyConditionExpression: vi.fn(() => "serialized-selection"),
featureToRef: vi.fn(() => ({ value: true })),
- useVueState: vi.fn((getter: () => unknown) => getter()),
getOrFetchPolicyByParentAndType: vi.fn(),
upsertPolicy: vi.fn(),
};
@@ -187,10 +186,6 @@ vi.mock("@/react/components/ui/tooltip", () => ({
Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
vi.mock("@/store", () => ({
featureToRef: mocks.featureToRef,
pushNotification: vi.fn(),
@@ -199,13 +194,21 @@ vi.mock("@/store", () => ({
vi.mock("@/react/stores/app", () => ({
useAppStore: Object.assign(
(
- selector: (state: { settingsByName: Record<string, unknown> }) => unknown
- ) => selector({ settingsByName: {} }),
+ selector: (state: {
+ settingsByName: Record<string, unknown>;
+ hasInstanceFeature: () => boolean;
+ }) => unknown
+ ) =>
+ selector({
+ settingsByName: {},
+ hasInstanceFeature: () => mocks.featureToRef().value,
+ }),
{
getState: () => ({
getOrFetchPolicyByParentAndType: mocks.getOrFetchPolicyByParentAndType,
upsertPolicy: mocks.upsertPolicy,
classification: () => [],
+ hasInstanceFeature: () => mocks.featureToRef().value,
}),
}
),
diff --git a/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.tsx b/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.tsx
index 26f7f40a1b..a33158b501 100644
--- a/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.tsx
+++ b/frontend/src/react/pages/project/database-detail/catalog/GrantAccessDialog.tsx
@@ -27,7 +27,6 @@ import { ExpirationPicker } from "@/react/components/ui/expiration-picker";
import { FeatureModal } from "@/react/components/ui/feature-modal";
import { Input } from "@/react/components/ui/input";
import { Tooltip } from "@/react/components/ui/tooltip";
-import { useVueState } from "@/react/hooks/useVueState";
import { getClassificationLevelOptions } from "@/react/lib/sensitive-data/components-utils";
import { rewriteResourceDatabase } from "@/react/lib/sensitive-data/exemptionDataUtils";
import type { SensitiveColumn } from "@/react/lib/sensitive-data/types";
@@ -36,7 +35,7 @@ import {
getExpressionsForDatabaseResource as getResourceExpressions,
} from "@/react/lib/sensitive-data/utils";
import { useAppStore } from "@/react/stores/app";
-import { featureToRef, pushNotification } from "@/store";
+import { pushNotification } from "@/store";
import type { DatabaseResource } from "@/types";
import { ExprSchema } from "@/types/proto-es/google/type/expr_pb";
import type {
@@ -91,8 +90,8 @@ export function GrantAccessDialog({
}: GrantAccessDialogProps) {
const { t } = useTranslation();
- const hasRequiredFeature = useVueState(
- () => featureToRef(PlanFeature.FEATURE_DATA_MASKING, instance).value
+ const hasRequiredFeature = useAppStore((s) =>
+ s.hasInstanceFeature(PlanFeature.FEATURE_DATA_MASKING, instance)
);
const initialDatabaseResources = useMemo<DatabaseResource[]>(
diff --git a/frontend/src/react/pages/project/database-detail/catalog/SensitiveColumnTable.tsx b/frontend/src/react/pages/project/database-detail/catalog/SensitiveColumnTable.tsx
index 73794bd538..438ca9673d 100644
--- a/frontend/src/react/pages/project/database-detail/catalog/SensitiveColumnTable.tsx
+++ b/frontend/src/react/pages/project/database-detail/catalog/SensitiveColumnTable.tsx
@@ -19,7 +19,7 @@ import {
TableRow,
} from "@/react/components/ui/table";
import type { MaskData } from "@/react/lib/sensitive-data/types";
-import { router } from "@/router";
+import { router } from "@/react/router";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import { autoDatabaseRoute } from "@/utils";
diff --git a/frontend/src/react/pages/project/database-detail/changelog/DatabaseChangelogTable.test.tsx b/frontend/src/react/pages/project/database-detail/changelog/DatabaseChangelogTable.test.tsx
index 19e3483973..af3d36b53e 100644
--- a/frontend/src/react/pages/project/database-detail/changelog/DatabaseChangelogTable.test.tsx
+++ b/frontend/src/react/pages/project/database-detail/changelog/DatabaseChangelogTable.test.tsx
@@ -15,7 +15,8 @@ vi.mock("react-i18next", () => ({
}),
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
push: vi.fn(),
},
diff --git a/frontend/src/react/pages/project/database-detail/changelog/DatabaseChangelogTable.tsx b/frontend/src/react/pages/project/database-detail/changelog/DatabaseChangelogTable.tsx
index 10457b6411..76b76aa4f5 100644
--- a/frontend/src/react/pages/project/database-detail/changelog/DatabaseChangelogTable.tsx
+++ b/frontend/src/react/pages/project/database-detail/changelog/DatabaseChangelogTable.tsx
@@ -9,7 +9,7 @@ import {
TableHeader,
TableRow,
} from "@/react/components/ui/table";
-import { router } from "@/router";
+import { router } from "@/react/router";
import { getDateForPbTimestampProtoEs } from "@/types";
import {
type Changelog,
diff --git a/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.test.tsx b/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.test.tsx
index d7b30a21da..d53242838a 100644
--- a/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.test.tsx
+++ b/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.test.tsx
@@ -18,7 +18,6 @@ const mocks = vi.hoisted(() => {
return {
currentRoute,
routerReplace: vi.fn(() => Promise.resolve()),
- useVueState: vi.fn(),
useDatabaseCatalog: vi.fn(),
getColumnCatalog: vi.fn(() => ({
semanticType: "",
@@ -55,18 +54,26 @@ const mocks = vi.hoisted(() => {
let DatabaseObjectExplorer: typeof import("./DatabaseObjectExplorer").DatabaseObjectExplorer;
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
replace: mocks.routerReplace,
currentRoute: mocks.currentRoute,
},
+ useCurrentRoute: () => ({
+ name: undefined,
+ fullPath: "",
+ hash: "",
+ params: {},
+ query: mocks.currentRoute.value.query,
+ requiredPermissions: [],
+ overrideDocumentTitle: false,
+ meta: {},
+ }),
}));
// The component now reads dbSchema getters plus the former setting-store
@@ -78,6 +85,7 @@ vi.mock("@/react/stores/app", () => {
const getState = () => ({
getOrFetchSettingByName: mocks.getOrFetchSettingByName,
getProjectClassification: mocks.getProjectClassification,
+ hasInstanceFeature: () => mocks.featureToRef().value,
...((mocks.dbSchemaStore() ?? {}) as Record<string, unknown>),
});
return {
@@ -272,8 +280,6 @@ beforeEach(async () => {
);
mocks.hasIndexSizeProperty.mockReset();
mocks.hasIndexSizeProperty.mockReturnValue(true);
- mocks.useVueState.mockReset();
- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
mocks.hasTableEngineProperty.mockReset();
mocks.hasTableEngineProperty.mockReturnValue(false);
mocks.instanceV1HasCollationAndCharacterSet.mockReset();
diff --git a/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.tsx b/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.tsx
index b3baf176f9..bc91846486 100644
--- a/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.tsx
+++ b/frontend/src/react/pages/project/database-detail/overview/DatabaseObjectExplorer.tsx
@@ -11,14 +11,12 @@ import {
} from "@/react/components/ui/select";
import { useAppDatabaseMetadata } from "@/react/hooks/useAppDatabaseMetadata";
import { useDatabaseCatalog } from "@/react/hooks/useDatabaseCatalog";
-import { useVueState } from "@/react/hooks/useVueState";
+import { router, useCurrentRoute } from "@/react/router";
import { useAppStore } from "@/react/stores/app";
import {
getColumnCatalog,
getTableCatalog,
} from "@/react/stores/app/databaseCatalog";
-import { router } from "@/router";
-import { featureToRef } from "@/store";
import { Engine } from "@/types/proto-es/v1/common_pb";
import type {
Database,
@@ -107,13 +105,11 @@ export function DatabaseObjectExplorer({
schema: selectedSchemaName,
})
);
- const routeTable = useVueState(() => {
- const table = router.currentRoute.value.query.table;
- return typeof table === "string" ? table : "";
- });
+ const tableQuery = useCurrentRoute().query.table;
+ const routeTable = typeof tableQuery === "string" ? tableQuery : "";
const databaseMetadata = useAppDatabaseMetadata(database.name);
- const hasSensitiveDataFeature = useVueState(
- () => featureToRef(PlanFeature.FEATURE_DATA_MASKING).value
+ const hasSensitiveDataFeature = useAppStore((s) =>
+ s.hasInstanceFeature(PlanFeature.FEATURE_DATA_MASKING)
);
const catalog = useDatabaseCatalog(database.name, false);
const project = getDatabaseProject(database);
diff --git a/frontend/src/react/pages/project/database-detail/overview/TableDetailDialog.test.tsx b/frontend/src/react/pages/project/database-detail/overview/TableDetailDialog.test.tsx
index 90b38c92ea..f4b38eb6a0 100644
--- a/frontend/src/react/pages/project/database-detail/overview/TableDetailDialog.test.tsx
+++ b/frontend/src/react/pages/project/database-detail/overview/TableDetailDialog.test.tsx
@@ -23,7 +23,6 @@ const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({
t: (key: string) => key,
})),
- useVueState: vi.fn(),
useDatabaseCatalog: vi.fn(),
updateDatabaseCatalog: vi.fn(),
getTableCatalog: vi.fn(),
@@ -48,10 +47,6 @@ vi.mock("react-i18next", () => ({
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
vi.mock("@/react/components/ui/dialog", () => ({
Dialog: ({ open, children }: { open: boolean; children: ReactNode }) =>
open ? <div data-testid="dialog-root">{children}</div> : null,
@@ -241,8 +236,6 @@ beforeEach(async () => {
mocks.useTranslation.mockReturnValue({
t: (key: string) => key,
});
- mocks.useVueState.mockReset();
- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
mocks.getOrFetchSettingByName.mockReset();
mocks.getSettingByName.mockReset();
mocks.getProjectClassification.mockReset();
diff --git a/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.test.tsx b/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.test.tsx
index 173de7aaf4..73b7ca36fb 100644
--- a/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.test.tsx
+++ b/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.test.tsx
@@ -19,7 +19,6 @@ const mocks = vi.hoisted(() => ({
useTranslation: vi.fn(() => ({
t: (key: string) => key,
})),
- useVueState: vi.fn(),
useDatabaseCatalog: vi.fn(),
getTableCatalog: vi.fn(),
featureToRef: vi.fn(() => ({ value: true })),
@@ -49,13 +48,10 @@ const mocks = vi.hoisted(() => ({
let TableMetadataTable: typeof import("./TableMetadataTable").TableMetadataTable;
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
vi.mock("@/store", () => ({
featureToRef: mocks.featureToRef,
}));
@@ -66,6 +62,7 @@ vi.mock("@/react/stores/app", () => {
getSettingByName: mocks.getSettingByName,
getProjectClassification: mocks.getProjectClassification,
hasFeature: mocks.hasFeature,
+ hasInstanceFeature: () => mocks.featureToRef().value,
instanceMissingLicense: mocks.instanceMissingLicense,
updateDatabaseCatalog: mocks.updateDatabaseCatalog,
});
@@ -251,8 +248,6 @@ beforeEach(async () => {
mocks.useTranslation.mockReturnValue({
t: (key: string) => key,
});
- mocks.useVueState.mockReset();
- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
mocks.useDatabaseCatalog.mockReset();
mocks.useDatabaseCatalog.mockReturnValue({ schemas: [] });
mocks.getTableCatalog.mockReset();
diff --git a/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.tsx b/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.tsx
index adbc96142b..4cb98d6391 100644
--- a/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.tsx
+++ b/frontend/src/react/pages/project/database-detail/overview/TableMetadataTable.tsx
@@ -9,11 +9,9 @@ import {
TableRow,
} from "@/react/components/ui/table";
import { useDatabaseCatalog } from "@/react/hooks/useDatabaseCatalog";
-import { useVueState } from "@/react/hooks/useVueState";
import { updateTableCatalog } from "@/react/lib/column-data-table/utils";
import { useAppStore } from "@/react/stores/app";
import { getTableCatalog } from "@/react/stores/app/databaseCatalog";
-import { featureToRef } from "@/store";
import { Engine } from "@/types/proto-es/v1/common_pb";
import type {
Database,
@@ -46,8 +44,8 @@ export function TableMetadataTable({
const { t } = useTranslation();
const databaseEngine = getDatabaseEngine(database);
const showSchemaColumn = hasSchemaProperty(databaseEngine);
- const showClassificationColumn = useVueState(
- () => featureToRef(PlanFeature.FEATURE_DATA_MASKING).value
+ const showClassificationColumn = useAppStore((s) =>
+ s.hasInstanceFeature(PlanFeature.FEATURE_DATA_MASKING)
);
const catalog = useDatabaseCatalog(database.name, false);
const project = getDatabaseProject(database);
diff --git a/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.test.tsx b/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.test.tsx
index 6b11f23387..38240c4c62 100644
--- a/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.test.tsx
+++ b/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.test.tsx
@@ -176,7 +176,6 @@ const mocks = vi.hoisted(() => {
return {
localStorage,
featureToRef: vi.fn(() => ({ value: true })),
- useVueState: vi.fn((getter: () => unknown) => getter()),
useDatabaseCatalog: vi.fn(() => makeDatabaseCatalog()),
getOrFetchPolicyByParentAndType: vi.fn(),
upsertPolicy: vi.fn(),
@@ -361,10 +360,6 @@ vi.mock("react-i18next", () => ({
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
vi.mock("@/store", () => ({
featureToRef: mocks.featureToRef,
pushNotification: mocks.pushNotification,
@@ -382,6 +377,7 @@ vi.mock("@/react/stores/app", () => {
getOrFetchSettingByName: mocks.getOrFetchSettingByName,
getSettingByName: mocks.getSettingByName,
getProjectClassification: mocks.getProjectClassification,
+ hasInstanceFeature: () => mocks.featureToRef().value,
});
return {
useAppStore: Object.assign(
@@ -400,7 +396,8 @@ vi.mock("@/utils", () => ({
instanceV1MaskingForNoSQL: mocks.instanceV1MaskingForNoSQL,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
resolve: mocks.routerResolve,
},
@@ -473,8 +470,6 @@ beforeEach(async () => {
mocks.useTranslation.mockReturnValue({
t: (key: string) => key,
});
- mocks.useVueState.mockReset();
- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
mocks.useDatabaseCatalog.mockReset();
mocks.useDatabaseCatalog.mockReturnValue(makeDatabaseCatalog());
mocks.getOrFetchPolicyByParentAndType.mockReset();
diff --git a/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx b/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx
index 774cf11c29..c57511b89c 100644
--- a/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx
+++ b/frontend/src/react/pages/project/database-detail/panels/DatabaseCatalogPanel.tsx
@@ -20,7 +20,6 @@ import {
} from "@/react/components/ui/dialog";
import { Input } from "@/react/components/ui/input";
import { useDatabaseCatalog } from "@/react/hooks/useDatabaseCatalog";
-import { useVueState } from "@/react/hooks/useVueState";
import type {
MaskData,
MaskDataTarget,
@@ -30,7 +29,7 @@ import {
isCurrentColumnException,
} from "@/react/lib/sensitive-data/utils";
import { useAppStore } from "@/react/stores/app";
-import { featureToRef, pushNotification } from "@/store";
+import { pushNotification } from "@/store";
import type { Permission } from "@/types";
import type {
ColumnCatalog,
@@ -210,8 +209,8 @@ export function DatabaseCatalogPanel({ database }: { database: Database }) {
const classificationConfig = useAppStore((s) =>
s.getProjectClassification(project.dataClassificationConfigId ?? "")
);
- const hasSensitiveDataFeature = useVueState(
- () => featureToRef(PlanFeature.FEATURE_DATA_MASKING, instance).value
+ const hasSensitiveDataFeature = useAppStore((s) =>
+ s.hasInstanceFeature(PlanFeature.FEATURE_DATA_MASKING, instance)
);
const [searchText, setSearchText] = useState("");
diff --git a/frontend/src/react/pages/project/database-detail/panels/DatabaseOverviewPanel.test.tsx b/frontend/src/react/pages/project/database-detail/panels/DatabaseOverviewPanel.test.tsx
index 94d9ac87cf..2758010ab7 100644
--- a/frontend/src/react/pages/project/database-detail/panels/DatabaseOverviewPanel.test.tsx
+++ b/frontend/src/react/pages/project/database-detail/panels/DatabaseOverviewPanel.test.tsx
@@ -31,7 +31,6 @@ const mocks = vi.hoisted(() => {
schemaList: [{ name: "public" }, { name: "sales" }],
currentRoute,
routerReplace: vi.fn(() => Promise.resolve()),
- useVueState: vi.fn(),
dbSchemaStore: vi.fn(),
useDatabaseCatalog: vi.fn(),
updateDatabaseCatalog: vi.fn(),
@@ -78,18 +77,26 @@ vi.stubGlobal("localStorage", mocks.localStorage);
let DatabaseOverviewPanel: typeof import("./DatabaseOverviewPanel").DatabaseOverviewPanel;
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
replace: mocks.routerReplace,
currentRoute: mocks.currentRoute,
},
+ useCurrentRoute: () => ({
+ name: undefined,
+ fullPath: "",
+ hash: "",
+ params: {},
+ query: mocks.currentRoute.value.query,
+ requiredPermissions: [],
+ overrideDocumentTitle: false,
+ meta: {},
+ }),
}));
// The component (and its children `DatabaseObjectExplorer`, `TableDetailDialog`,
@@ -104,6 +111,7 @@ vi.mock("@/react/stores/app", () => {
getSettingByName: mocks.getSettingByName,
getProjectClassification: mocks.getProjectClassification,
hasFeature: mocks.hasFeature,
+ hasInstanceFeature: () => mocks.featureToRef().value,
instanceMissingLicense: mocks.instanceMissingLicense,
...((mocks.dbSchemaStore() ?? {}) as Record<string, unknown>),
});
@@ -394,8 +402,6 @@ beforeEach(async () => {
mocks.hasTableEngineProperty.mockReturnValue(false);
mocks.instanceV1SupportsIndex.mockReset();
mocks.instanceV1SupportsIndex.mockReturnValue(true);
- mocks.useVueState.mockReset();
- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
vi.resetModules();
({ DatabaseOverviewPanel } = await import("./DatabaseOverviewPanel"));
@@ -589,7 +595,7 @@ describe("DatabaseOverviewPanel", () => {
});
test("syncs selected table to the route query and restores it from the route", async () => {
- const { router } = await import("@/router");
+ const { router } = await import("@/react/router");
router.currentRoute.value.query = { schema: "public", table: "orders" };
const { container, render, unmount } = renderIntoContainer(
@@ -699,7 +705,7 @@ describe("DatabaseOverviewPanel", () => {
});
test("clears a stale table query when the table does not exist", async () => {
- const { router } = await import("@/router");
+ const { router } = await import("@/react/router");
router.currentRoute.value.query = { schema: "public", table: "missing" };
const { render, unmount } = renderIntoContainer(
@@ -726,7 +732,7 @@ describe("DatabaseOverviewPanel", () => {
});
test("keeps an existing schema query instead of clearing it during initialization", async () => {
- const { router } = await import("@/router");
+ const { router } = await import("@/react/router");
router.currentRoute.value.query = { schema: "sales" };
const { container, render, unmount } = renderIntoContainer(
@@ -882,7 +888,7 @@ describe("DatabaseOverviewPanel", () => {
});
test("does not fall back to the first schema for schema-scoped sequences", async () => {
- const { router } = await import("@/router");
+ const { router } = await import("@/react/router");
router.currentRoute.value.query = { schema: "sales" };
mocks.instanceV1SupportsSequence.mockReturnValue(true);
@@ -971,7 +977,7 @@ describe("DatabaseOverviewPanel", () => {
});
test("does not fall back to the first schema for schema-scoped streams and tasks", async () => {
- const { router } = await import("@/router");
+ const { router } = await import("@/react/router");
router.currentRoute.value.query = { schema: "sales" };
mocks.getDatabaseEngine.mockReturnValue(Engine.SNOWFLAKE);
@@ -1016,7 +1022,7 @@ describe("DatabaseOverviewPanel", () => {
});
test("does not fall back to the first schema for schema-scoped package objects", async () => {
- const { router } = await import("@/router");
+ const { router } = await import("@/react/router");
router.currentRoute.value.query = { schema: "sales" };
mocks.getDatabaseEngine.mockReturnValue(Engine.ORACLE);
diff --git a/frontend/src/react/pages/project/database-detail/panels/DatabaseOverviewPanel.tsx b/frontend/src/react/pages/project/database-detail/panels/DatabaseOverviewPanel.tsx
index 6473b5ff75..2466f8b65d 100644
--- a/frontend/src/react/pages/project/database-detail/panels/DatabaseOverviewPanel.tsx
+++ b/frontend/src/react/pages/project/database-detail/panels/DatabaseOverviewPanel.tsx
@@ -1,7 +1,6 @@
import { useEffect, useMemo, useState } from "react";
-import { useVueState } from "@/react/hooks/useVueState";
+import { router, useCurrentRoute } from "@/react/router";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import { getDatabaseProject, hasProjectPermissionV2 } from "@/utils";
import { DatabaseObjectExplorer } from "../overview/DatabaseObjectExplorer";
@@ -15,10 +14,8 @@ export function DatabaseOverviewPanel({
hasSchemaPermission?: boolean;
}) {
const schemaList = useAppStore((s) => s.getSchemaList(database.name));
- const routeSchema = useVueState(() => {
- const schema = router.currentRoute.value.query.schema;
- return typeof schema === "string" ? schema : "";
- });
+ const schemaQuery = useCurrentRoute().query.schema;
+ const routeSchema = typeof schemaQuery === "string" ? schemaQuery : "";
const [selectedSchemaName, setSelectedSchemaName] = useState("");
const [tableSearchKeyword, setTableSearchKeyword] = useState("");
const [externalTableSearchKeyword, setExternalTableSearchKeyword] =
diff --git a/frontend/src/react/pages/project/database-detail/revision/DatabaseRevisionTable.tsx b/frontend/src/react/pages/project/database-detail/revision/DatabaseRevisionTable.tsx
index b63463bb59..c659890067 100644
--- a/frontend/src/react/pages/project/database-detail/revision/DatabaseRevisionTable.tsx
+++ b/frontend/src/react/pages/project/database-detail/revision/DatabaseRevisionTable.tsx
@@ -8,7 +8,7 @@ import {
TableHeader,
TableRow,
} from "@/react/components/ui/table";
-import { router } from "@/router";
+import { router } from "@/react/router";
import { getDateForPbTimestampProtoEs } from "@/types";
import type { Revision } from "@/types/proto-es/v1/revision_service_pb";
import { humanizeDate } from "@/utils";
diff --git a/frontend/src/react/pages/project/database-detail/useProjectDatabaseDetail.test.tsx b/frontend/src/react/pages/project/database-detail/useProjectDatabaseDetail.test.tsx
index 7c36fe61f6..7e2a5aa00a 100644
--- a/frontend/src/react/pages/project/database-detail/useProjectDatabaseDetail.test.tsx
+++ b/frontend/src/react/pages/project/database-detail/useProjectDatabaseDetail.test.tsx
@@ -48,18 +48,11 @@ const mocks = vi.hoisted(() => {
};
});
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: { replace: mocks.replace },
}));
-vi.mock("@/router/dashboard/projectV1", () => ({
- PROJECT_V1_ROUTE_DATABASE_DETAIL: mocks.routeNames.databaseDetail,
- PROJECT_V1_ROUTE_DATABASE_CHANGELOG_DETAIL:
- mocks.routeNames.databaseChangelogDetail,
- PROJECT_V1_ROUTE_DATABASE_REVISION_DETAIL:
- mocks.routeNames.databaseRevisionDetail,
-}));
-
vi.mock("@/store", () => ({}));
// Build the `databasesByName` cache the hook subscribes to from the mocked
diff --git a/frontend/src/react/pages/project/database-detail/useProjectDatabaseDetail.ts b/frontend/src/react/pages/project/database-detail/useProjectDatabaseDetail.ts
index 2df28e6d08..a05562e239 100644
--- a/frontend/src/react/pages/project/database-detail/useProjectDatabaseDetail.ts
+++ b/frontend/src/react/pages/project/database-detail/useProjectDatabaseDetail.ts
@@ -1,13 +1,11 @@
import { useEffect, useMemo, useState } from "react";
-import type { LocationQueryRaw } from "vue-router";
-import { useVueState } from "@/react/hooks/useVueState";
-import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
+import { router } from "@/react/router";
import {
PROJECT_V1_ROUTE_DATABASE_CHANGELOG_DETAIL,
PROJECT_V1_ROUTE_DATABASE_DETAIL,
PROJECT_V1_ROUTE_DATABASE_REVISION_DETAIL,
-} from "@/router/dashboard/projectV1";
+} from "@/react/router/handles";
+import { useAppStore } from "@/react/stores/app";
import { unknownDatabase } from "@/types/v1/database";
import { isDefaultProject } from "@/types/v1/project";
import { getInstanceResource, instanceV1HasAlterSchema } from "@/utils";
@@ -19,7 +17,7 @@ export interface UseProjectDatabaseDetailOptions {
databaseName: string;
routeName?: string;
hash?: string;
- query?: LocationQueryRaw;
+ query?: Record<string, string | undefined>;
changelogId?: string;
revisionId?: string;
}
@@ -39,8 +37,9 @@ export function useProjectDatabaseDetail({
);
const databasesByName = useAppStore((s) => s.databasesByName);
const fullDatabaseName = `instances/${instanceId}/databases/${databaseName}`;
- const database = useVueState(
- () => databasesByName[fullDatabaseName] ?? unknownDatabase()
+ const database = useMemo(
+ () => databasesByName[fullDatabaseName] ?? unknownDatabase(),
+ [databasesByName, fullDatabaseName]
);
const [loading, setLoading] = useState(true);
diff --git a/frontend/src/react/pages/project/export-center/DataExportPrepSheet.test.tsx b/frontend/src/react/pages/project/export-center/DataExportPrepSheet.test.tsx
index 5458f5affa..f01dfcfa97 100644
--- a/frontend/src/react/pages/project/export-center/DataExportPrepSheet.test.tsx
+++ b/frontend/src/react/pages/project/export-center/DataExportPrepSheet.test.tsx
@@ -87,10 +87,6 @@ vi.mock("@/react/lib/utils", () => ({
cls.filter(Boolean).join(" "),
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: (getter: () => unknown) => getter(),
-}));
-
vi.mock("@/react/hooks/useSessionPageSize", () => ({
useSessionPageSize: () => [20, () => {}],
}));
@@ -130,10 +126,9 @@ vi.mock("@/types/proto-es/v1/sheet_service_pb", () => ({
SheetSchema: {},
}));
-vi.mock("@/router", () => ({ router: { push: vi.fn() } }));
-
-vi.mock("@/router/dashboard/projectV1", () => ({
- PROJECT_V1_ROUTE_ISSUE_DETAIL: "issue-detail",
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
+ router: { push: vi.fn() },
}));
vi.mock("@/react/components/instance/constants", () => ({
diff --git a/frontend/src/react/pages/project/export-center/DataExportPrepSheet.tsx b/frontend/src/react/pages/project/export-center/DataExportPrepSheet.tsx
index 3cfa2ef1b2..9ff60837ae 100644
--- a/frontend/src/react/pages/project/export-center/DataExportPrepSheet.tsx
+++ b/frontend/src/react/pages/project/export-center/DataExportPrepSheet.tsx
@@ -20,13 +20,13 @@ import {
} from "@/react/components/ui/sheet";
import { Switch } from "@/react/components/ui/switch";
import { useCurrentUser } from "@/react/hooks/useAppState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { useSessionPageSize } from "@/react/hooks/useSessionPageSize";
-import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
+import { router } from "@/react/router";
+import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
import { experimentalCreateIssueByPlan } from "@/react/stores/app/issue";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
import { DEFAULT_MAX_RESULT_SIZE_IN_MB, pushNotification } from "@/store";
import { isValidDatabaseGroupName, isValidDatabaseName } from "@/types";
import { ExportFormat } from "@/types/proto-es/v1/common_pb";
@@ -91,9 +91,7 @@ export function DataExportPrepSheet({
// subscribe to re-render on project cache change
const projectsByName = useAppStore((s) => s.projectsByName);
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
void projectsByName;
const [step, setStep] = useState<Step>(1);
@@ -559,11 +557,12 @@ function TargetBadge({ target }: { target: string }) {
const isGroupTarget = isValidDatabaseGroupName(target);
const databasesByName = useAppStore((s) => s.databasesByName);
- // Always call useVueState unconditionally (rules of hooks)
- const db = useVueState(() =>
- isDatabaseTarget
- ? (databasesByName[target] ?? unknownDatabase())
- : undefined
+ const db = useMemo(
+ () =>
+ isDatabaseTarget
+ ? (databasesByName[target] ?? unknownDatabase())
+ : undefined,
+ [isDatabaseTarget, databasesByName, target]
);
if (isDatabaseTarget && db) {
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx
index 4e0cec09fa..32d9bee5aa 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx
@@ -4,7 +4,7 @@ import { useTranslation } from "react-i18next";
import { EngineIcon } from "@/react/components/EngineIcon";
import { Alert } from "@/react/components/ui/alert";
import { Badge } from "@/react/components/ui/badge";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { useAppStore } from "@/react/stores/app";
import { projectNamePrefix } from "@/store/modules/v1/common";
import { isValidDatabaseName } from "@/types";
@@ -25,9 +25,7 @@ export function IssueDetailAccessGrantDetails() {
(state) => state.searchMyAccessGrants
);
const projectName = `${projectNamePrefix}${page.projectId}`;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
void projectsByName;
const [isLoading, setIsLoading] = useState(true);
const [accessGrant, setAccessGrant] = useState<AccessGrant | undefined>();
@@ -171,8 +169,9 @@ export function IssueDetailAccessGrantDetails() {
function IssueDetailAccessGrantTarget({ target }: { target: string }) {
const databasesByName = useAppStore((s) => s.databasesByName);
- const database = useVueState(
- () => databasesByName[target] ?? unknownDatabase()
+ const database = useMemo(
+ () => databasesByName[target] ?? unknownDatabase(),
+ [databasesByName, target]
);
// Subscribe to the env cache so the row re-resolves once it loads; compute
// via getState() in a memo because getEnvironmentByName returns a fresh
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailActionBar.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailActionBar.tsx
index b9802fd7ae..26211cf765 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailActionBar.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailActionBar.tsx
@@ -42,18 +42,18 @@ import {
import { Tooltip } from "@/react/components/ui/tooltip";
import { useCurrentUser } from "@/react/hooks/useAppState";
import { useClickOutside } from "@/react/hooks/useClickOutside";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { cn } from "@/react/lib/utils";
-import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
+import { router } from "@/react/router";
import {
PROJECT_V1_ROUTE_ISSUE_DETAIL,
PROJECT_V1_ROUTE_PLAN_DETAIL,
-} from "@/router/dashboard/projectV1";
+} from "@/react/router/handles";
import {
buildPlanDeployRouteFromPlanName,
buildPlanDeployRouteFromRolloutName,
-} from "@/router/dashboard/projectV1RouteHelpers";
+} from "@/react/router/routeHelpers";
+import { useAppStore } from "@/react/stores/app";
import { pushNotification } from "@/store";
import { projectNamePrefix } from "@/store/modules/v1/common";
import {
@@ -108,9 +108,7 @@ export function IssueDetailActionBar() {
const menuRef = useRef<HTMLDivElement>(null);
const [menuOpen, setMenuOpen] = useState(false);
const projectName = `${projectNamePrefix}${page.projectId}`;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
void projectsByName;
const { isSpecEmpty } = useIssueDetailSpecValidation(page.plan?.specs ?? []);
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailApprovalFlow.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailApprovalFlow.tsx
index f2691a5a4d..5e7a4cbfaa 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailApprovalFlow.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailApprovalFlow.tsx
@@ -15,7 +15,7 @@ import { getAvatarColor, getInitials } from "@/react/components/UserAvatar";
import { Button } from "@/react/components/ui/button";
import { Tooltip } from "@/react/components/ui/tooltip";
import { useCurrentUser } from "@/react/hooks/useAppState";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { displayRoleTitleFromList } from "@/react/lib/role";
import { cn } from "@/react/lib/utils";
import { useAppStore } from "@/react/stores/app";
@@ -522,9 +522,7 @@ function useApprovalStep(issue: Issue, step: string, stepIndex: number) {
const [reRequesting, setReRequesting] = useState(false);
const projectName = `${projectNamePrefix}${page.projectId}`;
const currentUserEmail = currentUser?.email ?? "";
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
void projectsByName;
const stepApprover = issue.approvers[stepIndex];
@@ -566,9 +564,6 @@ function useApprovalStep(issue: Issue, step: string, stepIndex: number) {
// Subscribe directly to the Zustand project IAM cache so groupNames /
// candidateEmails recompute the moment loadProjectIamPolicy() resolves.
- // Wrapping the Zustand getter in useVueState would only react to Vue
- // dependencies and miss the Zustand write, leaving the approval step
- // empty on a cold issue page.
const projectIamPolicy = useAppStore(
(state) => state.projectPoliciesByName[projectName]
);
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailChecks.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailChecks.tsx
index f87f20511a..bab8361f6f 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailChecks.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailChecks.tsx
@@ -4,7 +4,7 @@ import { useTranslation } from "react-i18next";
import { planServiceClientConnect } from "@/connect";
import { PlanCheckSection } from "@/react/components/plan-check/PlanCheckSection";
import { useCurrentUser } from "@/react/hooks/useAppState";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { useAppStore } from "@/react/stores/app";
import { pushNotification } from "@/store";
import { extractUserEmail, projectNamePrefix } from "@/store/modules/v1/common";
@@ -26,9 +26,7 @@ export function IssueDetailChecks() {
const currentUser = useCurrentUser();
const [isRunningChecks, setIsRunningChecks] = useState(false);
const projectName = `${projectNamePrefix}${page.projectId}`;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
void projectsByName;
const summary = useMemo(
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailCommentList.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailCommentList.tsx
index 2fe9bc1f30..946a51e917 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailCommentList.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailCommentList.tsx
@@ -29,15 +29,15 @@ import {
DialogTitle,
} from "@/react/components/ui/dialog";
import { useCurrentUser } from "@/react/hooks/useAppState";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { cn } from "@/react/lib/utils";
+import { router, useCurrentRoute } from "@/react/router";
+import { buildPlanDeployRouteFromPlanName } from "@/react/router/routeHelpers";
import { useAppStore } from "@/react/stores/app";
import {
getIssueCommentType,
IssueCommentType,
} from "@/react/stores/app/issueComment";
-import { router } from "@/router";
-import { buildPlanDeployRouteFromPlanName } from "@/router/dashboard/projectV1RouteHelpers";
import { extractUserEmail, pushNotification } from "@/store";
import { projectNamePrefix } from "@/store/modules/v1/common";
import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";
@@ -108,11 +108,9 @@ export function IssueDetailCommentList() {
(state) => state.batchGetOrFetchUsers
);
const currentUser = useCurrentUser();
- const routeHash = useVueState(() => router.currentRoute.value.hash);
+ const routeHash = useCurrentRoute().hash;
const projectName = `${projectNamePrefix}${page.projectId}`;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
void projectsByName;
const issueName = page.issue?.name || page.plan?.issue || "";
// `getIssueComments` returns a stable empty array on miss, so reading it
@@ -368,9 +366,7 @@ function IssueDescriptionCommentRow({
// subscribe to re-render on project cache change
const projectsByName = useAppStore((s) => s.projectsByName);
const projectName = `${projectNamePrefix}${page.projectId}`;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
void projectsByName;
const creatorUser = useAppStore((state) =>
state.getUserByIdentifier(page.issue?.creator || "")
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.test.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.test.tsx
index d5b4824cfd..0e72d5ffa3 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.test.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.test.tsx
@@ -95,7 +95,6 @@ const mocks = vi.hoisted(() => {
useTranslation: vi.fn(() => ({
t: (key: string) => key,
})),
- useVueState: vi.fn(<T,>(getter: () => T) => getter()),
cn: vi.fn((...values: Array<string | false | null | undefined>) =>
values.filter(Boolean).join(" ")
),
@@ -159,6 +158,7 @@ vi.mock("lucide-react", () => ({
}));
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: mocks.useTranslation,
}));
@@ -200,26 +200,19 @@ vi.mock("@/react/components/ui/tooltip", () => ({
Tooltip: mocks.Tooltip,
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
vi.mock("@/react/lib/utils", () => ({
cn: mocks.cn,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
resolve: mocks.routerResolve,
},
}));
-vi.mock("@/router/dashboard/projectV1", () => ({
- PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL: "database-group.detail",
- PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS: "plan.detail.specs",
-}));
-
-vi.mock("@/router/dashboard/projectV1RouteHelpers", () => ({
+vi.mock("@/react/router/routeHelpers", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router/routeHelpers")>()),
buildPlanDeployRouteFromPlanName: mocks.buildPlanDeployRouteFromPlanName,
}));
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx
index 6cbb453e96..19c561b318 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseChangeView.tsx
@@ -21,15 +21,14 @@ import {
} from "@/react/components/ui/sheet";
import { Switch } from "@/react/components/ui/switch";
import { Tooltip } from "@/react/components/ui/tooltip";
-import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
-import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
+import { router } from "@/react/router";
import {
PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,
PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,
-} from "@/router/dashboard/projectV1";
-import { buildPlanDeployRouteFromPlanName } from "@/router/dashboard/projectV1RouteHelpers";
+} from "@/react/router/handles";
+import { buildPlanDeployRouteFromPlanName } from "@/react/router/routeHelpers";
+import { useAppStore } from "@/react/stores/app";
import { getProjectNameAndDatabaseGroupName } from "@/store";
import {
isValidDatabaseGroupName,
@@ -185,10 +184,12 @@ function IssueDetailDatabaseChangeOptions({
}
return [];
}, [selectedSpec]);
- const databases = useVueState(() =>
- targets
- .map((target) => databasesByName[target] ?? unknownDatabase())
- .filter((database) => isValidDatabaseName(database.name))
+ const databases = useMemo(
+ () =>
+ targets
+ .map((target) => databasesByName[target] ?? unknownDatabase())
+ .filter((database) => isValidDatabaseName(database.name)),
+ [targets, databasesByName]
);
const parsedStatement = useMemo(
() => parseStatement(sheetStatement),
@@ -521,7 +522,7 @@ function IssueDetailDatabaseChangeTargets({
const visibleTargets = useMemo(() => {
return targets.slice(0, Math.min(DEFAULT_VISIBLE_TARGETS, targets.length));
}, [targets]);
- const nonEnvDatabaseNames = useVueState(() => {
+ const nonEnvDatabaseNames = useMemo(() => {
if (isLoadingTargets) {
return [];
}
@@ -541,8 +542,8 @@ function IssueDetailDatabaseChangeTargets({
(name) =>
!(databasesByName[name] ?? unknownDatabase()).effectiveEnvironment
);
- });
- const filteredTargets = useVueState(() => {
+ }, [isLoadingTargets, targets, databasesByName]);
+ const filteredTargets = useMemo(() => {
if (!searchText) {
return targets;
}
@@ -557,7 +558,7 @@ function IssueDetailDatabaseChangeTargets({
}
return String(target).toLowerCase().includes(normalizedSearchText);
});
- });
+ }, [searchText, targets, databasesByName]);
const nonEnvWarning =
nonEnvDatabaseNames.length === 1
? t("plan.targets.non-env-warning.one", {
@@ -762,8 +763,9 @@ function IssueDetailDatabaseTarget({
const { t } = useTranslation();
const databasesByName = useAppStore((s) => s.databasesByName);
const environmentList = useAppStore((s) => s.environmentList);
- const database = useVueState(
- () => databasesByName[target] ?? unknownDatabase()
+ const database = useMemo(
+ () => databasesByName[target] ?? unknownDatabase(),
+ [databasesByName, target]
);
const environmentName =
database.effectiveEnvironment ??
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseCreateView.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseCreateView.tsx
index 7d66aa15c2..00ad4ed8d2 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseCreateView.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseCreateView.tsx
@@ -3,11 +3,11 @@ import { useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { EngineIcon } from "@/react/components/EngineIcon";
import { Tooltip } from "@/react/components/ui/tooltip";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { cn } from "@/react/lib/utils";
+import { router } from "@/react/router";
+import { INSTANCE_ROUTE_DETAIL } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { INSTANCE_ROUTE_DETAIL } from "@/router/dashboard/instance";
import { projectNamePrefix } from "@/store/modules/v1/common";
import {
formatEnvironmentName,
@@ -36,9 +36,7 @@ export function IssueDetailDatabaseCreateView() {
const projectsByName = useAppStore((s) => s.projectsByName);
const environmentList = useAppStore((s) => s.environmentList);
const projectName = `${projectNamePrefix}${page.projectId}`;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
void projectsByName;
const createDatabaseSpec = useMemo(() => {
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseExportView.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseExportView.tsx
index 9c0999e535..2d2a7d87a5 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseExportView.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailDatabaseExportView.tsx
@@ -24,11 +24,10 @@ import {
import { Input } from "@/react/components/ui/input";
import { Switch } from "@/react/components/ui/switch";
import { Tooltip } from "@/react/components/ui/tooltip";
-import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
+import { router } from "@/react/router";
+import { PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL } from "@/router/dashboard/projectV1";
import {
DEFAULT_MAX_RESULT_SIZE_IN_MB,
getProjectNameAndDatabaseGroupName,
@@ -640,8 +639,9 @@ function IssueDetailDatabaseExportDatabaseTarget({
const { t } = useTranslation();
const databasesByName = useAppStore((s) => s.databasesByName);
const environmentList = useAppStore((s) => s.environmentList);
- const database = useVueState(
- () => databasesByName[target] ?? unknownDatabase()
+ const database = useMemo(
+ () => databasesByName[target] ?? unknownDatabase(),
+ [databasesByName, target]
);
const environmentName =
database.effectiveEnvironment ??
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailLabels.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailLabels.tsx
index 0dc341e2d4..a58ac7fd27 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailLabels.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailLabels.tsx
@@ -12,11 +12,11 @@ import { issueServiceClientConnect } from "@/connect";
import { Checkbox } from "@/react/components/ui/checkbox";
import { LAYER_SURFACE_CLASS } from "@/react/components/ui/layer";
import { useClickOutside } from "@/react/hooks/useClickOutside";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { cn } from "@/react/lib/utils";
+import { router } from "@/react/router";
+import { PROJECT_V1_ROUTE_SETTINGS } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_SETTINGS } from "@/router/dashboard/projectV1";
import { pushNotification } from "@/store";
import { getProjectName, projectNamePrefix } from "@/store/modules/v1/common";
import {
@@ -42,9 +42,7 @@ export function IssueDetailLabels() {
// subscribe to re-render on project cache change
const projectsByName = useAppStore((s) => s.projectsByName);
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
useClickOutside(containerRef, open, () => setOpen(false));
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.test.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.test.tsx
index a75c0a5b84..2cf11195e4 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.test.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.test.tsx
@@ -9,6 +9,7 @@ const { mockContextRef } = vi.hoisted(() => ({
}));
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: () => ({
t: (key: string, vars?: Record<string, unknown>) => {
let s = key;
@@ -52,10 +53,6 @@ vi.mock("@/react/components/EnvironmentLabel", () => ({
}));
// Stub other modules the component pulls in.
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: <T,>(getter: () => T) => getter(),
-}));
-
vi.mock("@/types/v1/database", () => ({
unknownDatabase: () => ({
name: "instances/-/databases/-",
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx
index e100cea98f..61ff0cff94 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailRoleGrantDetails.tsx
@@ -1,5 +1,5 @@
import dayjs from "dayjs";
-import { useEffect, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { DDLWarningCallout } from "@/react/components/role-grant/DDLWarningCallout";
import {
@@ -11,7 +11,6 @@ import {
TableRow,
} from "@/react/components/ui/table";
import { useEnvironmentList } from "@/react/hooks/useAppState";
-import { useVueState } from "@/react/hooks/useVueState";
import { getRoleEnvironmentLimitationKind } from "@/react/lib/project-member/utils";
import { displayRoleTitleFromList } from "@/react/lib/role";
import { useAppStore } from "@/react/stores/app";
@@ -177,36 +176,37 @@ function IssueDetailDatabaseResourceTable({
}) {
const { t } = useTranslation();
// Subscribe to the instance cache so rows reactively pick up titles once
- // instances hydrate; a bare getState() read would not re-render here because
- // useVueState only tracks Vue dependencies.
+ // instances hydrate; a bare getState() read would not re-render here.
const instancesByName = useAppStore((s) => s.instancesByName);
const databasesByName = useAppStore((s) => s.databasesByName);
// Subscribe so titles refresh if the environment list changes.
- void useAppStore((s) => s.environmentList);
- const rows = useVueState(() =>
- databaseResourceList.map((resource) => {
- const database =
- databasesByName[resource.databaseFullName] ?? unknownDatabase();
- const { databaseName, instanceName } = extractDatabaseResourceName(
- resource.databaseFullName
- );
- const instance = instanceName
- ? instancesByName[`instances/${instanceName}`]
- : database.instanceResource;
- const environmentName =
- database.effectiveEnvironment ??
- database.instanceResource?.environment ??
- "";
- const environment = useAppStore
- .getState()
- .getEnvironmentByName(environmentName);
- return {
- databaseName,
- environmentTitle: environment.title,
- instanceTitle: instance?.title ?? "",
- resource,
- };
- })
+ const environmentList = useAppStore((s) => s.environmentList);
+ const rows = useMemo(
+ () =>
+ databaseResourceList.map((resource) => {
+ const database =
+ databasesByName[resource.databaseFullName] ?? unknownDatabase();
+ const { databaseName, instanceName } = extractDatabaseResourceName(
+ resource.databaseFullName
+ );
+ const instance = instanceName
+ ? instancesByName[`instances/${instanceName}`]
+ : database.instanceResource;
+ const environmentName =
+ database.effectiveEnvironment ??
+ database.instanceResource?.environment ??
+ "";
+ const environment = useAppStore
+ .getState()
+ .getEnvironmentByName(environmentName);
+ return {
+ databaseName,
+ environmentTitle: environment.title,
+ instanceTitle: instance?.title ?? "",
+ resource,
+ };
+ }),
+ [databaseResourceList, databasesByName, instancesByName, environmentList]
);
return (
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailStatementSection.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailStatementSection.tsx
index 24bcdd8a1b..79dea3db10 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailStatementSection.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailStatementSection.tsx
@@ -8,7 +8,7 @@ import { ReleaseInfoCard } from "@/react/components/release/ReleaseInfoCard";
import { Alert } from "@/react/components/ui/alert";
import { Button } from "@/react/components/ui/button";
import { useCurrentUser, useReleaseByName } from "@/react/hooks/useAppState";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { cn } from "@/react/lib/utils";
import { useAppStore } from "@/react/stores/app";
import { projectNamePrefix, pushNotification } from "@/store";
@@ -59,11 +59,7 @@ export function IssueDetailStatementSection({
const projectsByName = useAppStore((s) => s.projectsByName);
void projectsByName;
const currentUser = useCurrentUser();
- const project = useVueState(() =>
- useAppStore
- .getState()
- .getProjectByName(`${projectNamePrefix}${page.projectId}`)
- );
+ const project = useProjectByName(`${projectNamePrefix}${page.projectId}`);
const releaseName =
spec.config?.case === "changeDatabaseConfig"
? spec.config.value.release
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailTaskRolloutActionPanel.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailTaskRolloutActionPanel.tsx
index 437f9ac134..76697e6deb 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailTaskRolloutActionPanel.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailTaskRolloutActionPanel.tsx
@@ -19,7 +19,7 @@ import {
import { Textarea } from "@/react/components/ui/textarea";
import { Tooltip } from "@/react/components/ui/tooltip";
import { useCurrentUser } from "@/react/hooks/useAppState";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { cn } from "@/react/lib/utils";
import { useAppStore } from "@/react/stores/app";
import { pushNotification } from "@/store";
@@ -88,9 +88,7 @@ export function IssueDetailTaskRolloutActionPanel({
// subscribe to re-render on project cache change
const projectsByName = useAppStore((s) => s.projectsByName);
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
const [loading, setLoading] = useState(false);
const [permissionLoading, setPermissionLoading] = useState(false);
const [canRun, setCanRun] = useState(true);
@@ -599,8 +597,9 @@ function IssueDetailDatabaseTarget({ target }: { target: string }) {
const { t } = useTranslation();
const databasesByName = useAppStore((s) => s.databasesByName);
const environmentList = useAppStore((s) => s.environmentList);
- const database = useVueState(
- () => databasesByName[target] ?? unknownDatabase()
+ const database = useMemo(
+ () => databasesByName[target] ?? unknownDatabase(),
+ [databasesByName, target]
);
const environmentName =
database.effectiveEnvironment ??
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailTaskRunTable.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailTaskRunTable.tsx
index 25c7d6f55f..d8d61948a0 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailTaskRunTable.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailTaskRunTable.tsx
@@ -14,7 +14,7 @@ import {
TableRow,
} from "@/react/components/ui/table";
import { Tooltip } from "@/react/components/ui/tooltip";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { cn } from "@/react/lib/utils";
import { useAppStore } from "@/react/stores/app";
import { projectNamePrefix } from "@/store/modules/v1/common";
@@ -54,9 +54,7 @@ export function IssueDetailTaskRunTable({
// subscribe to re-render on project cache change
const projectsByName = useAppStore((s) => s.projectsByName);
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
const taskByUID = useMemo(() => {
const map = new Map<string, Task>();
diff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailTitleInput.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailTitleInput.tsx
index 3dcf92c190..4d343c9821 100644
--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailTitleInput.tsx
+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailTitleInput.tsx
@@ -3,7 +3,7 @@ import { Loader2 } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { issueServiceClientConnect } from "@/connect";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { useAppStore } from "@/react/stores/app";
import { pushNotification } from "@/store";
import { projectNamePrefix } from "@/store/modules/v1/common";
@@ -22,9 +22,7 @@ export function IssueDetailTitleInput() {
// subscribe to re-render on project cache change
const projectsByName = useAppStore((s) => s.projectsByName);
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
const [title, setTitle] = useState(page.issue?.title || "");
const [isEditing, setIsEditing] = useState(false);
diff --git a/frontend/src/react/pages/project/issue-detail/hooks/useIssueDetailPage.ts b/frontend/src/react/pages/project/issue-detail/hooks/useIssueDetailPage.ts
index 4521cdbd89..1ddbcbc917 100644
--- a/frontend/src/react/pages/project/issue-detail/hooks/useIssueDetailPage.ts
+++ b/frontend/src/react/pages/project/issue-detail/hooks/useIssueDetailPage.ts
@@ -7,13 +7,13 @@ import {
planServiceClientConnect,
rolloutServiceClientConnect,
} from "@/connect";
-import { useVueState } from "@/react/hooks/useVueState";
-import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
+import { router } from "@/react/router";
import {
WORKSPACE_ROUTE_403,
WORKSPACE_ROUTE_404,
-} from "@/router/dashboard/workspaceRoutes";
+} from "@/react/router/handles";
+import { useAppStore } from "@/react/stores/app";
import { projectNamePrefix } from "@/store";
import { State } from "@/types/proto-es/v1/common_pb";
import {
@@ -285,9 +285,7 @@ export const useIssueDetailPage = ({
// subscribe to re-render on project cache change
const projectsByName = useAppStore((s) => s.projectsByName);
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(`${projectNamePrefix}${projectId}`)
- );
+ const project = useProjectByName(`${projectNamePrefix}${projectId}`);
const [snapshot, setSnapshot] = useState<IssueDetailPageSnapshot>(() =>
buildDefaultSnapshot(projectId, issueId)
);
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 f791c2843a..7ada0a4d7e 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
@@ -56,10 +56,12 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
push: mocks.routerPush,
},
@@ -97,7 +99,7 @@ vi.mock("@/react/stores/app", () => ({
// so the candidate list re-renders when the policy resolves.
projectPoliciesByName: { "projects/p1": { bindings: [] } },
// The approval flow subscribes to projectsByName so the project
- // useVueState getter re-renders when the cache changes.
+ // selector re-renders when the cache changes.
projectsByName: { "projects/p1": { allowSelfApproval: false } },
getIssueComments: mocks.issueCommentStore.getIssueComments,
}),
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 c55c3b6909..e8ae115663 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsx
@@ -15,17 +15,17 @@ import { getAvatarColor, getInitials } from "@/react/components/UserAvatar";
import { Button } from "@/react/components/ui/button";
import { Tooltip } from "@/react/components/ui/tooltip";
import { useCurrentUser } from "@/react/hooks/useAppState";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { displayRoleTitleFromList } from "@/react/lib/role";
import { cn } from "@/react/lib/utils";
+import { router } from "@/react/router";
+import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
import { ensureGroupIdentifier } from "@/react/stores/app/group";
import {
getIssueCommentType,
IssueCommentType,
} from "@/react/stores/app/issueComment";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
import { pushNotification } from "@/store";
import { projectNamePrefix, userNamePrefix } from "@/store/modules/v1/common";
import {
@@ -56,9 +56,9 @@ import { usePlanDetailContext } from "../shell/PlanDetailContext";
type ApprovalStepStatus = "approved" | "rejected" | "current" | "pending";
-// Stable empty array for the comments selector — useVueState's getter must
-// return a cached reference when we want React to skip re-renders, otherwise
-// useSyncExternalStore will treat every render as a snapshot change.
+// Stable empty array for the comments selector — the selector must return a
+// cached reference when we want React to skip re-renders, otherwise the store
+// subscription will treat every render as a snapshot change.
const EMPTY_COMMENTS: IssueComment[] = [];
export function PlanDetailSidebarApprovalFlow() {
@@ -682,14 +682,9 @@ function useApprovalStep(issue: Issue, step: string, stepIndex: number) {
const [reRequesting, setReRequesting] = useState(false);
const projectName = `${projectNamePrefix}${page.projectId}`;
const currentUserEmail = currentUser?.email ?? "";
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
// Subscribe directly to the Zustand project IAM cache so this step
- // re-renders the moment loadProjectIamPolicy() resolves. Wrapping the
- // Zustand getter in useVueState would only react to Vue dependencies
- // and miss the Zustand write, leaving the candidates list empty on a
- // cold plan page.
+ // re-renders the moment loadProjectIamPolicy() resolves.
const projectIamPolicy = useAppStore(
(state) => state.projectPoliciesByName[projectName]
);
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 84288d620a..b8a83d9d9d 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
@@ -72,10 +72,6 @@ vi.mock("@bufbuild/protobuf", () => ({
create: (_schema: unknown, init?: Record<string, unknown>) => ({ ...init }),
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: (getter: () => unknown) => getter(),
-}));
-
vi.mock("@/react/hooks/useSessionPageSize", () => ({
useSessionPageSize: () => [20, () => {}],
}));
@@ -234,18 +230,14 @@ vi.mock("@/react/lib/utils", () => ({
classes.filter(Boolean).join(" "),
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
push: mocks.routerPush,
resolve: () => ({ href: "/database-group-detail" }),
},
}));
-vi.mock("@/router/dashboard/projectV1", () => ({
- PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL: "database-group-detail",
- PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL: "plan-detail-spec-detail",
-}));
-
vi.mock("@/types", () => ({
isValidDatabaseGroupName: (name: string) =>
name?.includes("/databaseGroups/"),
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 ad6ed5a28d..7f196b0cd6 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx
@@ -58,15 +58,15 @@ import {
import { Switch } from "@/react/components/ui/switch";
import { Tooltip } from "@/react/components/ui/tooltip";
import { useCurrentUser } from "@/react/hooks/useAppState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { useSessionPageSize } from "@/react/hooks/useSessionPageSize";
-import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
-import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
+import { router } from "@/react/router";
import {
PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,
PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
-} from "@/router/dashboard/projectV1";
+} from "@/react/router/handles";
+import { useAppStore } from "@/react/stores/app";
import { getProjectNameAndDatabaseGroupName, pushNotification } from "@/store";
import {
isValidDatabaseGroupName,
@@ -192,9 +192,7 @@ export function PlanDetailChangesBranch({
// subscribe to re-render on project cache change
const projectsByName = useAppStore((s) => s.projectsByName);
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(`projects/${page.projectId}`)
- );
+ const project = useProjectByName(`projects/${page.projectId}`);
const [showAddSpecSheet, setShowAddSpecSheet] = useState(false);
const [showTargetSelectorSheet, setShowTargetSelectorSheet] = useState(false);
const [specPendingDelete, setSpecPendingDelete] = useState<Plan_Spec | null>(
@@ -714,9 +712,7 @@ function OptionsSection({
// subscribe to re-render on project cache change
const projectsByName = useAppStore((s) => s.projectsByName);
void projectsByName;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(`projects/${page.projectId}`)
- );
+ const project = useProjectByName(`projects/${page.projectId}`);
const databasesByName = useAppStore((s) => s.databasesByName);
const [sheetStatement, setSheetStatementValue] = useState("");
const [isSheetOversize, setIsSheetOversize] = useState(false);
@@ -728,23 +724,25 @@ function OptionsSection({
}
return [];
}, [selectedSpec]);
- const databases = useVueState(() =>
- targets
- .flatMap((target) => {
- if (isValidDatabaseName(target)) {
- return [databasesByName[target] ?? unknownDatabase()];
- }
- if (isValidDatabaseGroupName(target)) {
- const dbGroup = useAppStore
- .getState()
- .getDBGroupByName(target, DatabaseGroupView.FULL);
- return (dbGroup.matchedDatabases ?? []).map(
- (database) => databasesByName[database.name] ?? unknownDatabase()
- );
- }
- return [];
- })
- .filter((database) => isValidDatabaseName(database.name))
+ const databases = useMemo(
+ () =>
+ targets
+ .flatMap((target) => {
+ if (isValidDatabaseName(target)) {
+ return [databasesByName[target] ?? unknownDatabase()];
+ }
+ if (isValidDatabaseGroupName(target)) {
+ const dbGroup = useAppStore
+ .getState()
+ .getDBGroupByName(target, DatabaseGroupView.FULL);
+ return (dbGroup.matchedDatabases ?? []).map(
+ (database) => databasesByName[database.name] ?? unknownDatabase()
+ );
+ }
+ return [];
+ })
+ .filter((database) => isValidDatabaseName(database.name)),
+ [targets, databasesByName]
);
const firstDatabaseName = databases[0]?.name ?? "";
const instanceName = firstDatabaseName
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 f1531e0c21..57bfae0d07 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailDeployFuture.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailDeployFuture.tsx
@@ -20,8 +20,8 @@ import {
SheetHeader,
SheetTitle,
} from "@/react/components/ui/sheet";
-import { router } from "@/router";
-import { buildPlanDeployRouteFromRolloutName } from "@/router/dashboard/projectV1RouteHelpers";
+import { router } from "@/react/router";
+import { buildPlanDeployRouteFromRolloutName } from "@/react/router/routeHelpers";
import { pushNotification } from "@/store";
import { State } from "@/types/proto-es/v1/common_pb";
import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";
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 c684e55b62..1ceb9dfbbd 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx
@@ -17,12 +17,12 @@ import {
} from "@/react/components/ui/popover";
import { Tooltip } from "@/react/components/ui/tooltip";
import { cn } from "@/react/lib/utils";
-import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
+import { router } from "@/react/router";
import {
PROJECT_V1_ROUTE_ISSUE_DETAIL,
PROJECT_V1_ROUTE_PLAN_DETAIL,
-} from "@/router/dashboard/projectV1";
+} from "@/react/router/handles";
+import { useAppStore } from "@/react/stores/app";
import { pushNotification } from "@/store";
import { State } from "@/types/proto-es/v1/common_pb";
import {
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailRollbackSheet.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailRollbackSheet.tsx
index 98fea4d87c..2bcd00ae4f 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailRollbackSheet.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailRollbackSheet.tsx
@@ -22,10 +22,10 @@ import {
SheetHeader,
SheetTitle,
} from "@/react/components/ui/sheet";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
+import { router } from "@/react/router";
+import { PROJECT_V1_ROUTE_PLAN_DETAIL } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_PLAN_DETAIL } from "@/router/dashboard/projectV1";
import { pushNotification } from "@/store";
import {
CreatePlanRequestSchema,
@@ -70,9 +70,7 @@ export function PlanDetailRollbackSheet({
const normalizedProjectName = projectName.startsWith("projects/")
? projectName
: `projects/${projectName}`;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(normalizedProjectName)
- );
+ const project = useProjectByName(normalizedProjectName);
const [loading, setLoading] = useState(false);
const [selectedTaskRunNames, setSelectedTaskRunNames] = useState<string[]>(
[]
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 bf6af3fc1f..86ac4f2820 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx
@@ -11,7 +11,6 @@ import { MonacoEditor, ReadonlyMonaco } from "@/react/components/monaco";
import { ReleaseInfoCard } from "@/react/components/release/ReleaseInfoCard";
import { Alert } from "@/react/components/ui/alert";
import { Button } from "@/react/components/ui/button";
-import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
import { useAppStore } from "@/react/stores/app";
import { pushNotification } from "@/store";
@@ -108,17 +107,17 @@ export function PlanDetailStatementSection({
}
}, [targetDatabaseNames]);
// Show Schema Editor only when at least one target's engine supports it.
- // Wrapped in useVueState so the eligibility flips back on once the Pinia
- // store hydrates the targets — otherwise a Plan opened before its targets
+ // Memoized on the databasesByName subscription so eligibility flips on once
+ // the store hydrates the targets — otherwise a Plan opened before its targets
// are cached would render with the button perpetually hidden.
- const schemaEditorEligible = useVueState(() => {
+ const schemaEditorEligible = useMemo(() => {
if (targetDatabaseNames.length === 0) return false;
return targetDatabaseNames.some((name) => {
const db = databasesByName[name];
if (!db || !isValidDatabaseName(db.name)) return false;
return engineSupportsSchemaEditor(getInstanceResource(db).engine);
});
- });
+ }, [targetDatabaseNames, databasesByName]);
const language = useMemo(() => {
if (!targetDatabaseName) return "sql";
const database = databasesByName[targetDatabaseName] ?? unknownDatabase();
diff --git a/frontend/src/react/pages/project/plan-detail/components/SchemaEditorSheet.tsx b/frontend/src/react/pages/project/plan-detail/components/SchemaEditorSheet.tsx
index 9fa564a05b..214e093b1c 100644
--- a/frontend/src/react/pages/project/plan-detail/components/SchemaEditorSheet.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/SchemaEditorSheet.tsx
@@ -1,6 +1,6 @@
import { cloneDeep } from "lodash-es";
import { Loader2, Maximize2, Minimize2, X } from "lucide-react";
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { SchemaEditorLite } from "@/react/components/SchemaEditorLite";
import { generateDiffDDL } from "@/react/components/SchemaEditorLite/core/generateDiffDDL";
@@ -15,7 +15,6 @@ import {
SheetFooter,
SheetTitle,
} from "@/react/components/ui/sheet";
-import { useVueState } from "@/react/hooks/useVueState";
import { useAppStore } from "@/react/stores/app";
import { pushNotification } from "@/store";
import { isValidDatabaseName } from "@/types";
@@ -115,27 +114,28 @@ function SchemaEditorSheetBody({
}
}, [databaseNames]);
- // Subscribed to the Pinia store via useVueState — re-derives once the
- // hydration above completes so newly-fetched targets switch from the
- // bare-name placeholder to a real "<db> (<instance>)" label.
- const databaseOptions = useVueState(() =>
- databaseNames.map((name) => {
- const db = databasesByName[name] ?? unknownDatabase();
- const hydrated = db && isValidDatabaseName(db.name);
- const instance = hydrated ? getInstanceResource(db) : undefined;
- const databaseLabel = extractDatabaseResourceName(name).databaseName;
- const label = instance
- ? `${databaseLabel} (${instance.title})`
- : databaseLabel;
- return {
- value: name,
- label,
- // Until a target is hydrated we don't know its engine yet; keep it
- // disabled rather than rendering it as supported and letting the
- // user pick something we'd then have to reject.
- disabled: !instance || !engineSupportsSchemaEditor(instance.engine),
- };
- })
+ // Re-derives once hydration completes so newly-fetched targets switch from
+ // the bare-name placeholder to a real "<db> (<instance>)" label.
+ const databaseOptions = useMemo(
+ () =>
+ databaseNames.map((name) => {
+ const db = databasesByName[name] ?? unknownDatabase();
+ const hydrated = db && isValidDatabaseName(db.name);
+ const instance = hydrated ? getInstanceResource(db) : undefined;
+ const databaseLabel = extractDatabaseResourceName(name).databaseName;
+ const label = instance
+ ? `${databaseLabel} (${instance.title})`
+ : databaseLabel;
+ return {
+ value: name,
+ label,
+ // Until a target is hydrated we don't know its engine yet; keep it
+ // disabled rather than rendering it as supported and letting the
+ // user pick something we'd then have to reject.
+ disabled: !instance || !engineSupportsSchemaEditor(instance.engine),
+ };
+ }),
+ [databaseNames, databasesByName]
);
const prepareMetadata = useCallback(
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 ee33168ec6..ef60e401fb 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
@@ -1,8 +1,8 @@
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/react/components/ui/button";
+import { router } from "@/react/router";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
import { projectNamePrefix } from "@/store/modules/v1/common";
import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
import type { Rollout, Task } from "@/types/proto-es/v1/rollout_service_pb";
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 9620e7756f..32edde7dbe 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
@@ -13,7 +13,7 @@ import { ReadonlyMonaco } from "@/react/components/monaco";
import { Button } from "@/react/components/ui/button";
import { Checkbox } from "@/react/components/ui/checkbox";
import { cn } from "@/react/lib/utils";
-import { router } from "@/router";
+import { router } from "@/react/router";
import { getTimeForPbTimestampProtoEs } from "@/types";
import {
type Stage,
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskRow.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskRow.tsx
index a444034efd..63106d8ce3 100644
--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskRow.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskRow.tsx
@@ -2,7 +2,7 @@ import { X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/react/components/ui/button";
import { cn } from "@/react/lib/utils";
-import { router } from "@/router";
+import { router } from "@/react/router";
import { type Task } from "@/types/proto-es/v1/rollout_service_pb";
import { stringifyTaskStatus } from "@/utils";
import { DeployTaskStatus } from "./DeployTaskStatus";
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 8fba585d41..f2eaa07f6d 100644
--- a/frontend/src/react/pages/project/plan-detail/hooks/usePlanCheckActions.tsx
+++ b/frontend/src/react/pages/project/plan-detail/hooks/usePlanCheckActions.tsx
@@ -3,7 +3,7 @@ import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { planServiceClientConnect } from "@/connect";
import { useCurrentUser } from "@/react/hooks/useAppState";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { useAppStore } from "@/react/stores/app";
import { projectNamePrefix, pushNotification } from "@/store";
import { extractUserEmail } from "@/store/modules/v1/common";
@@ -27,9 +27,7 @@ export function usePlanCheckActions() {
void projectsByName;
const currentUser = useCurrentUser();
const projectName = `${projectNamePrefix}${page.projectId}`;
- const project = useVueState(() =>
- useAppStore.getState().getProjectByName(projectName)
- );
+ const project = useProjectByName(projectName);
const allowRunChecks = useMemo(() => {
if (page.plan.hasRollout) return false;
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
index 4d3fc85bb2..3dc26e29c7 100644
--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/useInitialFetch.ts
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/useInitialFetch.ts
@@ -1,11 +1,11 @@
import { Code, ConnectError } from "@connectrpc/connect";
import type { MutableRefObject } from "react";
import { useEffect } from "react";
-import { router } from "@/router";
+import { router } from "@/react/router";
import {
WORKSPACE_ROUTE_403,
WORKSPACE_ROUTE_404,
-} from "@/router/dashboard/workspaceRoutes";
+} from "@/react/router/handles";
import { unknownPlan } from "@/types/v1/issue/plan";
import type { PlanDetailStoreApi } from "../../shared/stores/usePlanDetailStore";
import { fetchPlanSnapshot } from "./fetchPlanSnapshot";
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
index 7254828506..e593e584a0 100644
--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/useLeaveGuard.ts
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/useLeaveGuard.ts
@@ -1,6 +1,6 @@
import { useCallback, useEffect } from "react";
import { useTranslation } from "react-i18next";
-import { router } from "@/router";
+import { router } from "@/react/router";
import {
usePlanDetailStore,
usePlanDetailStoreApi,
diff --git a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsx b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsx
index 66964d730f..a905674650 100644
--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsx
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.test.tsx
@@ -13,29 +13,18 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: () => ({ t: (key: string) => key }),
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
push: mocks.routerPush,
replace: mocks.routerReplace,
},
}));
-vi.mock("@/router/dashboard/projectV1", () => ({
- PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL: "project.plan.detail.spec.detail",
- PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS: "project.plan.detail.specs",
-}));
-
-vi.mock("@/router/dashboard/projectV1RouteHelpers", () => ({
- getRouteQueryString: (value: string | string[] | undefined) =>
- Array.isArray(value) ? value[0] : value,
- PLAN_DETAIL_PHASE_CHANGES: "changes",
- PLAN_DETAIL_PHASE_REVIEW: "review",
- PLAN_DETAIL_PHASE_DEPLOY: "deploy",
-}));
-
vi.mock("@/utils", () => ({
getIssueRoute: mocks.getIssueRoute,
isDev: () => true,
@@ -105,7 +94,7 @@ describe("usePlanDetailPage", () => {
usePlanDetailPage({
projectId: "foo",
planId: "create",
- routeName: "project.plan.detail.specs",
+ routeName: "workspace.project.plan.detail.specs",
pageHost: null,
}),
{ wrapper }
@@ -216,7 +205,7 @@ describe("usePlanDetailPage", () => {
usePlanDetailPage({
projectId: "foo",
planId: "plan-1",
- routeName: "project.plan.detail.specs",
+ routeName: "workspace.project.plan.detail.specs",
pageHost: null,
}),
{ wrapper }
@@ -244,7 +233,7 @@ describe("usePlanDetailPage", () => {
usePlanDetailPage({
projectId: "foo",
planId: "plan-1",
- routeName: "project.plan.detail.specs",
+ routeName: "workspace.project.plan.detail.specs",
pageHost: null,
}),
{ wrapper }
@@ -275,7 +264,7 @@ describe("usePlanDetailPage", () => {
usePlanDetailPage({
projectId: "foo",
planId: "plan-1",
- routeName: "project.plan.detail.spec.detail",
+ routeName: "workspace.project.plan.detail.spec.detail",
specId: "spec-1",
pageHost: null,
}),
@@ -359,7 +348,7 @@ describe("usePlanDetailPage", () => {
usePlanDetailPage({
projectId: "foo",
planId: "plan-1",
- routeName: "project.plan.detail.spec.detail",
+ routeName: "workspace.project.plan.detail.spec.detail",
specId,
pageHost: null,
}),
@@ -389,7 +378,7 @@ describe("usePlanDetailPage", () => {
usePlanDetailPage({
projectId: "foo",
planId,
- routeName: "project.plan.detail.spec.detail",
+ routeName: "workspace.project.plan.detail.spec.detail",
specId: "spec-1",
pageHost: null,
}),
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
index 35feafc172..7222a8a6f3 100644
--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.ts
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/usePlanDetailPage.ts
@@ -7,16 +7,14 @@ import {
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 { router } from "@/react/router";
import {
PLAN_DETAIL_PHASE_CHANGES,
PLAN_DETAIL_PHASE_DEPLOY,
PLAN_DETAIL_PHASE_REVIEW,
-} from "@/router/dashboard/projectV1RouteHelpers";
+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,
+} from "@/react/router/handles";
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";
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
index 0a3664bc64..8317f4da5b 100644
--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/useRedirects.ts
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/useRedirects.ts
@@ -1,5 +1,5 @@
import { useEffect } from "react";
-import { router } from "@/router";
+import { router } from "@/react/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";
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
index bf17ef0f07..6ea64af86e 100644
--- a/frontend/src/react/pages/project/plan-detail/shell/hooks/useRouteSelection.ts
+++ b/frontend/src/react/pages/project/plan-detail/shell/hooks/useRouteSelection.ts
@@ -1,5 +1,5 @@
import { useEffect } from "react";
-import { getRouteQueryString } from "@/router/dashboard/projectV1RouteHelpers";
+import { getRouteQueryString } from "@/react/router/handles";
import type { PlanDetailPhase } from "../../shared/stores/types";
import { usePlanDetailStore } from "../../shared/stores/usePlanDetailStore";
diff --git a/frontend/src/react/pages/settings/CreateInstancePage.tsx b/frontend/src/react/pages/settings/CreateInstancePage.tsx
index 13d1f4de92..a9187dbba9 100644
--- a/frontend/src/react/pages/settings/CreateInstancePage.tsx
+++ b/frontend/src/react/pages/settings/CreateInstancePage.tsx
@@ -9,9 +9,9 @@ import {
useInstanceFormContext,
} from "@/react/components/instance";
import type { InfoSection } from "@/react/components/instance/info-content";
+import { router } from "@/react/router";
+import { INSTANCE_ROUTE_DASHBOARD } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { INSTANCE_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";
import { pushNotification } from "@/store";
const MIN_DOCKED_MAIN_WIDTH = 700;
diff --git a/frontend/src/react/pages/settings/CustomApprovalPage.tsx b/frontend/src/react/pages/settings/CustomApprovalPage.tsx
index 7fecc4f769..f9c12b2ef7 100644
--- a/frontend/src/react/pages/settings/CustomApprovalPage.tsx
+++ b/frontend/src/react/pages/settings/CustomApprovalPage.tsx
@@ -1,11 +1,10 @@
import { Loader2 } from "lucide-react";
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { RulesSection } from "@/react/components/CustomApproval/RulesSection";
import { APPROVAL_SOURCES } from "@/react/components/CustomApproval/utils";
import { FeatureAttention } from "@/react/components/FeatureAttention";
import { Alert } from "@/react/components/ui/alert";
-import { useVueState } from "@/react/hooks/useVueState";
import { useAppStore } from "@/react/stores/app";
import {
useWorkspaceApprovalSettingStore,
@@ -94,7 +93,9 @@ function SourceSection({
hasFeature: boolean;
onShowFeatureModal: () => void;
}) {
- const rules = useVueState(() => store.getRulesBySource(source));
+ // getRulesBySource returns a fresh filtered array each call, so memoize on
+ // the store + source to keep a stable reference.
+ const rules = useMemo(() => store.getRulesBySource(source), [store, source]);
return (
<RulesSection
diff --git a/frontend/src/react/pages/settings/DatabasesPage.tsx b/frontend/src/react/pages/settings/DatabasesPage.tsx
index b4962b1bad..28ea80f650 100644
--- a/frontend/src/react/pages/settings/DatabasesPage.tsx
+++ b/frontend/src/react/pages/settings/DatabasesPage.tsx
@@ -23,8 +23,8 @@ import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";
import { PermissionGuard } from "@/react/components/PermissionGuard";
import { Button } from "@/react/components/ui/button";
import type { DatabaseFilter } from "@/react/lib/databaseFilter";
+import { router } from "@/react/router";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
import { pushNotification } from "@/store";
import {
environmentNamePrefix,
diff --git a/frontend/src/react/pages/settings/EnvironmentsPage.tsx b/frontend/src/react/pages/settings/EnvironmentsPage.tsx
index d029d481c0..faae028741 100644
--- a/frontend/src/react/pages/settings/EnvironmentsPage.tsx
+++ b/frontend/src/react/pages/settings/EnvironmentsPage.tsx
@@ -57,17 +57,16 @@ import {
} from "@/react/components/ui/tabs";
import { useEnvironmentList } from "@/react/hooks/useAppState";
import { useUnsavedChangesGuard } from "@/react/hooks/useUnsavedChangesGuard";
-import { useVueState } from "@/react/hooks/useVueState";
import { displayRoleTitleFromList } from "@/react/lib/role";
import { cn } from "@/react/lib/utils";
-import { useAppStore } from "@/react/stores/app";
-import { getEmptyRolloutPolicy } from "@/react/stores/app/policy";
-import { useSQLReviewStore } from "@/react/stores/sqlReview";
-import { router } from "@/router";
+import { router } from "@/react/router";
import {
WORKSPACE_ROUTE_SQL_REVIEW_CREATE,
WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,
-} from "@/router/dashboard/workspaceRoutes";
+} from "@/react/router/handles";
+import { useAppStore } from "@/react/stores/app";
+import { getEmptyRolloutPolicy } from "@/react/stores/app/policy";
+import { useSQLReviewStore } from "@/react/stores/sqlReview";
import { pushNotification } from "@/store";
import { environmentNamePrefix } from "@/store/modules/v1/common";
import {
@@ -430,7 +429,7 @@ function SQLReviewSectionInner(
);
const canUpdatePolicy = hasWorkspacePermissionV2("bb.policies.update");
- const reviewPolicyList = useVueState(() => [...reviewStore.reviewPolicyList]);
+ const reviewPolicyList = reviewStore.reviewPolicyList;
const currentPolicy = useMemo(() => {
return reviewPolicyList.find((p) => p.resources.includes(resourcePath));
@@ -1271,8 +1270,7 @@ function SortableEnvironmentRow({
// `ReorderSheetInner` is keyed by an open counter so it remounts fresh
// every time the Sheet opens (re-initializing its `list` state from the
// snapshot), but does NOT reset mid-session when the parent's
-// `environments` prop gets a new reference on every render (which
-// `useVueState` does — it spreads the store's array). A naive
+// `environments` prop gets a new reference on every render. A naive
// `useEffect([open, environments])` reset would clobber the user's drag
// reorder the instant the parent re-renders, which was the previous bug.
function ReorderSheet({
@@ -1352,7 +1350,7 @@ function ReorderSheetInner({
// Compare against the initial order captured at mount, not against the
// live `environments` prop (which may change reference on every parent
- // render thanks to useVueState spreading the store array).
+ // render).
const initialOrderRef = useRef(environments.map((e) => e.id));
const orderChanged = useMemo(() => {
if (list.length !== initialOrderRef.current.length) return true;
diff --git a/frontend/src/react/pages/settings/GlobalMaskingPage.tsx b/frontend/src/react/pages/settings/GlobalMaskingPage.tsx
index 0cdb112f56..cd7e8b535b 100644
--- a/frontend/src/react/pages/settings/GlobalMaskingPage.tsx
+++ b/frontend/src/react/pages/settings/GlobalMaskingPage.tsx
@@ -30,7 +30,6 @@ import {
SelectTrigger,
SelectValue,
} from "@/react/components/ui/select";
-import { useVueState } from "@/react/hooks/useVueState";
import {
factorOperatorOverrideMap,
getClassificationLevelOptions,
@@ -55,7 +54,6 @@ import {
batchConvertCELStringToParsedExpr,
batchConvertParsedExprToCELString,
getDatabaseIdOptionConfig,
- getEnvironmentIdOptions,
getInstanceIdOptionConfig,
getProjectIdOptionConfig,
hasWorkspacePermissionV2,
@@ -354,8 +352,8 @@ function MaskingRuleConfig({
export function GlobalMaskingPage() {
const { t } = useTranslation();
- const hasSensitiveDataFeature = useVueState(() =>
- useAppStore.getState().hasInstanceFeature(PlanFeature.FEATURE_DATA_MASKING)
+ const hasSensitiveDataFeature = useAppStore((s) =>
+ s.hasInstanceFeature(PlanFeature.FEATURE_DATA_MASKING)
);
const hasPermission = hasWorkspacePermissionV2(
@@ -379,8 +377,16 @@ export function GlobalMaskingPage() {
[]
);
- // Subscribe to reactive store data so the memo recomputes when settings load.
- const environmentOptions = useVueState(() => getEnvironmentIdOptions());
+ // Recomputes once the environment list loads into the app store.
+ const environmentList = useAppStore((s) => s.environmentList);
+ const environmentOptions = useMemo(
+ () =>
+ environmentList.map((env) => ({
+ label: `${env.title} (${env.id})`,
+ value: env.id,
+ })),
+ [environmentList]
+ );
// `getClassificationLevelOptions` reads the app store imperatively, so key
// this on a `settingsByName` subscription to recompute once the
// DATA_CLASSIFICATION setting resolves.
diff --git a/frontend/src/react/pages/settings/GroupsPage.tsx b/frontend/src/react/pages/settings/GroupsPage.tsx
index 35315a1b83..0f14ba54f3 100644
--- a/frontend/src/react/pages/settings/GroupsPage.tsx
+++ b/frontend/src/react/pages/settings/GroupsPage.tsx
@@ -46,11 +46,10 @@ import {
import { Tooltip } from "@/react/components/ui/tooltip";
import { useCurrentUser } from "@/react/hooks/useAppState";
import { PagedTableFooter, usePagedData } from "@/react/hooks/usePagedData";
-import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
+import { router } from "@/react/router";
+import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";
import { pushNotification } from "@/store";
import { extractUserEmail, groupNamePrefix } from "@/store/modules/v1/common";
import { UNKNOWN_USER_NAME } from "@/types";
@@ -478,7 +477,7 @@ function GroupForm({
}: Omit<CreateGroupSheetProps, "open">) {
const { t } = useTranslation();
const currentUser = useCurrentUser();
- const isSaaSMode = useVueState(() => useAppStore.getState().isSaaSMode());
+ const isSaaSMode = useAppStore((s) => s.isSaaSMode());
const getOrFetchUserByIdentifier = useAppStore(
(state) => state.getOrFetchUserByIdentifier
);
@@ -926,14 +925,12 @@ export function GroupsPage() {
const listGroups = useAppStore((state) => state.listGroups);
const fetchGroup = useAppStore((state) => state.fetchGroup);
- const hasUserGroupFeature = useVueState(() =>
- useAppStore.getState().hasInstanceFeature(PlanFeature.FEATURE_USER_GROUPS)
+ const hasUserGroupFeature = useAppStore((s) =>
+ s.hasInstanceFeature(PlanFeature.FEATURE_USER_GROUPS)
);
const workspaceDomains = useAppStore((s) => s.getWorkspaceProfile().domains);
- const hasDirectorySyncFeature = useVueState(() =>
- useAppStore
- .getState()
- .hasInstanceFeature(PlanFeature.FEATURE_DIRECTORY_SYNC)
+ const hasDirectorySyncFeature = useAppStore((s) =>
+ s.hasInstanceFeature(PlanFeature.FEATURE_DIRECTORY_SYNC)
);
const canAccessSettings = hasWorkspacePermissionV2("bb.settings.get");
diff --git a/frontend/src/react/pages/settings/IDPDetailPage.tsx b/frontend/src/react/pages/settings/IDPDetailPage.tsx
index 369a3c9882..ee8a4d2c7f 100644
--- a/frontend/src/react/pages/settings/IDPDetailPage.tsx
+++ b/frontend/src/react/pages/settings/IDPDetailPage.tsx
@@ -22,10 +22,9 @@ import {
DialogTitle,
} from "@/react/components/ui/dialog";
import { Input } from "@/react/components/ui/input";
-import { useVueState } from "@/react/hooks/useVueState";
+import { router, useCurrentRoute } from "@/react/router";
+import { WORKSPACE_ROUTE_IDENTITY_PROVIDERS } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { WORKSPACE_ROUTE_IDENTITY_PROVIDERS } from "@/router/dashboard/workspaceRoutes";
import { pushNotification } from "@/store";
import {
getIdentityProviderResourceId,
@@ -1116,10 +1115,8 @@ export function IDPDetailPage() {
(state) => state.deleteIdentityProvider
);
- // Reactively read idpId from Vue Router's current route params
- const idpId = useVueState(
- () => router.currentRoute.value.params.idpId as string | undefined
- );
+ // Reactively read idpId from the current route params
+ const idpId = useCurrentRoute().params.idpId as string | undefined;
const [isLoading, setIsLoading] = useState(true);
const [isUpdating, setIsUpdating] = useState(false);
diff --git a/frontend/src/react/pages/settings/IDPsPage.tsx b/frontend/src/react/pages/settings/IDPsPage.tsx
index 46ff05eb4c..db6227f435 100644
--- a/frontend/src/react/pages/settings/IDPsPage.tsx
+++ b/frontend/src/react/pages/settings/IDPsPage.tsx
@@ -48,10 +48,9 @@ import {
TableRow,
} from "@/react/components/ui/table";
import { useIdentityProviderList } from "@/react/hooks/useAppState";
-import { useVueState } from "@/react/hooks/useVueState";
+import { router } from "@/react/router";
+import { WORKSPACE_ROUTE_IDENTITY_PROVIDER_DETAIL } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { WORKSPACE_ROUTE_IDENTITY_PROVIDER_DETAIL } from "@/router/dashboard/workspaceRoutes";
import { pushNotification } from "@/store";
import {
getIdentityProviderResourceId,
@@ -136,9 +135,7 @@ interface FieldMappingState {
function ExternalURLInfo({ type }: { type: IdentityProviderType }) {
const { t } = useTranslation();
- const externalUrl = useVueState(
- () => useAppStore.getState().serverInfo?.externalUrl ?? ""
- );
+ const externalUrl = useAppStore((s) => s.serverInfo?.externalUrl ?? "");
const redirectUrl = useMemo(() => {
const url = externalUrl || window.origin;
@@ -1301,8 +1298,8 @@ function CreateWizardDrawer({
const identityProviderList = useIdentityProviderList();
useEscapeKey(onClose);
- const hasEnterpriseSSOFeature = useVueState(() =>
- useAppStore.getState().hasFeature(PlanFeature.FEATURE_ENTERPRISE_SSO)
+ const hasEnterpriseSSOFeature = useAppStore((s) =>
+ s.hasFeature(PlanFeature.FEATURE_ENTERPRISE_SSO)
);
const [currentStep, setCurrentStep] = useState(1);
@@ -1973,8 +1970,8 @@ export function IDPsPage() {
const [ready, setReady] = useState(false);
const [showCreateDrawer, setShowCreateDrawer] = useState(false);
- const hasSSOFeature = useVueState(() =>
- useAppStore.getState().hasFeature(PlanFeature.FEATURE_GOOGLE_AND_GITHUB_SSO)
+ const hasSSOFeature = useAppStore((s) =>
+ s.hasFeature(PlanFeature.FEATURE_GOOGLE_AND_GITHUB_SSO)
);
const canCreate = hasWorkspacePermissionV2("bb.identityProviders.create");
diff --git a/frontend/src/react/pages/settings/InstanceDatabaseRedirectPage.tsx b/frontend/src/react/pages/settings/InstanceDatabaseRedirectPage.tsx
index 1b867974ef..56c79227fd 100644
--- a/frontend/src/react/pages/settings/InstanceDatabaseRedirectPage.tsx
+++ b/frontend/src/react/pages/settings/InstanceDatabaseRedirectPage.tsx
@@ -5,10 +5,12 @@ import {
instanceNamePrefix,
isValidProjectName,
} from "@/react/lib/resourceName";
+import { router } from "@/react/router";
+import {
+ INSTANCE_ROUTE_DETAIL,
+ PROJECT_V1_ROUTE_DATABASE_DETAIL,
+} from "@/react/router/handles";
import { getOrFetchDatabaseByName } from "@/react/stores/app/databaseAccess";
-import { router } from "@/router";
-import { INSTANCE_ROUTE_DETAIL } from "@/router/dashboard/instance";
-import { PROJECT_V1_ROUTE_DATABASE_DETAIL } from "@/router/dashboard/projectV1";
import { pushNotification } from "@/store";
export function InstanceDatabaseRedirectPage({
diff --git a/frontend/src/react/pages/settings/InstancesPage.tsx b/frontend/src/react/pages/settings/InstancesPage.tsx
index 2d5aa9519f..647b1f2162 100644
--- a/frontend/src/react/pages/settings/InstancesPage.tsx
+++ b/frontend/src/react/pages/settings/InstancesPage.tsx
@@ -63,13 +63,12 @@ import {
getPageSizeOptions,
useSessionPageSize,
} from "@/react/hooks/useSessionPageSize";
-import { useVueState } from "@/react/hooks/useVueState";
import { cn } from "@/react/lib/utils";
+import { router } from "@/react/router";
+import { INSTANCE_ROUTE_CREATE } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
import type { InstanceFilter } from "@/react/stores/app/types";
-import { router } from "@/router";
-import { INSTANCE_ROUTE_CREATE } from "@/router/dashboard/instance";
-import { featureToRef, pushNotification } from "@/store";
+import { pushNotification } from "@/store";
import { environmentNamePrefix } from "@/store/modules/v1/common";
import {
isValidInstanceName,
@@ -186,8 +185,8 @@ function EnvironmentName({ environmentName }: { environmentName: string }) {
environment.name === UNKNOWN_ENVIRONMENT_NAME ||
environment.name === NULL_ENVIRONMENT_NAME;
- const hasEnvTierFeature = useVueState(
- () => featureToRef(PlanFeature.FEATURE_ENVIRONMENT_TIERS).value
+ const hasEnvTierFeature = useAppStore((s) =>
+ s.hasInstanceFeature(PlanFeature.FEATURE_ENVIRONMENT_TIERS)
);
const isProtected =
hasEnvTierFeature && environment.tags?.protected === "protected";
diff --git a/frontend/src/react/pages/settings/LandingPage.tsx b/frontend/src/react/pages/settings/LandingPage.tsx
index 7377c3a82e..4d3223198a 100644
--- a/frontend/src/react/pages/settings/LandingPage.tsx
+++ b/frontend/src/react/pages/settings/LandingPage.tsx
@@ -34,14 +34,15 @@ import {
useOptionalCurrentUser,
useServerState,
} from "@/react/hooks/useAppState";
-import { useVueState } from "@/react/hooks/useVueState";
-import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
+import { useRecentVisit } from "@/react/hooks/useRecentVisit";
+import { router } from "@/react/router";
import {
DATABASE_ROUTE_DASHBOARD,
ENVIRONMENT_V1_ROUTE_DASHBOARD,
INSTANCE_ROUTE_DASHBOARD,
PROJECT_V1_ROUTE_DASHBOARD,
+ SETTING_ROUTE_WORKSPACE_GENERAL,
+ SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,
WORKSPACE_ROUTE_AUDIT_LOG,
WORKSPACE_ROUTE_CUSTOM_APPROVAL,
WORKSPACE_ROUTE_DATA_CLASSIFICATION,
@@ -58,12 +59,8 @@ import {
WORKSPACE_ROUTE_SQL_REVIEW,
WORKSPACE_ROUTE_USERS,
WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,
-} from "@/router/dashboard/workspaceRoutes";
-import {
- SETTING_ROUTE_WORKSPACE_GENERAL,
- SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,
-} from "@/router/dashboard/workspaceSetting";
-import { useRecentVisit } from "@/router/useRecentVisit";
+} from "@/react/router/handles";
+import { useAppStore } from "@/react/stores/app";
import { projectNamePrefix } from "@/store/modules/v1/common";
import { UNKNOWN_PROJECT_NAME } from "@/types";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
@@ -288,9 +285,7 @@ function useQuickAccessConfig(email: string) {
// ---------------------------------------------------------------------------
function useLastVisitedProject() {
- const lastVisitProjectPath = useVueState(
- () => useRecentVisit().lastVisitProjectPath.value
- );
+ const { lastVisitProjectPath } = useRecentVisit();
const [project, setProject] = useState<Project | undefined>();
useEffect(() => {
diff --git a/frontend/src/react/pages/settings/MCPPage.tsx b/frontend/src/react/pages/settings/MCPPage.tsx
index 7c2e595822..e5475d0ceb 100644
--- a/frontend/src/react/pages/settings/MCPPage.tsx
+++ b/frontend/src/react/pages/settings/MCPPage.tsx
@@ -12,8 +12,8 @@ import {
} from "@/react/components/ui/tabs";
import { Textarea } from "@/react/components/ui/textarea";
import { useServerState } from "@/react/hooks/useAppState";
-import { router } from "@/router";
-import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";
+import { router } from "@/react/router";
+import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/react/router/handles";
import { hasWorkspacePermissionV2 } from "@/utils";
export function MCPPage() {
diff --git a/frontend/src/react/pages/settings/MembersPage.test.tsx b/frontend/src/react/pages/settings/MembersPage.test.tsx
index 10b70913e1..5c533a69d3 100644
--- a/frontend/src/react/pages/settings/MembersPage.test.tsx
+++ b/frontend/src/react/pages/settings/MembersPage.test.tsx
@@ -180,10 +180,6 @@ vi.mock("@/react/hooks/useEscapeKey", () => ({
useEscapeKey: () => {},
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: (getter: () => unknown) => getter(),
-}));
-
vi.mock("@/react/lib/project-member/utils", () => ({
getRoleEnvironmentLimitationKind: vi.fn(() => undefined),
roleHasDatabaseLimitation: vi.fn((role: string) =>
@@ -269,6 +265,7 @@ vi.mock("@bufbuild/protobuf", () => ({
}));
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: () => ({ t: (key: string) => key }),
}));
diff --git a/frontend/src/react/pages/settings/MembersPage.tsx b/frontend/src/react/pages/settings/MembersPage.tsx
index c3fb4d6ff0..ea465f9bfa 100644
--- a/frontend/src/react/pages/settings/MembersPage.tsx
+++ b/frontend/src/react/pages/settings/MembersPage.tsx
@@ -69,7 +69,7 @@ import {
import { Tooltip } from "@/react/components/ui/tooltip";
import { useCurrentUser } from "@/react/hooks/useAppState";
import { useEscapeKey } from "@/react/hooks/useEscapeKey";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import {
getMemberBindings,
groupProjectRoleBindings,
@@ -162,7 +162,7 @@ function MemberTable({
}) {
const { t } = useTranslation();
const currentUser = useCurrentUser();
- const isSaaSMode = useVueState(() => useAppStore.getState().isSaaSMode());
+ const isSaaSMode = useAppStore((s) => s.isSaaSMode());
const batchGetOrFetchUsers = useAppStore(
(state) => state.batchGetOrFetchUsers
);
@@ -174,8 +174,8 @@ function MemberTable({
// Group expand state. Cache is keyed by group name and invalidated
// when the group-binding *content* changes — not on `bindings`
// reference change, because the parent rebuilds `memberBindings` via
- // `useVueState(() => getMemberBindings(...))` and gets a new array
- // identity on every render. We can't use the `prevBindingsRef.current
+ // `useMemo(() => getMemberBindings(...))` and gets a new array identity
+ // whenever its deps change. We can't use the `prevBindingsRef.current
// !== bindings` shortcut that `GroupsPage` uses (its `groups` comes
// from a reducer-backed `usePagedData` with stable identity).
// Comparing a content-derived signature instead lets the cache only
@@ -620,7 +620,7 @@ function MemberTableByRole({
}) {
const { t } = useTranslation();
const currentUser = useCurrentUser();
- const isSaaSMode = useVueState(() => useAppStore.getState().isSaaSMode());
+ const isSaaSMode = useAppStore((s) => s.isSaaSMode());
const roleList = useAppStore((state) => state.roleList);
const [expandedRoles, setExpandedRoles] = useState<Set<string>>(new Set());
const initializedRef = useRef(false);
@@ -1381,7 +1381,7 @@ function EditMemberRoleDrawer({
const updateProjectIamPolicy = useAppStore(
(state) => state.updateProjectIamPolicy
);
- const isSaaSMode = useVueState(() => useAppStore.getState().isSaaSMode());
+ const isSaaSMode = useAppStore((s) => s.isSaaSMode());
const roleList = useAppStore((state) => state.roleList);
const settingsByName = useAppStore((s) => s.settingsByName);
const hasEmailSetting = useMemo(
@@ -1400,7 +1400,8 @@ function EditMemberRoleDrawer({
// Live project role bindings for the member (reactively updated when IAM policy changes).
// Active bindings come first, expired ones last; original order is preserved within each group.
- const liveProjectRoleBindings = useVueState(() => {
+ const projectPoliciesByName = useAppStore((s) => s.projectPoliciesByName);
+ const liveProjectRoleBindings = useMemo(() => {
if (!isProjectEditMode || !member || !projectName) return [];
const policy = getProjectIamPolicy(projectName);
const matching = policy.bindings.filter((b) =>
@@ -1411,7 +1412,14 @@ function EditMemberRoleDrawer({
const bExpired = isBindingPolicyExpired(b) ? 1 : 0;
return aExpired - bExpired;
});
- });
+ // projectPoliciesByName backs getProjectIamPolicy — recompute on its change.
+ }, [
+ isProjectEditMode,
+ member,
+ projectName,
+ getProjectIamPolicy,
+ projectPoliciesByName,
+ ]);
const [selectedBindings, setSelectedBindings] = useState<string[]>(
initialBindings ?? []
@@ -2062,11 +2070,8 @@ export function MembersPage({ projectId }: { projectId?: string }) {
const projectName = projectId
? `${projectNamePrefix}${projectId}`
: undefined;
- const project = useVueState(() =>
- projectName
- ? useAppStore.getState().getProjectByName(projectName)
- : undefined
- );
+ const projectFromName = useProjectByName(projectName ?? "");
+ const project = projectName ? projectFromName : undefined;
const [memberSearchText, setMemberSearchText] = useState("");
const [memberViewTab, setMemberViewTab] = useState<"MEMBERS" | "ROLES">(
@@ -2079,8 +2084,8 @@ export function MembersPage({ projectId }: { projectId?: string }) {
>();
const [showRequestRoleDialog, setShowRequestRoleDialog] = useState(false);
- const hasRequestRoleFeature = useVueState(() =>
- useAppStore.getState().hasFeature(PlanFeature.FEATURE_REQUEST_ROLE_WORKFLOW)
+ const hasRequestRoleFeature = useAppStore((s) =>
+ s.hasFeature(PlanFeature.FEATURE_REQUEST_ROLE_WORKFLOW)
);
// IAM policy loads are owned by the parent shells: ProjectRouteShell
@@ -2089,37 +2094,42 @@ export function MembersPage({ projectId }: { projectId?: string }) {
// (+ referenced groups) on /settings/members. This page just reads them.
// Subscribe directly to the Zustand projectPoliciesByName slice so the
// member table re-renders when loadProjectIamPolicy / updateProjectIamPolicy
- // writes to the app store. Wrapping `getProjectIamPolicy()` in
- // `useVueState` would only re-render on Vue reactivity changes and miss
- // these Zustand writes.
+ // writes to the app store.
const projectIamPolicy = useAppStore((state) =>
projectName ? state.projectPoliciesByName[projectName] : undefined
);
-
- // `useVueState` ensures we re-render whenever any reactive dep
- // `getMemberBindings(...)` reads from changes — IAM policies, but
- // also the group / user / service-account / workload-identity stores
- // it pulls metadata from. The result array reference changes on every
- // render; the table component handles that with content-based change
- // detection (a group-bindings signature) so its expand-cache only
- // resets on real membership changes.
- // Keep this in useVueState so it re-runs when the Pinia user/group/
- // service-account/workload-identity stores that getMemberBindings reads
- // for member metadata change. The workspace IAM policy itself now comes
- // from the app store: subscribing to `workspacePolicy` above re-renders
- // this component on policy changes, and useVueState reads the latest getter
- // each render, so both reactivity sources are covered.
- const memberBindings = useVueState(() =>
- getMemberBindings({
- policies:
- projectName && projectIamPolicy
- ? [{ level: "PROJECT" as const, policy: projectIamPolicy }]
- : workspacePolicy
- ? [{ level: "WORKSPACE" as const, policy: workspacePolicy }]
- : [],
- searchText: memberSearchText,
- ignoreRoles: EMPTY_ROLE_SET,
- })
+ // getMemberBindings reads member metadata from the group / user /
+ // service-account / workload-identity app-store maps via getState(); subscribe
+ // to them (plus the IAM policies) so the list refreshes when any of those
+ // caches hydrate.
+ const groupsByName = useAppStore((s) => s.groupsByName);
+ const usersByName = useAppStore((s) => s.usersByName);
+ const serviceAccountsByName = useAppStore((s) => s.serviceAccountsByName);
+ const workloadIdentitiesByName = useAppStore(
+ (s) => s.workloadIdentitiesByName
+ );
+ const memberBindings = useMemo(
+ () =>
+ getMemberBindings({
+ policies:
+ projectName && projectIamPolicy
+ ? [{ level: "PROJECT" as const, policy: projectIamPolicy }]
+ : workspacePolicy
+ ? [{ level: "WORKSPACE" as const, policy: workspacePolicy }]
+ : [],
+ searchText: memberSearchText,
+ ignoreRoles: EMPTY_ROLE_SET,
+ }),
+ [
+ projectName,
+ projectIamPolicy,
+ workspacePolicy,
+ memberSearchText,
+ groupsByName,
+ usersByName,
+ serviceAccountsByName,
+ workloadIdentitiesByName,
+ ]
);
const canSetIamPolicy = project
diff --git a/frontend/src/react/pages/settings/ProjectsPage.tsx b/frontend/src/react/pages/settings/ProjectsPage.tsx
index 65afb5bf76..1a6ba51215 100644
--- a/frontend/src/react/pages/settings/ProjectsPage.tsx
+++ b/frontend/src/react/pages/settings/ProjectsPage.tsx
@@ -33,10 +33,10 @@ import {
useSessionPageSize,
} from "@/react/hooks/useSessionPageSize";
import { cn } from "@/react/lib/utils";
+import { router } from "@/react/router";
+import { PROJECT_V1_ROUTE_ISSUES } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_ISSUES } from "@/router/dashboard/projectV1";
-import { pushNotification, useAuthStore } from "@/store";
+import { pushNotification } from "@/store";
import { getProjectName } from "@/store/modules/v1/common";
import { State } from "@/types/proto-es/v1/common_pb";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
@@ -227,7 +227,7 @@ function ProjectActionDropdown({
export function ProjectsPage() {
const { t } = useTranslation();
- const authStore = useAuthStore();
+ const isLoggedIn = useAppStore((s) => s.isLoggedIn());
// Search state — managed as SearchParams (query + scopes)
const [searchParams, setSearchParams] = useState<SearchParams>(() => {
@@ -367,7 +367,7 @@ export function ProjectsPage() {
const fetchProjects = useCallback(
async (isRefresh: boolean) => {
- if (!authStore.isLoggedIn) return;
+ if (!isLoggedIn) return;
abortRef.current?.abort();
abortRef.current = new AbortController();
@@ -413,14 +413,7 @@ export function ProjectsPage() {
}
}
},
- [
- authStore.isLoggedIn,
- pageSize,
- searchText,
- selectedState,
- selectedLabels,
- orderBy,
- ]
+ [isLoggedIn, pageSize, searchText, selectedState, selectedLabels, orderBy]
);
// Fetch on mount + re-fetch on filter/sort/pageSize changes (debounced after first load)
diff --git a/frontend/src/react/pages/settings/RequestRoleSheet.test.tsx b/frontend/src/react/pages/settings/RequestRoleSheet.test.tsx
index d0dfba1323..0b042d6bb6 100644
--- a/frontend/src/react/pages/settings/RequestRoleSheet.test.tsx
+++ b/frontend/src/react/pages/settings/RequestRoleSheet.test.tsx
@@ -111,11 +111,8 @@ vi.mock("@/react/components/RoleSelect", () => ({
}),
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: (getter: () => unknown) => getter(),
-}));
-
vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
useTranslation: () => ({ t: (key: string) => key }),
}));
@@ -147,16 +144,13 @@ vi.mock("@/types/proto-es/v1/issue_service_pb", () => ({
vi.mock("@/types/proto-es/v1/project_service_pb", () => ({}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
resolve: () => ({ fullPath: "/issues/1" }),
},
}));
-vi.mock("@/router/dashboard/projectV1", () => ({
- PROJECT_V1_ROUTE_ISSUE_DETAIL: "issue-detail",
-}));
-
vi.mock("@/react/lib/project-member/utils", () => ({
// Wrap in vi.fn() so per-test overrides (vi.mocked(x).mockReturnValue(...))
// work — plain arrow functions can't be re-mocked at runtime.
diff --git a/frontend/src/react/pages/settings/RequestRoleSheet.tsx b/frontend/src/react/pages/settings/RequestRoleSheet.tsx
index e2a20c0fa2..2932037ca6 100644
--- a/frontend/src/react/pages/settings/RequestRoleSheet.tsx
+++ b/frontend/src/react/pages/settings/RequestRoleSheet.tsx
@@ -36,9 +36,9 @@ import {
roleHasDatabaseLimitation,
} from "@/react/lib/project-member/utils";
import { displayRoleTitleFromList } from "@/react/lib/role";
+import { router } from "@/react/router";
+import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
import { pushNotification } from "@/store";
import type { Permission } from "@/types";
import { type DatabaseResource, PresetRoleType } from "@/types";
diff --git a/frontend/src/react/pages/settings/RolesPage.tsx b/frontend/src/react/pages/settings/RolesPage.tsx
index ae6b59c634..90c145ea03 100644
--- a/frontend/src/react/pages/settings/RolesPage.tsx
+++ b/frontend/src/react/pages/settings/RolesPage.tsx
@@ -47,7 +47,6 @@ import {
} from "@/react/components/ui/table";
import { Textarea } from "@/react/components/ui/textarea";
import { BlockTooltip } from "@/react/components/ui/tooltip";
-import { useVueState } from "@/react/hooks/useVueState";
import {
displayRoleDescriptionFromList,
displayRoleTitleFromList,
@@ -682,8 +681,8 @@ export function RolesPage() {
const [deleteTarget, setDeleteTarget] = useState<Role | undefined>();
const [deleteResources, setDeleteResources] = useState<string[]>([]);
- const hasCustomRoleFeature = useVueState(() =>
- useAppStore.getState().hasInstanceFeature(PlanFeature.FEATURE_CUSTOM_ROLES)
+ const hasCustomRoleFeature = useAppStore((s) =>
+ s.hasInstanceFeature(PlanFeature.FEATURE_CUSTOM_ROLES)
);
const canCreate = hasWorkspacePermissionV2("bb.roles.create");
diff --git a/frontend/src/react/pages/settings/SQLReviewDetailPage.tsx b/frontend/src/react/pages/settings/SQLReviewDetailPage.tsx
index 50e9ddae0e..9ddded6c29 100644
--- a/frontend/src/react/pages/settings/SQLReviewDetailPage.tsx
+++ b/frontend/src/react/pages/settings/SQLReviewDetailPage.tsx
@@ -17,11 +17,10 @@ import {
DialogTitle,
} from "@/react/components/ui/dialog";
import { Input } from "@/react/components/ui/input";
-import { useVueState } from "@/react/hooks/useVueState";
import { rulesToTemplate } from "@/react/lib/sql-review/utils";
+import { router } from "@/react/router";
+import { WORKSPACE_ROUTE_SQL_REVIEW } from "@/react/router/handles";
import { useSQLReviewStore } from "@/react/stores/sqlReview";
-import { router } from "@/router";
-import { WORKSPACE_ROUTE_SQL_REVIEW } from "@/router/dashboard/workspaceRoutes";
import { pushNotification } from "@/store";
import type { RuleTemplateV2 } from "@/types";
import {
@@ -43,6 +42,16 @@ import {
// SQLReviewDetailPage
// ============================================================
+// Stable placeholder for an unresolved policy — a module constant so the
+// `?? UNKNOWN_REVIEW_POLICY` fallback keeps a stable reference across renders.
+const UNKNOWN_REVIEW_POLICY = {
+ id: `${UNKNOWN_ID}`,
+ enforce: false,
+ name: "",
+ ruleList: [],
+ resources: [],
+};
+
export function SQLReviewDetailPage({
sqlReviewPolicySlug,
}: {
@@ -63,16 +72,8 @@ export function SQLReviewDetailPage({
.getOrFetchReviewPolicyByName(sqlReviewName, false);
}, [sqlReviewName]);
- const reviewPolicy = useVueState(
- () =>
- store.getReviewPolicyByName(sqlReviewName) ?? {
- id: `${UNKNOWN_ID}`,
- enforce: false,
- name: "",
- ruleList: [],
- resources: [],
- }
- );
+ const reviewPolicy =
+ store.getReviewPolicyByName(sqlReviewName) ?? UNKNOWN_REVIEW_POLICY;
// Set document title
useEffect(() => {
diff --git a/frontend/src/react/pages/settings/SQLReviewPage.tsx b/frontend/src/react/pages/settings/SQLReviewPage.tsx
index 3a3317b209..19f7ad79a5 100644
--- a/frontend/src/react/pages/settings/SQLReviewPage.tsx
+++ b/frontend/src/react/pages/settings/SQLReviewPage.tsx
@@ -17,13 +17,12 @@ import {
TableRow,
} from "@/react/components/ui/table";
import { Tooltip } from "@/react/components/ui/tooltip";
-import { useVueState } from "@/react/hooks/useVueState";
-import { useSQLReviewStore } from "@/react/stores/sqlReview";
-import { router } from "@/router";
+import { router } from "@/react/router";
import {
WORKSPACE_ROUTE_SQL_REVIEW_CREATE,
WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,
-} from "@/router/dashboard/workspaceRoutes";
+} from "@/react/router/handles";
+import { useSQLReviewStore } from "@/react/stores/sqlReview";
import { pushNotification } from "@/store";
import type { SQLReviewPolicy } from "@/types";
import { hasWorkspacePermissionV2, sqlReviewPolicySlug } from "@/utils";
@@ -250,7 +249,7 @@ export function SQLReviewPage() {
useSQLReviewStore.getState().fetchReviewPolicyList();
}, []);
- const policyList = useVueState(() => [...sqlReviewStore.reviewPolicyList]);
+ const policyList = sqlReviewStore.reviewPolicyList;
const filteredList = useMemo(() => {
if (!searchText) return policyList;
diff --git a/frontend/src/react/pages/settings/SemanticTypesPage.tsx b/frontend/src/react/pages/settings/SemanticTypesPage.tsx
index b38d2c41f1..3676c9055a 100644
--- a/frontend/src/react/pages/settings/SemanticTypesPage.tsx
+++ b/frontend/src/react/pages/settings/SemanticTypesPage.tsx
@@ -29,7 +29,6 @@ import {
TableRow,
} from "@/react/components/ui/table";
import { Tooltip } from "@/react/components/ui/tooltip";
-import { useVueState } from "@/react/hooks/useVueState";
import { useAppStore } from "@/react/stores/app";
import { pushNotification } from "@/store";
import { getSemanticTemplateList } from "@/types";
@@ -98,8 +97,8 @@ export function SemanticTypesPage() {
const { t } = useTranslation();
const hasPermission = hasWorkspacePermissionV2("bb.policies.update");
- const hasSensitiveDataFeature = useVueState(() =>
- useAppStore.getState().hasInstanceFeature(PlanFeature.FEATURE_DATA_MASKING)
+ const hasSensitiveDataFeature = useAppStore((s) =>
+ s.hasInstanceFeature(PlanFeature.FEATURE_DATA_MASKING)
);
const isReadonly = !hasPermission || !hasSensitiveDataFeature;
diff --git a/frontend/src/react/pages/settings/ServiceAccountsPage.tsx b/frontend/src/react/pages/settings/ServiceAccountsPage.tsx
index 1fe8c64ea2..230fb62257 100644
--- a/frontend/src/react/pages/settings/ServiceAccountsPage.tsx
+++ b/frontend/src/react/pages/settings/ServiceAccountsPage.tsx
@@ -28,7 +28,7 @@ import {
} from "@/react/components/ui/table";
import { Tooltip } from "@/react/components/ui/tooltip";
import { PagedTableFooter, usePagedData } from "@/react/hooks/usePagedData";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { cn } from "@/react/lib/utils";
import { useAppStore } from "@/react/stores/app";
import {
@@ -438,11 +438,10 @@ function ServiceAccountForm({
// subscribe to re-render on project cache change
void projectsByName;
- const projectEntity = useVueState(() =>
- project ? useAppStore.getState().getProjectByName(project) : undefined
- );
+ const projectEntityFromName = useProjectByName(project ?? "");
+ const projectEntity = project ? projectEntityFromName : undefined;
- const parent = useVueState(() => project ?? workspaceResourceName);
+ const parent = project ?? workspaceResourceName;
const isEditMode = !!serviceAccount && !!serviceAccount.email;
const emailSuffix = useMemo(() => {
@@ -681,13 +680,10 @@ export function ServiceAccountsPage({ projectId }: { projectId?: string }) {
: undefined;
// subscribe to re-render on project cache change
void projectsByName;
- const project = useVueState(() =>
- projectName
- ? useAppStore.getState().getProjectByName(projectName)
- : undefined
- );
+ const projectFromName = useProjectByName(projectName ?? "");
+ const project = projectName ? projectFromName : undefined;
- const parent = useVueState(() => projectName ?? workspaceResourceName);
+ const parent = projectName ?? workspaceResourceName;
const [showInactive, setShowInactive] = useState(false);
const [showDrawer, setShowDrawer] = useState(false);
diff --git a/frontend/src/react/pages/settings/UsersPage.tsx b/frontend/src/react/pages/settings/UsersPage.tsx
index 5ff5e00b90..0569f0d6fc 100644
--- a/frontend/src/react/pages/settings/UsersPage.tsx
+++ b/frontend/src/react/pages/settings/UsersPage.tsx
@@ -42,12 +42,12 @@ import { Tooltip } from "@/react/components/ui/tooltip";
import { useCurrentUser } from "@/react/hooks/useAppState";
import { PagedTableFooter, usePagedData } from "@/react/hooks/usePagedData";
import { cn } from "@/react/lib/utils";
-import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
+import { router } from "@/react/router";
import {
WORKSPACE_ROUTE_GROUPS,
WORKSPACE_ROUTE_USER_PROFILE,
-} from "@/router/dashboard/workspaceRoutes";
+} from "@/react/router/handles";
+import { useAppStore } from "@/react/stores/app";
import { pushNotification } from "@/store";
import { getUserFullNameByType } from "@/store/modules/v1/common";
import {
diff --git a/frontend/src/react/pages/settings/WorkloadIdentitiesPage.tsx b/frontend/src/react/pages/settings/WorkloadIdentitiesPage.tsx
index 88b86d7efa..dd08cf32de 100644
--- a/frontend/src/react/pages/settings/WorkloadIdentitiesPage.tsx
+++ b/frontend/src/react/pages/settings/WorkloadIdentitiesPage.tsx
@@ -16,7 +16,7 @@ import {
} from "@/react/components/ui/table";
import { Tooltip } from "@/react/components/ui/tooltip";
import { PagedTableFooter, usePagedData } from "@/react/hooks/usePagedData";
-import { useVueState } from "@/react/hooks/useVueState";
+import { useProjectByName } from "@/react/hooks/useProjectByName";
import { useAppStore } from "@/react/stores/app";
import {
ensureWorkloadIdentityFullName,
@@ -247,13 +247,10 @@ export function WorkloadIdentitiesPage({ projectId }: { projectId?: string }) {
: undefined;
// subscribe to re-render on project cache change
void projectsByName;
- const project = useVueState(() =>
- projectName
- ? useAppStore.getState().getProjectByName(projectName)
- : undefined
- );
+ const projectFromName = useProjectByName(projectName ?? "");
+ const project = projectName ? projectFromName : undefined;
- const parent = useVueState(() => projectName ?? workspaceResourceName);
+ const parent = projectName ?? workspaceResourceName;
const [showInactive, setShowInactive] = useState(false);
const [showDrawer, setShowDrawer] = useState(false);
diff --git a/frontend/src/react/pages/settings/general/GeneralSection.tsx b/frontend/src/react/pages/settings/general/GeneralSection.tsx
index 9560d57852..f7fba0627c 100644
--- a/frontend/src/react/pages/settings/general/GeneralSection.tsx
+++ b/frontend/src/react/pages/settings/general/GeneralSection.tsx
@@ -23,9 +23,9 @@ import {
} from "@/react/components/ui/dialog";
import { Input } from "@/react/components/ui/input";
import { useServerState } from "@/react/hooks/useAppState";
+import { router } from "@/react/router";
+import { SQL_EDITOR_HOME_MODULE } from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { SQL_EDITOR_HOME_MODULE } from "@/router/sqlEditor";
import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";
import type { SectionHandle } from "./useSettingSection";
diff --git a/frontend/src/react/pages/settings/profile/ProfilePage.test.tsx b/frontend/src/react/pages/settings/profile/ProfilePage.test.tsx
index 9e73de4904..b41a6adea6 100644
--- a/frontend/src/react/pages/settings/profile/ProfilePage.test.tsx
+++ b/frontend/src/react/pages/settings/profile/ProfilePage.test.tsx
@@ -25,7 +25,6 @@ const updatedCurrentUser = {
};
const mocks = vi.hoisted(() => ({
- useVueState: vi.fn<(getter: () => unknown) => unknown>((getter) => getter()),
useCurrentUser: vi.fn(() => legacyCurrentUser),
useAuthStore: vi.fn(() => ({
updateCurrentUserNameForEmailChange: vi.fn(),
@@ -45,10 +44,6 @@ const mocks = vi.hoisted(() => ({
hasWorkspacePermissionV2: vi.fn(() => true),
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
vi.mock("@/react/hooks/useAppState", () => ({
useCurrentUser: mocks.useCurrentUser,
}));
@@ -63,10 +58,12 @@ vi.mock("@/react/stores/app", () => {
getOrFetchUserByIdentifier: mocks.getOrFetchUserByIdentifier,
updateUser: mocks.updateUser,
updateEmail: mocks.updateEmail,
+ updateCurrentUserNameForEmailChange: () => {},
roleList: [],
workspacePolicy: undefined,
getWorkspaceRolesByName: mocks.getWorkspaceRolesByName,
fetchWorkspaceIamPolicy: mocks.fetchWorkspaceIamPolicy,
+ hasFeature: () => mocks.hasFeature(),
// Migrated off the Pinia actuator/setting store mocks.
isSaaSMode: () => false,
getWorkspaceProfile: () => ({
@@ -86,28 +83,14 @@ vi.mock("@/store", () => ({
useAuthStore: mocks.useAuthStore,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
replace: mocks.routerReplace,
push: mocks.routerPush,
},
}));
-vi.mock("@/router/dashboard/workspaceRoutes", async (importOriginal) => {
- const actual =
- await importOriginal<typeof import("@/router/dashboard/workspaceRoutes")>();
- return {
- ...actual,
- WORKSPACE_ROUTE_404: "404",
- WORKSPACE_ROUTE_USER_PROFILE: "user-profile",
- };
-});
-
-vi.mock("@/router/dashboard/workspaceSetting", () => ({
- SETTING_ROUTE_PROFILE_TWO_FACTOR: "profile.two-factor",
- SETTING_ROUTE_WORKSPACE_SUBSCRIPTION: "workspace.subscription",
-}));
-
vi.mock("@/utils", () => ({
hasWorkspacePermissionV2: mocks.hasWorkspacePermissionV2,
setDocumentTitle: mocks.setDocumentTitle,
@@ -218,6 +201,7 @@ vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string) => key,
}),
+ initReactI18next: { type: "3rdParty", init: () => {} },
}));
let ProfilePage: typeof import("./ProfilePage").ProfilePage;
diff --git a/frontend/src/react/pages/settings/profile/ProfilePage.tsx b/frontend/src/react/pages/settings/profile/ProfilePage.tsx
index 7d9c02834a..6d0439a3d7 100644
--- a/frontend/src/react/pages/settings/profile/ProfilePage.tsx
+++ b/frontend/src/react/pages/settings/profile/ProfilePage.tsx
@@ -25,20 +25,17 @@ import { FeatureModal } from "@/react/components/ui/feature-modal";
import { Input } from "@/react/components/ui/input";
import { useCurrentUser } from "@/react/hooks/useAppState";
import { useUnsavedChangesGuard } from "@/react/hooks/useUnsavedChangesGuard";
-import { useVueState } from "@/react/hooks/useVueState";
import { displayRoleTitleFromList } from "@/react/lib/role";
import { RegenerateRecoveryCodesView } from "@/react/pages/settings/two-factor/RegenerateRecoveryCodesView";
-import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import {
- WORKSPACE_ROUTE_404,
- WORKSPACE_ROUTE_USER_PROFILE,
-} from "@/router/dashboard/workspaceRoutes";
+import { router } from "@/react/router";
import {
SETTING_ROUTE_PROFILE_TWO_FACTOR,
SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,
-} from "@/router/dashboard/workspaceSetting";
-import { hasFeature, pushNotification, useAuthStore } from "@/store";
+ WORKSPACE_ROUTE_404,
+ WORKSPACE_ROUTE_USER_PROFILE,
+} from "@/react/router/handles";
+import { useAppStore } from "@/react/stores/app";
+import { hasFeature, pushNotification } from "@/store";
import {
AccountType,
ALL_USERS_USER_EMAIL,
@@ -62,7 +59,9 @@ interface ProfilePageProps {
export function ProfilePage({ principalEmail }: ProfilePageProps) {
const { t } = useTranslation();
- const authStore = useAuthStore();
+ const updateCurrentUserNameForEmailChange = useAppStore(
+ (state) => state.updateCurrentUserNameForEmailChange
+ );
const getOrFetchUserByIdentifier = useAppStore(
(state) => state.getOrFetchUserByIdentifier
);
@@ -93,15 +92,15 @@ export function ProfilePage({ principalEmail }: ProfilePageProps) {
(s) => s.getWorkspaceProfile().passwordRestriction
);
- const isSaaSMode = useVueState(() => useAppStore.getState().isSaaSMode());
+ const isSaaSMode = useAppStore((s) => s.isSaaSMode());
- const has2FAFeature = useVueState(() =>
- hasFeature(PlanFeature.FEATURE_TWO_FA)
+ const has2FAFeature = useAppStore((s) =>
+ s.hasFeature(PlanFeature.FEATURE_TWO_FA)
);
const requireMfa = useAppStore((s) => s.getWorkspaceProfile().requireMfa);
- const tempRecoveryCodes = useVueState(() => currentUser.tempRecoveryCodes);
+ const tempRecoveryCodes = currentUser.tempRecoveryCodes;
// --- Derived values ---
const isSelf = currentUser.name === user.name;
@@ -244,7 +243,7 @@ export function ProfilePage({ principalEmail }: ProfilePageProps) {
const updatedUser = await updateEmail(oldEmail, editingUser.email);
migrateUserStorage(oldEmail, editingUser.email);
if (isSelf) {
- authStore.updateCurrentUserNameForEmailChange(updatedUser.name);
+ updateCurrentUserNameForEmailChange(updatedUser.name);
setCurrentUser(updatedUser);
}
}
diff --git a/frontend/src/react/pages/settings/two-factor/TwoFactorSetupPage.test.tsx b/frontend/src/react/pages/settings/two-factor/TwoFactorSetupPage.test.tsx
index 3e3f95fd11..fc5f27f2fc 100644
--- a/frontend/src/react/pages/settings/two-factor/TwoFactorSetupPage.test.tsx
+++ b/frontend/src/react/pages/settings/two-factor/TwoFactorSetupPage.test.tsx
@@ -27,7 +27,6 @@ const regeneratedCurrentUser = {
};
const mocks = vi.hoisted(() => ({
- useVueState: vi.fn<(getter: () => unknown) => unknown>((getter) => getter()),
useCurrentUser: vi.fn(() => legacyCurrentUser),
updateUser: vi.fn(async () => regeneratedCurrentUser),
pushNotification: vi.fn(),
@@ -37,10 +36,6 @@ const mocks = vi.hoisted(() => ({
},
}));
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
vi.mock("@/react/hooks/useAppState", () => ({
useCurrentUser: mocks.useCurrentUser,
}));
@@ -56,21 +51,14 @@ vi.mock("@/store", () => ({
pushNotification: mocks.pushNotification,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
replace: mocks.routerReplace,
currentRoute: mocks.currentRoute,
},
}));
-vi.mock("@/router/auth", () => ({
- AUTH_2FA_SETUP_MODULE: "auth.2fa-setup",
-}));
-
-vi.mock("@/router/dashboard/workspaceSetting", () => ({
- SETTING_ROUTE_PROFILE: "workspace.setting.profile",
-}));
-
vi.mock("@bufbuild/protobuf", async (importOriginal) => {
const actual = await importOriginal<typeof import("@bufbuild/protobuf")>();
return {
diff --git a/frontend/src/react/pages/settings/two-factor/TwoFactorSetupPage.tsx b/frontend/src/react/pages/settings/two-factor/TwoFactorSetupPage.tsx
index eb97f82c9b..08e20fb923 100644
--- a/frontend/src/react/pages/settings/two-factor/TwoFactorSetupPage.tsx
+++ b/frontend/src/react/pages/settings/two-factor/TwoFactorSetupPage.tsx
@@ -9,10 +9,12 @@ import { LearnMoreLink } from "@/react/components/LearnMoreLink";
import { Button } from "@/react/components/ui/button";
import { OtpInput } from "@/react/components/ui/otp-input";
import { useCurrentUser } from "@/react/hooks/useAppState";
+import { router } from "@/react/router";
+import {
+ AUTH_2FA_SETUP_MODULE,
+ SETTING_ROUTE_PROFILE,
+} from "@/react/router/handles";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
-import { AUTH_2FA_SETUP_MODULE } from "@/router/auth";
-import { SETTING_ROUTE_PROFILE } from "@/router/dashboard/workspaceSetting";
import { pushNotification } from "@/store";
import { UpdateUserRequestSchema } from "@/types/proto-es/v1/user_service_pb";
import { RecoveryCodesView } from "./RecoveryCodesView";
diff --git a/frontend/src/react/pages/workspace/MyIssuesPage.tsx b/frontend/src/react/pages/workspace/MyIssuesPage.tsx
index e42070dc55..af1e8483ea 100644
--- a/frontend/src/react/pages/workspace/MyIssuesPage.tsx
+++ b/frontend/src/react/pages/workspace/MyIssuesPage.tsx
@@ -13,8 +13,8 @@ import {
import { useCurrentUser } from "@/react/hooks/useAppState";
import { PagedTableFooter, usePagedData } from "@/react/hooks/usePagedData";
import { refreshIssueList } from "@/react/lib/issue/issueListRefresh";
+import { router } from "@/react/router";
import { useAppStore } from "@/react/stores/app";
-import { router } from "@/router";
import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";
diff --git a/frontend/src/react/pages/workspace/Page403.tsx b/frontend/src/react/pages/workspace/Page403.tsx
index b83692f923..5f8094ad36 100644
--- a/frontend/src/react/pages/workspace/Page403.tsx
+++ b/frontend/src/react/pages/workspace/Page403.tsx
@@ -2,8 +2,8 @@ import { ChevronLeft, ShieldAlert } from "lucide-react";
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/react/components/ui/button";
-import { router } from "@/router";
-import { WORKSPACE_ROOT_MODULE } from "@/router/dashboard/workspaceRoutes";
+import { router } from "@/react/router";
+import { WORKSPACE_ROOT_MODULE } from "@/react/router/handles";
import type { Permission } from "@/types";
export function Page403() {
diff --git a/frontend/src/react/pages/workspace/Page404.tsx b/frontend/src/react/pages/workspace/Page404.tsx
index fc9bc11da8..7c52ed525c 100644
--- a/frontend/src/react/pages/workspace/Page404.tsx
+++ b/frontend/src/react/pages/workspace/Page404.tsx
@@ -2,8 +2,8 @@ import { ChevronLeft } from "lucide-react";
import { useTranslation } from "react-i18next";
import logoIcon from "@/assets/logo-icon.svg";
import { Button } from "@/react/components/ui/button";
-import { router } from "@/router";
-import { WORKSPACE_ROOT_MODULE } from "@/router/dashboard/workspaceRoutes";
+import { router } from "@/react/router";
+import { WORKSPACE_ROOT_MODULE } from "@/react/router/handles";
export function Page404() {
const { t } = useTranslation();
diff --git a/frontend/src/react/plugins/agent/components/AgentChat.test.tsx b/frontend/src/react/plugins/agent/components/AgentChat.test.tsx
index 5f8f8823ed..5abf96b0bd 100644
--- a/frontend/src/react/plugins/agent/components/AgentChat.test.tsx
+++ b/frontend/src/react/plugins/agent/components/AgentChat.test.tsx
@@ -45,7 +45,8 @@ vi.mock("react-i18next", () => ({
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
push: vi.fn(),
},
diff --git a/frontend/src/react/plugins/agent/components/AgentChat.tsx b/frontend/src/react/plugins/agent/components/AgentChat.tsx
index 87e2cb2756..78eaac776a 100644
--- a/frontend/src/react/plugins/agent/components/AgentChat.tsx
+++ b/frontend/src/react/plugins/agent/components/AgentChat.tsx
@@ -3,8 +3,8 @@ import { useTranslation } from "react-i18next";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { Button } from "@/react/components/ui/button";
-import { router } from "@/router";
-import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";
+import { router } from "@/react/router";
+import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/react/router/handles";
import { hasWorkspacePermissionV2 } from "@/utils";
import type { AgentMessage, ToolCall } from "../logic/types";
import {
diff --git a/frontend/src/react/plugins/agent/components/AgentInput.test.tsx b/frontend/src/react/plugins/agent/components/AgentInput.test.tsx
index 657c4a614d..1c3be2951f 100644
--- a/frontend/src/react/plugins/agent/components/AgentInput.test.tsx
+++ b/frontend/src/react/plugins/agent/components/AgentInput.test.tsx
@@ -60,7 +60,8 @@ vi.mock("react-i18next", () => ({
useTranslation: mocks.useTranslation,
}));
-vi.mock("@/router", () => ({
+vi.mock("@/react/router", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/react/router")>()),
router: {
currentRoute: {
value: {
diff --git a/frontend/src/react/plugins/agent/components/AgentInput.tsx b/frontend/src/react/plugins/agent/components/AgentInput.tsx
index 5a0317a391..1bd34162b4 100644
--- a/frontend/src/react/plugins/agent/components/AgentInput.tsx
+++ b/frontend/src/react/plugins/agent/components/AgentInput.tsx
@@ -12,7 +12,7 @@ import { useTranslation } from "react-i18next";
import { v4 as uuidv4 } from "uuid";
import { Button } from "@/react/components/ui/button";
import { getLayerRoot, LAYER_SURFACE_CLASS } from "@/react/components/ui/layer";
-import { router } from "@/router";
+import { router } from "@/react/router";
import type { DomRefSuggestion } from "../dom";
import { lazyExtractDomRefSuggestions } from "../dom";
import { runAgentLoop } from "../logic/agentLoop";
diff --git a/frontend/src/react/plugins/agent/dom/index.test.ts b/frontend/src/react/plugins/agent/dom/index.test.ts
index 9cad54ad73..ef75296f6a 100644
--- a/frontend/src/react/plugins/agent/dom/index.test.ts
+++ b/frontend/src/react/plugins/agent/dom/index.test.ts
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, test, vi } from "vitest";
-import type { Router } from "vue-router";
+import type { AppRouterInstance } from "@/react/router";
import {
lazyExecuteDomAction,
lazyExtractDomRefSuggestions,
@@ -142,7 +142,7 @@ describe("lazyExecuteDomAction", () => {
const router = {
push: vi.fn().mockResolvedValue(undefined),
- } as unknown as Router;
+ } as unknown as AppRouterInstance;
const result = await lazyExecuteDomAction(
{ type: "click", ref: "e1" },
diff --git a/frontend/src/react/plugins/agent/dom/index.ts b/frontend/src/react/plugins/agent/dom/index.ts
index 8aed96d48d..401cd0890b 100644
--- a/frontend/src/react/plugins/agent/dom/index.ts
+++ b/frontend/src/react/plugins/agent/dom/index.ts
@@ -1,4 +1,4 @@
-import type { Router } from "vue-router";
+import type { AppRouterInstance } from "@/react/router";
import type {
DomActionParams,
DomActionResult,
@@ -61,7 +61,7 @@ function getElementRef(params: DomActionParams): string | undefined {
export async function lazyExecuteDomAction(
params: DomActionParams,
- router?: Router
+ router?: AppRouterInstance
): Promise<DomActionResult> {
const elementRef = getElementRef(params);
if (!elementRef) {
@@ -84,7 +84,7 @@ export async function lazyExecuteDomAction(
return formatRefreshError(`Element [${elementRef}] is stale.`);
}
- // For <a> clicks, use Vue Router to avoid full page reload
+ // For <a> clicks, use Vue AppRouterInstance to avoid full page reload
if (params.type === "click" && router) {
const path = isSameOriginLink(entry.element);
if (path) {
diff --git a/frontend/src/react/plugins/agent/logic/context.ts b/frontend/src/react/plugins/agent/logic/context.ts
index 34c6e85036..c3e1842d5b 100644
--- a/frontend/src/react/plugins/agent/logic/context.ts
+++ b/frontend/src/react/plugins/agent/logic/context.ts
@@ -1,4 +1,4 @@
-import type { RouteLocationNormalizedLoaded } from "vue-router";
+import type { ReactRoute } from "@/react/router";
import { useAppStore } from "@/react/stores/app";
import { Engine, State } from "@/types/proto-es/v1/common_pb";
import { Issue_Type, IssueStatus } from "@/types/proto-es/v1/issue_service_pb";
@@ -12,7 +12,7 @@ interface PageContext {
}
export async function extractRouteContext(
- route: RouteLocationNormalizedLoaded
+ route: ReactRoute
): Promise<PageContext> {
const ctx: PageContext = {};
diff --git a/frontend/src/react/plugins/agent/logic/tools/domAction.test.ts b/frontend/src/react/plugins/agent/logic/tools/domAction.test.ts
index 1f25ad5db0..169939733b 100644
--- a/frontend/src/react/plugins/agent/logic/tools/domAction.test.ts
+++ b/frontend/src/react/plugins/agent/logic/tools/domAction.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test, vi } from "vitest";
-import type { Router } from "vue-router";
+import type { AppRouterInstance } from "@/react/router";
vi.mock("../../dom", () => ({
lazyExecuteDomAction: vi.fn(async () => ({ success: true, message: "done" })),
@@ -10,7 +10,7 @@ import { createDomActionTool } from "./domAction";
describe("createDomActionTool", () => {
test("forwards read actions with ref-based args", async () => {
- const router = { push: vi.fn() } as unknown as Router;
+ const router = { push: vi.fn() } as unknown as AppRouterInstance;
const tool = createDomActionTool(router);
const result = await tool({ type: "read", ref: "e3" });
diff --git a/frontend/src/react/plugins/agent/logic/tools/domAction.ts b/frontend/src/react/plugins/agent/logic/tools/domAction.ts
index d8d044712d..db5a6802ac 100644
--- a/frontend/src/react/plugins/agent/logic/tools/domAction.ts
+++ b/frontend/src/react/plugins/agent/logic/tools/domAction.ts
@@ -1,4 +1,4 @@
-import type { Router } from "vue-router";
+import type { AppRouterInstance } from "@/react/router";
import { lazyExecuteDomAction } from "../../dom";
export interface DomActionArgs {
@@ -7,7 +7,7 @@ export interface DomActionArgs {
value?: string;
}
-export function createDomActionTool(router: Router) {
+export function createDomActionTool(router: AppRouterInstance) {
return async (args: DomActionArgs): Promise<string> => {
const result = await lazyExecuteDomAction(args, router);
return JSON.stringify(result);
diff --git a/frontend/src/react/plugins/agent/logic/tools/index.test.ts b/frontend/src/react/plugins/agent/logic/tools/index.test.ts
index a494ed7d18..66ba8809f0 100644
--- a/frontend/src/react/plugins/agent/logic/tools/index.test.ts
+++ b/frontend/src/react/plugins/agent/logic/tools/index.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test, vi } from "vitest";
-import type { Router } from "vue-router";
+import type { AppRouterInstance } from "@/react/router";
vi.mock("../skills", () => ({
getSkill: vi.fn(async () => "skill"),
@@ -33,7 +33,9 @@ describe("agent tools navigate", () => {
);
vi.mocked(createNavigateTool).mockReturnValue(navigateTool);
const onNavigate = vi.fn();
- const executeTool = createToolExecutor({} as Router, { onNavigate });
+ const executeTool = createToolExecutor({} as AppRouterInstance, {
+ onNavigate,
+ });
const result = await executeTool(
"navigate",
@@ -129,7 +131,7 @@ describe("agent tools ask_user", () => {
});
test("parses choose prompts with sanitized options", async () => {
- const executeTool = createToolExecutor({} as Router);
+ const executeTool = createToolExecutor({} as AppRouterInstance);
const result = await executeTool(
"ask_user",
@@ -175,7 +177,7 @@ describe("agent tools ask_user", () => {
});
test("falls back to input when choose options are missing", async () => {
- const executeTool = createToolExecutor({} as Router);
+ const executeTool = createToolExecutor({} as AppRouterInstance);
const result = await executeTool(
"ask_user",
@@ -263,10 +265,10 @@ describe("agent tools concurrency guard", () => {
);
});
- const firstExecutor = createToolExecutor({} as Router, {
+ const firstExecutor = createToolExecutor({} as AppRouterInstance, {
chatId: "thread-1",
});
- const secondExecutor = createToolExecutor({} as Router, {
+ const secondExecutor = createToolExecutor({} as AppRouterInstance, {
chatId: "thread-2",
});
diff --git a/frontend/src/react/plugins/agent/logic/tools/index.ts b/frontend/src/react/plugins/agent/logic/tools/index.ts
index 1226d2d8a9..4e9454e478 100644
--- a/frontend/src/react/plugins/agent/logic/tools/index.ts
+++ b/frontend/src/react/plugins/agent/logic/tools/index.ts
@@ -1,4 +1,4 @@
-import type { Router } from "vue-router";
+import type { AppRouterInstance } from "@/react/router";
import { getSkill, type GetSkillArgs } from "../skills";
import type {
AgentAskUserKind,
@@ -398,7 +398,7 @@ const withPageMutationLock = async <T>(
};
export function createToolExecutor(
- router: Router,
+ router: AppRouterInstance,
options: CreateToolExecutorOptions = {}
): ToolExecutor {
const navigateTool = createNavigateTool(router);
diff --git a/frontend/src/react/plugins/agent/logic/tools/navigate.ts b/frontend/src/react/plugins/agent/logic/tools/navigate.ts
index a3d487503b..ae47b38576 100644
--- a/frontend/src/react/plugins/agent/logic/tools/navigate.ts
+++ b/frontend/src/react/plugins/agent/logic/tools/navigate.ts
@@ -1,6 +1,6 @@
-import type { Router } from "vue-router";
+import type { AppRouterInstance } from "@/react/router";
-function getRouteMap(router: Router): string[] {
+function getRouteMap(router: AppRouterInstance): string[] {
const routes = router.getRoutes();
const paths = new Set<string>();
@@ -25,7 +25,7 @@ function getRouteMap(router: Router): string[] {
return [...paths].sort();
}
-export function createNavigateTool(router: Router) {
+export function createNavigateTool(router: AppRouterInstance) {
return async (args: { path?: string; list?: boolean }): Promise<string> => {
if (args.list) {
const routes = getRouteMap(router);
diff --git a/frontend/src/react/plugins/agent/logic/tools/pageState.test.ts b/frontend/src/react/plugins/agent/logic/tools/pageState.test.ts
index 3ca017877a..72bdbd1f58 100644
--- a/frontend/src/react/plugins/agent/logic/tools/pageState.test.ts
+++ b/frontend/src/react/plugins/agent/logic/tools/pageState.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test, vi } from "vitest";
-import type { Router } from "vue-router";
+import type { AppRouterInstance } from "@/react/router";
vi.mock("../../dom", () => ({
lazyExtractDomTree: vi.fn(async () => ({
@@ -29,7 +29,7 @@ describe("createPageStateTool", () => {
query: { view: "overview" },
},
},
- } as unknown as Router;
+ } as unknown as AppRouterInstance;
document.title = "Project Demo";
@@ -62,7 +62,7 @@ describe("createPageStateTool", () => {
query: {},
},
},
- } as unknown as Router;
+ } as unknown as AppRouterInstance;
document.title = "Issue 123";
diff --git a/frontend/src/react/plugins/agent/logic/tools/pageState.ts b/frontend/src/react/plugins/agent/logic/tools/pageState.ts
index ab01609d4d..7083c58360 100644
--- a/frontend/src/react/plugins/agent/logic/tools/pageState.ts
+++ b/frontend/src/react/plugins/agent/logic/tools/pageState.ts
@@ -1,4 +1,4 @@
-import type { Router } from "vue-router";
+import type { AppRouterInstance } from "@/react/router";
import { lazyExtractDomTree } from "../../dom";
import { extractRouteContext } from "../context";
@@ -6,7 +6,7 @@ export interface PageStateArgs {
mode?: "semantic" | "dom";
}
-export function createPageStateTool(router: Router) {
+export function createPageStateTool(router: AppRouterInstance) {
return async (args?: PageStateArgs): Promise<string> => {
const route = router.currentRoute.value;
const base: Record<string, unknown> = {
diff --git a/frontend/src/react/router/ProjectRouteGate.test.tsx b/frontend/src/react/router/ProjectRouteGate.test.tsx
new file mode 100644
index 0000000000..4daebe6917
--- /dev/null
+++ b/frontend/src/react/router/ProjectRouteGate.test.tsx
@@ -0,0 +1,175 @@
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import type { Permission } from "@/types";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ route: {
+ name: "workspace.project.database",
+ fullPath: "/projects/prod/databases",
+ params: { projectId: "prod" },
+ query: {},
+ requiredPermissions: [] as Permission[],
+ },
+ params: { projectId: "prod" } as Record<string, string>,
+ projectsByName: {} as Record<string, unknown>,
+ projectErrorsByName: {} as Record<string, { message: string }>,
+ workspacePermissions: new Set<Permission>(),
+ projectPermissions: new Set<Permission>(),
+ fetchProject: vi.fn(async (name: string) => mocks.projectsByName[name]),
+ replace: vi.fn(),
+ resolve: vi.fn(() => ({ fullPath: "/projects/prod" })),
+ // Stable ref — mirrors the real `useNotify` (returns `state.notify`). A fresh
+ // function each render would make the load effect's deps unstable and loop.
+ notify: vi.fn(),
+}));
+
+vi.mock("react-router-dom", () => ({
+ Outlet: () => <div data-testid="outlet" />,
+ useParams: () => mocks.params,
+}));
+
+vi.mock("@/react/router", () => ({
+ useCurrentRoute: () => mocks.route,
+ useNavigate: () => ({ replace: mocks.replace, resolve: mocks.resolve }),
+ WORKSPACE_ROUTE_LANDING: "workspace.landing",
+ PROJECT_V1_ROUTE_DETAIL: "workspace.project.detail",
+}));
+
+vi.mock("@/react/hooks/useAppState", () => ({
+ useNotify: () => mocks.notify,
+}));
+
+vi.mock("@/react/pages/settings/RequestRoleSheet", () => ({
+ RequestRoleSheet: () => <div data-testid="request-role-sheet" />,
+}));
+
+vi.mock("@/react/components/FeatureBadge", () => ({
+ FeatureBadge: () => <span data-testid="feature-badge" />,
+}));
+
+vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/react/stores/app", () => {
+ const state = {
+ currentUser: { name: "users/[email protected]" },
+ roles: [],
+ subscription: { plan: 3 },
+ workspacePolicy: undefined,
+ projectPoliciesByName: {},
+ get projectsByName() {
+ return mocks.projectsByName;
+ },
+ get projectErrorsByName() {
+ return mocks.projectErrorsByName;
+ },
+ serverInfo: { defaultProject: "projects/default" },
+ fetchProject: mocks.fetchProject,
+ loadCurrentUser: vi.fn(async () => undefined),
+ loadServerInfo: vi.fn(async () => undefined),
+ loadWorkspacePermissionState: vi.fn(async () => {}),
+ loadProjectIamPolicy: vi.fn(async () => undefined),
+ loadSubscription: vi.fn(async () => undefined),
+ setRecentProject: vi.fn(),
+ removeRecentVisit: vi.fn(),
+ hasWorkspacePermission: (permission: Permission) =>
+ mocks.workspacePermissions.has(permission),
+ hasProjectPermission: (_project: unknown, permission: Permission) =>
+ mocks.workspacePermissions.has(permission) ||
+ mocks.projectPermissions.has(permission),
+ };
+ const useAppStore = (selector?: (s: typeof state) => unknown) =>
+ selector ? selector(state) : state;
+ useAppStore.getState = () => state;
+ return {
+ useAppStore,
+ projectResourceNameFromId: (id: string) => `projects/${id}`,
+ };
+});
+
+import { ProjectRouteGate } from "./ProjectRouteGate";
+
+const BASIC_PERMISSIONS: Permission[] = [
+ "bb.roles.list",
+ "bb.workspaces.getIamPolicy",
+ "bb.settings.getWorkspaceProfile",
+];
+
+let container: HTMLDivElement;
+let root: ReturnType<typeof createRoot>;
+
+beforeEach(() => {
+ mocks.route.requiredPermissions = ["bb.projects.get", "bb.databases.list"];
+ mocks.params = { projectId: "prod" };
+ mocks.projectsByName = {
+ "projects/prod": { name: "projects/prod", allowRequestRole: true },
+ };
+ mocks.projectErrorsByName = {};
+ mocks.workspacePermissions = new Set(BASIC_PERMISSIONS);
+ mocks.projectPermissions = new Set();
+ mocks.fetchProject.mockClear();
+ mocks.replace.mockClear();
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ document.body.removeChild(container);
+});
+
+const render = async () => {
+ await act(async () => {
+ root.render(<ProjectRouteGate />);
+ });
+ // Flush the async project-load effect + the permission-ready effect.
+ for (let i = 0; i < 5; i++) {
+ await act(async () => {
+ await Promise.resolve();
+ });
+ }
+};
+
+describe("ProjectRouteGate", () => {
+ test("renders the Outlet when project route permissions pass", async () => {
+ mocks.projectPermissions = new Set([
+ "bb.projects.get",
+ "bb.databases.list",
+ ]);
+
+ await render();
+
+ expect(container.querySelector("[data-testid='outlet']")).not.toBeNull();
+ expect(container.querySelector("[role='alert']")).toBeNull();
+ expect(mocks.fetchProject).toHaveBeenCalledWith("projects/prod");
+ });
+
+ test("renders the permission-denied fallback when a route permission is missing", async () => {
+ // Has bb.projects.get (so the project loads) but lacks bb.databases.list.
+ mocks.projectPermissions = new Set(["bb.projects.get"]);
+
+ await render();
+
+ expect(container.querySelector("[data-testid='outlet']")).toBeNull();
+ expect(container.querySelector("[role='alert']")).not.toBeNull();
+ expect(container.textContent).toContain("bb.databases.list");
+ });
+
+ test("redirects to landing when the project cannot be loaded", async () => {
+ mocks.projectsByName = {};
+ mocks.projectErrorsByName = {};
+
+ await render();
+
+ expect(mocks.replace).toHaveBeenCalledWith({ name: "workspace.landing" });
+ expect(container.querySelector("[data-testid='outlet']")).toBeNull();
+ });
+});
diff --git a/frontend/src/react/router/ProjectRouteGate.tsx b/frontend/src/react/router/ProjectRouteGate.tsx
new file mode 100644
index 0000000000..16a9881fd1
--- /dev/null
+++ b/frontend/src/react/router/ProjectRouteGate.tsx
@@ -0,0 +1,128 @@
+import { LoaderCircle } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { Outlet, useParams } from "react-router-dom";
+import {
+ PermissionDeniedFallback,
+ useComponentPermissionState,
+ usePermissionDataReady,
+} from "@/react/components/ComponentPermissionGuard";
+import { useNotify } from "@/react/hooks/useAppState";
+import {
+ PROJECT_V1_ROUTE_DETAIL,
+ useCurrentRoute,
+ useNavigate,
+ WORKSPACE_ROUTE_LANDING,
+} from "@/react/router";
+import { projectResourceNameFromId, useAppStore } from "@/react/stores/app";
+
+// `<Outlet/>`-aware permission gate for `/projects/:projectId/*`. Project-scoped
+// permission checks need the loaded `Project` resource, so this loads the
+// project (and its IAM policy, via `usePermissionDataReady`) before gating the
+// routed leaf on `route.requiredPermissions` — the aggregated parent
+// (`bb.projects.get`) + leaf permission lists from the route handles. Mirrors
+// the project-load + gate of the Vue-bridge `ProjectRouteShell`, but renders an
+// `<Outlet/>` for react-router instead of a teleport target. A user lacking a
+// route permission sees the request-role / permission-denied fallback instead
+// of mounting the page and failing on individual API calls. (The rest of
+// `ProjectRouteShell`'s chrome — archived banner, IAM-remind dialog, document
+// title — stays with the deferred shell-mounting phase.)
+export function ProjectRouteGate() {
+ const params = useParams();
+ const projectId = params.projectId ?? "";
+ const projectName = projectResourceNameFromId(projectId);
+ const route = useCurrentRoute();
+ const navigate = useNavigate();
+ const navigateRef = useRef(navigate);
+ navigateRef.current = navigate;
+ const notify = useNotify();
+
+ const project = useAppStore((state) => state.projectsByName[projectName]);
+ const fetchProject = useAppStore((state) => state.fetchProject);
+ const loadCurrentUser = useAppStore((state) => state.loadCurrentUser);
+ const loadServerInfo = useAppStore((state) => state.loadServerInfo);
+ const setRecentProject = useAppStore((state) => state.setRecentProject);
+ const removeRecentVisit = useAppStore((state) => state.removeRecentVisit);
+ const [loadedProjectName, setLoadedProjectName] = useState("");
+
+ useEffect(() => {
+ let stale = false;
+ setLoadedProjectName("");
+
+ const load = async () => {
+ await Promise.all([loadCurrentUser(), loadServerInfo()]);
+ const nextProject = await fetchProject(projectName);
+ if (stale) return;
+ if (!nextProject) {
+ // Project missing or not accessible (e.g. no `bb.projects.get`): drop
+ // it from recent visits and bounce to landing, like ProjectRouteShell.
+ const projectRoute = navigateRef.current.resolve({
+ name: PROJECT_V1_ROUTE_DETAIL,
+ params: { projectId },
+ });
+ removeRecentVisit(projectRoute.fullPath);
+ const error = useAppStore.getState().projectErrorsByName[projectName];
+ if (error) {
+ notify({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: `Failed to fetch project ${projectId}`,
+ description: error.message,
+ });
+ }
+ void navigateRef.current.replace({ name: WORKSPACE_ROUTE_LANDING });
+ return;
+ }
+ setRecentProject(nextProject.name);
+ if (!stale) {
+ setLoadedProjectName(projectName);
+ }
+ };
+
+ void load();
+ return () => {
+ stale = true;
+ };
+ }, [
+ fetchProject,
+ loadCurrentUser,
+ loadServerInfo,
+ notify,
+ projectId,
+ projectName,
+ removeRecentVisit,
+ setRecentProject,
+ ]);
+
+ const permissionReady = usePermissionDataReady(project);
+ const { missedBasicPermissions, missedPermissions, permitted } =
+ useComponentPermissionState({
+ permissions: route.requiredPermissions,
+ project,
+ checkBasicWorkspacePermissions: true,
+ });
+
+ const loaded = loadedProjectName === projectName;
+
+ if (!loaded || !project || !permissionReady) {
+ return (
+ <div className="flex h-full min-h-0 items-center justify-center">
+ <LoaderCircle className="size-5 animate-spin text-control-light" />
+ </div>
+ );
+ }
+
+ if (!permitted) {
+ return (
+ <PermissionDeniedFallback
+ missedBasicPermissions={missedBasicPermissions}
+ missedPermissions={missedPermissions}
+ project={project}
+ className="m-4"
+ path={route.fullPath}
+ enableRequestRole
+ />
+ );
+ }
+
+ return <Outlet />;
+}
diff --git a/frontend/src/react/router/currentRouteSnapshot.test.ts b/frontend/src/react/router/currentRouteSnapshot.test.ts
new file mode 100644
index 0000000000..0f75a94efe
--- /dev/null
+++ b/frontend/src/react/router/currentRouteSnapshot.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from "vitest";
+import { router } from "./index";
+
+// Guardrail for the "getSnapshot should be cached" infinite-loop class.
+// `router.currentRoute.value` backs the `useReactiveRoute` `useSyncExternalStore`
+// snapshot. If it returns a fresh object on every read, any external-store
+// consumer re-renders forever (this crashed the SQL Editor: GutterBar →
+// useReactiveRoute → "Maximum update depth exceeded"). The snapshot is memoized in
+// `currentRouteSnapshot` to keep a stable reference between actual route
+// changes; this test fails if that memoization regresses.
+describe("router.currentRoute snapshot stability", () => {
+ it("returns a referentially stable object across reads without navigation", () => {
+ const a = router.currentRoute.value;
+ const b = router.currentRoute.value;
+ expect(a).toBe(b);
+ });
+});
diff --git a/frontend/src/react/router/guard.test.ts b/frontend/src/react/router/guard.test.ts
new file mode 100644
index 0000000000..f4a88057cc
--- /dev/null
+++ b/frontend/src/react/router/guard.test.ts
@@ -0,0 +1,148 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+// Configurable fake session, controlled per test.
+const session = {
+ isLoggedIn: false,
+ unauthenticatedOccurred: false,
+ requireResetPassword: false,
+ requireMfa: false,
+ hasTwoFa: false,
+ currentUser: undefined as { mfaEnabled: boolean } | undefined,
+};
+
+const resets = {
+ resetDatabases: vi.fn(),
+ resetInstances: vi.fn(),
+ resetProjects: vi.fn(),
+};
+
+vi.mock("@/react/stores/app", () => ({
+ useAppStore: {
+ getState: () => ({
+ isLoggedIn: () => session.isLoggedIn,
+ unauthenticatedOccurred: session.unauthenticatedOccurred,
+ requireResetPassword: () => session.requireResetPassword,
+ getWorkspaceProfile: () => ({ requireMfa: session.requireMfa }),
+ hasFeature: () => session.hasTwoFa,
+ currentUser: session.currentUser,
+ ...resets,
+ }),
+ },
+}));
+
+vi.mock("@/plugins/ai/store", () => ({
+ // Zustand store: the guard calls `useConversationStore.getState().reset()`.
+ useConversationStore: { getState: () => ({ reset: vi.fn() }) },
+}));
+
+import { rootGuard } from "./guard";
+import {
+ AUTH_2FA_SETUP_MODULE,
+ AUTH_OAUTH_CALLBACK_MODULE,
+ AUTH_PASSWORD_RESET_MODULE,
+ AUTH_SIGNIN_MODULE,
+ PROJECT_V1_ROUTE_DASHBOARD,
+ WORKSPACE_ROUTE_404,
+} from "./handles";
+import { setRouteNameIndex } from "./navigation";
+
+beforeEach(() => {
+ session.isLoggedIn = false;
+ session.unauthenticatedOccurred = false;
+ session.requireResetPassword = false;
+ session.requireMfa = false;
+ session.hasTwoFa = false;
+ session.currentUser = undefined;
+ vi.clearAllMocks();
+ setRouteNameIndex(
+ new Map<string, string>([
+ [AUTH_SIGNIN_MODULE, "/auth"],
+ [AUTH_2FA_SETUP_MODULE, "/auth/2fa-setup"],
+ [AUTH_PASSWORD_RESET_MODULE, "/auth/password-reset"],
+ [WORKSPACE_ROUTE_404, "/404"],
+ ])
+ );
+});
+
+const loc = (location: (typeof window)["location"] | undefined) => location;
+void loc; // keep TS happy if unused
+
+function run(name: string | undefined, path: string) {
+ return rootGuard({ name, url: new URL(`https://app.example.com${path}`) });
+}
+
+function location(result: Response | null): string | null {
+ return result instanceof Response ? result.headers.get("Location") : null;
+}
+
+describe("rootGuard", () => {
+ test("error page is allowed directly", () => {
+ expect(run(WORKSPACE_ROUTE_404, "/404")).toBeNull();
+ });
+
+ test("oauth callback is allowed directly", () => {
+ expect(run(AUTH_OAUTH_CALLBACK_MODULE, "/auth/oauth/callback")).toBeNull();
+ });
+
+ test("logged-in user on 2FA-setup route is allowed", () => {
+ session.isLoggedIn = true;
+ expect(run(AUTH_2FA_SETUP_MODULE, "/auth/2fa-setup")).toBeNull();
+ });
+
+ test("logged-in user on the signin route is redirected home", () => {
+ session.isLoggedIn = true;
+ expect(location(run(AUTH_SIGNIN_MODULE, "/auth"))).toBe("/");
+ });
+
+ test("logged-in user on signin with ?redirect goes there", () => {
+ session.isLoggedIn = true;
+ expect(location(run(AUTH_SIGNIN_MODULE, "/auth?redirect=/projects"))).toBe(
+ "/projects"
+ );
+ });
+
+ test("auth route resets caches and allows access", () => {
+ expect(run(AUTH_SIGNIN_MODULE, "/auth")).toBeNull();
+ expect(resets.resetDatabases).toHaveBeenCalled();
+ expect(resets.resetInstances).toHaveBeenCalled();
+ expect(resets.resetProjects).toHaveBeenCalled();
+ });
+
+ test("not-logged-in user is redirected to signin with a redirect query", () => {
+ const target = location(run(PROJECT_V1_ROUTE_DASHBOARD, "/projects/p1"));
+ expect(target).toBe("/auth?redirect=%2Fprojects%2Fp1");
+ });
+
+ test("enforces 2FA setup when required", () => {
+ session.isLoggedIn = true;
+ session.hasTwoFa = true;
+ session.requireMfa = true;
+ session.currentUser = { mfaEnabled: false };
+ expect(location(run(PROJECT_V1_ROUTE_DASHBOARD, "/projects/p1"))).toBe(
+ "/auth/2fa-setup"
+ );
+ });
+
+ test("enforces password reset when required", () => {
+ session.isLoggedIn = true;
+ session.requireResetPassword = true;
+ expect(location(run(PROJECT_V1_ROUTE_DASHBOARD, "/projects/p1"))).toBe(
+ "/auth/password-reset"
+ );
+ });
+
+ test("allows an authenticated user on an allowed route", () => {
+ session.isLoggedIn = true;
+ expect(run(PROJECT_V1_ROUTE_DASHBOARD, "/projects/p1")).toBeNull();
+ });
+
+ test("unknown named route falls back to 404", () => {
+ session.isLoggedIn = true;
+ expect(location(run("some.unknown.route", "/whatever"))).toBe("/404");
+ });
+
+ test("unnamed matched route is allowed", () => {
+ session.isLoggedIn = true;
+ expect(run(undefined, "/projects/p1/some-shell")).toBeNull();
+ });
+});
diff --git a/frontend/src/react/router/guard.ts b/frontend/src/react/router/guard.ts
new file mode 100644
index 0000000000..5da3f8b346
--- /dev/null
+++ b/frontend/src/react/router/guard.ts
@@ -0,0 +1,269 @@
+import { redirect } from "react-router-dom";
+import { useAppStore } from "@/react/stores/app";
+import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+import {
+ storageKeyRecentVisit,
+ workspaceCacheScope,
+} from "@/utils/storage-keys";
+import {
+ AUTH_2FA_SETUP_MODULE,
+ AUTH_MFA_MODULE,
+ AUTH_OAUTH_CALLBACK_MODULE,
+ AUTH_OIDC_CALLBACK_MODULE,
+ AUTH_PASSWORD_FORGOT_MODULE,
+ AUTH_PASSWORD_RESET_MODULE,
+ AUTH_PROFILE_SETUP_MODULE,
+ AUTH_SIGNIN_ADMIN_MODULE,
+ AUTH_SIGNIN_MODULE,
+ AUTH_SIGNUP_MODULE,
+ DATABASE_ROUTE_DASHBOARD,
+ ENVIRONMENT_V1_ROUTE_DASHBOARD,
+ INSTANCE_ROUTE_DASHBOARD,
+ OAUTH2_CONSENT_MODULE,
+ PROJECT_V1_ROUTE_DASHBOARD,
+ SETTING_ROUTE,
+ SETUP_MODULE,
+ SQL_EDITOR_HOME_MODULE,
+ WORKSPACE_ROOT_MODULE,
+ WORKSPACE_ROUTE_403,
+ WORKSPACE_ROUTE_404,
+ WORKSPACE_ROUTE_LANDING,
+} from "./handles";
+import { resolvePath } from "./navigation";
+
+const SIGNIN_QUERY_PARAMS = [
+ "idp",
+ "workspace",
+ "email",
+ "token",
+ "invitation",
+] as const;
+
+// Auth/landing route names that don't require an authenticated session.
+// Inlined (rather than importing `@/utils/auth`, which pulls the Vue router).
+export function isAuthRelatedRoute(routeName: string): boolean {
+ return [
+ AUTH_SIGNIN_MODULE,
+ AUTH_SIGNIN_ADMIN_MODULE,
+ AUTH_SIGNUP_MODULE,
+ AUTH_MFA_MODULE,
+ AUTH_PASSWORD_RESET_MODULE,
+ AUTH_PASSWORD_FORGOT_MODULE,
+ AUTH_OAUTH_CALLBACK_MODULE,
+ AUTH_OIDC_CALLBACK_MODULE,
+ ].includes(routeName);
+}
+
+function stripSigninQueryParams(fullPath: string): string {
+ const url = new URL(fullPath, window.location.origin);
+ for (const param of SIGNIN_QUERY_PARAMS) {
+ url.searchParams.delete(param);
+ }
+ return url.pathname + url.search + url.hash;
+}
+
+// Route-name prefixes that an authenticated user may always access.
+const ALLOWED_ROUTE_PATTERNS = [
+ ENVIRONMENT_V1_ROUTE_DASHBOARD,
+ INSTANCE_ROUTE_DASHBOARD,
+ PROJECT_V1_ROUTE_DASHBOARD,
+ DATABASE_ROUTE_DASHBOARD,
+ SETTING_ROUTE,
+ SETUP_MODULE,
+ "workspace",
+ "sql-editor",
+];
+
+// Resolve the redirect target for the bare workspace root ("/"), mirroring the
+// legacy `DummyRootView`. The root path has no page of its own:
+// - EDITOR change-mode workspaces go to the SQL Editor home
+// - otherwise the user's last meaningful visit, if any
+// - falling back to the landing page
+// `loadWorkspaceProfile()` is awaited before the router mounts (see main.ts),
+// so `appFeatures` is populated by the time this runs.
+function resolveRootRedirect(
+ store: ReturnType<typeof useAppStore.getState>
+): string {
+ if (
+ store.appFeatures["bb.feature.database-change-mode"] ===
+ DatabaseChangeMode.EDITOR
+ ) {
+ return resolvePath(SQL_EDITOR_HOME_MODULE);
+ }
+ const lastVisit = readLastVisit(store);
+ if (lastVisit && isMeaningfulVisit(lastVisit)) {
+ return lastVisit;
+ }
+ return resolvePath(WORKSPACE_ROUTE_LANDING);
+}
+
+// Read the most-recent visited path from the per-user recent-visit list in
+// localStorage (same scoped key + JSON format as `useRecentVisit`).
+function readLastVisit(
+ store: ReturnType<typeof useAppStore.getState>
+): string | undefined {
+ try {
+ const key = storageKeyRecentVisit(
+ workspaceCacheScope(
+ store.isSaaSMode(),
+ store.currentUser?.workspace ?? ""
+ ),
+ store.currentUser?.email ?? ""
+ );
+ const raw = localStorage.getItem(key);
+ const list = raw ? JSON.parse(raw) : [];
+ return Array.isArray(list) && list.length > 0 ? list[0] : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+// Ignore root-ish / transient paths so we don't redirect "/" back to itself or
+// to a route that itself redirects (mirrors `DummyRootView`'s ignore list).
+function isMeaningfulVisit(path: string): boolean {
+ return !(
+ path === "" ||
+ path === "/" ||
+ path.startsWith("?") ||
+ path.startsWith("#") ||
+ path.startsWith("/?") ||
+ path.startsWith("/#") ||
+ path.startsWith("/403") ||
+ path.startsWith("/404") ||
+ path.startsWith("/sql-editor")
+ );
+}
+
+/**
+ * Faithful port of the legacy vue-router `beforeEach` guard
+ * (`src/router/index.ts`). Runs as the react-router root-route loader: the
+ * root `.tsx` loader resolves the matched leaf route's `handle.name` (via
+ * `matchRoutes`) and calls this. Returns a `redirect()` Response to navigate
+ * elsewhere, or `null` to allow the navigation. Session state is read from the
+ * app store (the single source of truth).
+ */
+export function rootGuard({
+ name,
+ url,
+}: {
+ name: string | undefined;
+ url: URL;
+}): Response | null {
+ const toName = name ?? "";
+
+ // Error pages can be accessed directly.
+ if (toName === WORKSPACE_ROUTE_403 || toName === WORKSPACE_ROUTE_404) {
+ return null;
+ }
+ // Auth callbacks can be accessed directly.
+ if (
+ toName === AUTH_OAUTH_CALLBACK_MODULE ||
+ toName === AUTH_OIDC_CALLBACK_MODULE
+ ) {
+ return null;
+ }
+ // OAuth2 consent requires login but must not redirect away.
+ if (toName === OAUTH2_CONSENT_MODULE) {
+ return null;
+ }
+
+ const store = useAppStore.getState();
+ const isLoggedIn = store.isLoggedIn();
+
+ // Allow 2FA setup / password reset / profile setup for logged-in users.
+ if (
+ isLoggedIn &&
+ (toName === AUTH_2FA_SETUP_MODULE ||
+ toName === AUTH_PASSWORD_RESET_MODULE ||
+ toName === AUTH_PROFILE_SETUP_MODULE)
+ ) {
+ return null;
+ }
+
+ // If logged in and trying to access auth pages, redirect to the main app.
+ if (
+ isAuthRelatedRoute(toName) &&
+ isLoggedIn &&
+ !store.unauthenticatedOccurred
+ ) {
+ const relayState = url.searchParams.get("relay_state") ?? undefined;
+ const redirectParam = url.searchParams.get("redirect") ?? undefined;
+ let target = "/";
+ // Validate relay_state to prevent open redirect: relative URLs only,
+ // reject protocol-relative (//).
+ if (
+ relayState &&
+ relayState.startsWith("/") &&
+ !relayState.startsWith("//")
+ ) {
+ target = relayState;
+ } else if (redirectParam) {
+ target = redirectParam;
+ }
+ return redirect(target);
+ }
+
+ // Auth pages: reset caches and allow access.
+ if (isAuthRelatedRoute(toName)) {
+ store.resetDatabases();
+ store.resetInstances();
+ store.resetProjects();
+ void import("@/plugins/ai/store").then(({ useConversationStore }) => {
+ useConversationStore.getState().reset();
+ });
+ return null;
+ }
+
+ // Require authentication for all other pages.
+ if (!isLoggedIn) {
+ const query: Record<string, string> = {};
+ // Forward signin-only query params (consumed by the signin page).
+ for (const param of SIGNIN_QUERY_PARAMS) {
+ const value = url.searchParams.get(param);
+ if (value) query[param] = value;
+ }
+ const fullPath = url.pathname + url.search + url.hash;
+ // Set redirect if not root and not already set; strip signin-only params.
+ if (fullPath !== "/" && !url.searchParams.get("redirect")) {
+ query["redirect"] = stripSigninQueryParams(fullPath);
+ }
+ return redirect(resolvePath(AUTH_SIGNIN_MODULE, { query }));
+ }
+
+ // Enforce 2FA setup if required.
+ const profile = store.getWorkspaceProfile();
+ if (
+ store.hasFeature(PlanFeature.FEATURE_TWO_FA) &&
+ profile.requireMfa &&
+ store.currentUser &&
+ !store.currentUser.mfaEnabled &&
+ toName !== AUTH_2FA_SETUP_MODULE
+ ) {
+ return redirect(resolvePath(AUTH_2FA_SETUP_MODULE));
+ }
+
+ // Enforce password reset if required.
+ if (store.requireResetPassword() && toName !== AUTH_PASSWORD_RESET_MODULE) {
+ return redirect(resolvePath(AUTH_PASSWORD_RESET_MODULE));
+ }
+
+ // The bare workspace root ("/") has no page — redirect like DummyRootView.
+ if (toName === WORKSPACE_ROOT_MODULE) {
+ return redirect(resolveRootRedirect(store));
+ }
+
+ // Allow access to main application routes.
+ if (ALLOWED_ROUTE_PATTERNS.some((pattern) => toName.startsWith(pattern))) {
+ return null;
+ }
+
+ // An unnamed matched route (layout / redirect shell) is allowed — react
+ // router only ran this loader because a route matched the URL.
+ if (!toName) {
+ return null;
+ }
+
+ // Fallback: unknown named route → 404.
+ return redirect(resolvePath(WORKSPACE_ROUTE_404));
+}
diff --git a/frontend/src/react/router/handles.ts b/frontend/src/react/router/handles.ts
new file mode 100644
index 0000000000..7b952f9086
--- /dev/null
+++ b/frontend/src/react/router/handles.ts
@@ -0,0 +1,131 @@
+// Route-name constants for the React router — the single source of truth.
+// Fully VUE-FREE and self-contained (no `@/router/**` imports): the legacy
+// vue-router modules are retired, so all values are inlined as literals here.
+
+// --- dashboard/workspaceRoutes (inlined) ---
+export const WORKSPACE_ROOT_MODULE = "workspace.root";
+export const WORKSPACE_ROUTE_LANDING = "workspace.landing";
+export const WORKSPACE_ROUTE_MY_ISSUES = "workspace.my-issues";
+export const WORKSPACE_ROUTE_DATA_EXPORT = "workspace.data-export";
+export const WORKSPACE_ROUTE_USER_PROFILE = "workspace.user-profile";
+export const DATABASE_ROUTE_DASHBOARD = "workspace.database";
+export const INSTANCE_ROUTE_DASHBOARD = "workspace.instance";
+export const PROJECT_V1_ROUTE_DASHBOARD = "workspace.project";
+export const ENVIRONMENT_V1_ROUTE_DASHBOARD = "workspace.environment";
+export const WORKSPACE_ROUTE_SQL_REVIEW = "workspace.sql-review";
+export const WORKSPACE_ROUTE_SQL_REVIEW_CREATE = `${WORKSPACE_ROUTE_SQL_REVIEW}.create`;
+export const WORKSPACE_ROUTE_SQL_REVIEW_DETAIL = `${WORKSPACE_ROUTE_SQL_REVIEW}.detail`;
+export const WORKSPACE_ROUTE_RISK_ASSESSMENT = "workspace.risk-assessment";
+export const WORKSPACE_ROUTE_CUSTOM_APPROVAL = "workspace.custom-approval";
+export const WORKSPACE_ROUTE_GLOBAL_MASKING = "workspace.global-masking";
+export const WORKSPACE_ROUTE_SEMANTIC_TYPES = "workspace.semantic-types";
+export const WORKSPACE_ROUTE_DATA_CLASSIFICATION =
+ "workspace.data-classification";
+export const WORKSPACE_ROUTE_AUDIT_LOG = "workspace.audit-log";
+export const WORKSPACE_ROUTE_USERS = "workspace.users";
+export const WORKSPACE_ROUTE_SERVICE_ACCOUNTS = "workspace.service-accounts";
+export const WORKSPACE_ROUTE_WORKLOAD_IDENTITIES =
+ "workspace.workload-identities";
+export const WORKSPACE_ROUTE_MEMBERS = "workspace.members";
+export const WORKSPACE_ROUTE_GROUPS = "workspace.groups";
+export const WORKSPACE_ROUTE_ROLES = "workspace.roles";
+export const WORKSPACE_ROUTE_IDENTITY_PROVIDERS =
+ "workspace.identity-providers";
+export const WORKSPACE_ROUTE_IDENTITY_PROVIDER_DETAIL = `${WORKSPACE_ROUTE_IDENTITY_PROVIDERS}.detail`;
+export const WORKSPACE_ROUTE_INTEGRATION = "workspace.integration";
+export const WORKSPACE_ROUTE_IM = `${WORKSPACE_ROUTE_INTEGRATION}.im`;
+export const WORKSPACE_ROUTE_MCP = `${WORKSPACE_ROUTE_INTEGRATION}.mcp`;
+export const WORKSPACE_ROUTE_403 = "error.403";
+export const WORKSPACE_ROUTE_404 = "error.404";
+
+// --- auth.ts ---
+export const AUTH_SIGNIN_MODULE = "auth.signin";
+export const AUTH_SIGNIN_ADMIN_MODULE = "auth.signin.admin";
+export const AUTH_SIGNUP_MODULE = "auth.signup";
+export const AUTH_MFA_MODULE = "auth.mfa";
+export const AUTH_PASSWORD_RESET_MODULE = "auth.password.reset";
+export const AUTH_PASSWORD_FORGOT_MODULE = "auth.password.forgot";
+export const AUTH_OAUTH_CALLBACK_MODULE = "auth.oauth.callback";
+export const AUTH_OIDC_CALLBACK_MODULE = "auth.oidc.callback";
+export const AUTH_PROFILE_SETUP_MODULE = "auth.profile.setup";
+export const AUTH_2FA_SETUP_MODULE = "auth.2fa.setup";
+export const OAUTH2_CONSENT_MODULE = "oauth2.consent";
+
+// --- setup.ts ---
+export const SETUP_MODULE = "setup";
+
+// --- sqlEditor.ts ---
+export const SQL_EDITOR_HOME_MODULE = "sql-editor.home";
+export const SQL_EDITOR_PROJECT_MODULE = "sql-editor.project";
+export const SQL_EDITOR_INSTANCE_MODULE = "sql-editor.instance";
+export const SQL_EDITOR_DATABASE_MODULE = "sql-editor.database";
+export const SQL_EDITOR_WORKSHEET_MODULE = "sql-editor.worksheet";
+
+// --- dashboard/workspaceSetting.ts ---
+export const SETTING_ROUTE = "setting";
+export const SETTING_ROUTE_WORKSPACE = `${SETTING_ROUTE}.workspace`;
+export const SETTING_ROUTE_PROFILE = `${SETTING_ROUTE}.profile`;
+export const SETTING_ROUTE_PROFILE_TWO_FACTOR = `${SETTING_ROUTE_PROFILE}.two-factor`;
+export const SETTING_ROUTE_WORKSPACE_GENERAL = `${SETTING_ROUTE_WORKSPACE}.general`;
+export const SETTING_ROUTE_WORKSPACE_SUBSCRIPTION = `${SETTING_ROUTE_WORKSPACE}.subscription`;
+
+// --- dashboard/instance.ts ---
+export const INSTANCE_ROUTE_CREATE = `${INSTANCE_ROUTE_DASHBOARD}.create`;
+export const INSTANCE_ROUTE_DETAIL = `${INSTANCE_ROUTE_DASHBOARD}.detail`;
+export const INSTANCE_ROUTE_DATABASE_DETAIL = `${INSTANCE_ROUTE_DASHBOARD}.database.detail`;
+
+// --- dashboard/environmentV1.ts ---
+export const ENVIRONMENT_V1_ROUTE_DETAIL = `${ENVIRONMENT_V1_ROUTE_DASHBOARD}.detail`;
+
+// --- dashboard/projectV1.ts ---
+export const PROJECT_V1_ROUTE_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.detail`;
+export const PROJECT_V1_ROUTE_DATABASES = `${PROJECT_V1_ROUTE_DASHBOARD}.database`;
+export const PROJECT_V1_ROUTE_MASKING_EXEMPTION = `${PROJECT_V1_ROUTE_DASHBOARD}.masking-exemption`;
+export const PROJECT_V1_ROUTE_MASKING_EXEMPTION_CREATE = `${PROJECT_V1_ROUTE_DASHBOARD}.masking-exemption.create`;
+export const PROJECT_V1_ROUTE_DATABASE_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.database.detail`;
+export const PROJECT_V1_ROUTE_DATABASE_CHANGELOG_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.database.changelog.detail`;
+export const PROJECT_V1_ROUTE_DATABASE_REVISION_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.database.revision.detail`;
+export const PROJECT_V1_ROUTE_DATABASE_GROUPS = `${PROJECT_V1_ROUTE_DASHBOARD}.database-group`;
+export const PROJECT_V1_ROUTE_DATABASE_GROUPS_CREATE = `${PROJECT_V1_ROUTE_DASHBOARD}.database-group.create`;
+export const PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.database-group.detail`;
+export const PROJECT_V1_ROUTE_ISSUES = `${PROJECT_V1_ROUTE_DASHBOARD}.issue`;
+export const PROJECT_V1_ROUTE_ISSUE_DETAIL = `${PROJECT_V1_ROUTE_ISSUES}.detail`;
+export const PROJECT_V1_ROUTE_PLANS = `${PROJECT_V1_ROUTE_DASHBOARD}.plan`;
+export const PROJECT_V1_ROUTE_PLAN_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.plan.detail`;
+export const PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS = `${PROJECT_V1_ROUTE_PLAN_DETAIL}.specs`;
+export const PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL = `${PROJECT_V1_ROUTE_PLAN_DETAIL}.spec.detail`;
+export const PROJECT_V1_ROUTE_SYNC_SCHEMA = `${PROJECT_V1_ROUTE_DASHBOARD}.sync-schema`;
+export const PROJECT_V1_ROUTE_AUDIT_LOGS = `${PROJECT_V1_ROUTE_DASHBOARD}.audit-logs`;
+export const PROJECT_V1_ROUTE_WEBHOOKS = `${PROJECT_V1_ROUTE_DASHBOARD}.webhook`;
+export const PROJECT_V1_ROUTE_WEBHOOK_CREATE = `${PROJECT_V1_ROUTE_DASHBOARD}.webhook.create`;
+export const PROJECT_V1_ROUTE_WEBHOOK_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.webhook.detail`;
+export const PROJECT_V1_ROUTE_ACCESS_GRANTS = `${PROJECT_V1_ROUTE_DASHBOARD}.access-grants`;
+export const PROJECT_V1_ROUTE_MEMBERS = `${PROJECT_V1_ROUTE_DASHBOARD}.members`;
+export const PROJECT_V1_ROUTE_SERVICE_ACCOUNTS = `${PROJECT_V1_ROUTE_DASHBOARD}.service-accounts`;
+export const PROJECT_V1_ROUTE_WORKLOAD_IDENTITIES = `${PROJECT_V1_ROUTE_DASHBOARD}.workload-identities`;
+export const PROJECT_V1_ROUTE_SETTINGS = `${PROJECT_V1_ROUTE_DASHBOARD}.settings`;
+export const PROJECT_V1_ROUTE_DATA_EXPORT = `${PROJECT_V1_ROUTE_DASHBOARD}.data-export`;
+export const PROJECT_V1_ROUTE_RELEASES = `${PROJECT_V1_ROUTE_DASHBOARD}.release`;
+export const PROJECT_V1_ROUTE_RELEASE_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.release.detail`;
+export const PROJECT_V1_ROUTE_ROLLOUTS = `${PROJECT_V1_ROUTE_DASHBOARD}.rollouts`;
+export const PROJECT_V1_ROUTE_PLAN_ROLLOUT = `${PROJECT_V1_ROUTE_ROLLOUTS}.rollout`;
+export const PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE = `${PROJECT_V1_ROUTE_PLAN_ROLLOUT}.stage`;
+export const PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK = `${PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE}.task`;
+export const PROJECT_V1_ROUTE_GITOPS = `${PROJECT_V1_ROUTE_DASHBOARD}.gitops`;
+
+// --- dashboard/projectV1RouteHelpers.ts ---
+export const PLAN_DETAIL_PHASE_CHANGES = "changes";
+export const PLAN_DETAIL_PHASE_REVIEW = "review";
+export const PLAN_DETAIL_PHASE_DEPLOY = "deploy";
+
+// Normalize a query value (string | string[] | undefined) to a single string.
+// Ported vue-free from projectV1RouteHelpers.getRouteQueryString.
+export function getRouteQueryString(
+ value?: string | string[] | undefined
+): string | undefined {
+ if (typeof value === "string") return value;
+ if (Array.isArray(value)) {
+ return typeof value[0] === "string" ? value[0] : undefined;
+ }
+ return undefined;
+}
diff --git a/frontend/src/react/router/index.ts b/frontend/src/react/router/index.ts
index e0daee0a02..16279ae955 100644
--- a/frontend/src/react/router/index.ts
+++ b/frontend/src/react/router/index.ts
@@ -1,57 +1,33 @@
-import { useSyncExternalStore } from "react";
-import type { RouteLocationRaw } from "vue-router";
-import { router } from "@/router";
-import { AUTH_SIGNIN_MODULE } from "@/router/auth";
import {
- PROJECT_V1_ROUTE_DATABASES,
- PROJECT_V1_ROUTE_DATABASE_DETAIL,
- PROJECT_V1_ROUTE_DETAIL,
-} from "@/router/dashboard/projectV1";
-import {
- DATABASE_ROUTE_DASHBOARD,
- ENVIRONMENT_V1_ROUTE_DASHBOARD,
- INSTANCE_ROUTE_DASHBOARD,
- PROJECT_V1_ROUTE_DASHBOARD,
- WORKSPACE_ROUTE_AUDIT_LOG,
- WORKSPACE_ROUTE_CUSTOM_APPROVAL,
- WORKSPACE_ROUTE_DATA_CLASSIFICATION,
- WORKSPACE_ROUTE_GLOBAL_MASKING,
- WORKSPACE_ROUTE_GROUPS,
- WORKSPACE_ROUTE_IDENTITY_PROVIDERS,
- WORKSPACE_ROUTE_IM,
- WORKSPACE_ROUTE_LANDING,
- WORKSPACE_ROUTE_MCP,
- WORKSPACE_ROUTE_MEMBERS,
- WORKSPACE_ROUTE_MY_ISSUES,
- WORKSPACE_ROUTE_RISK_ASSESSMENT,
- WORKSPACE_ROUTE_ROLES,
- WORKSPACE_ROUTE_SEMANTIC_TYPES,
- WORKSPACE_ROUTE_SERVICE_ACCOUNTS,
- WORKSPACE_ROUTE_SQL_REVIEW,
- WORKSPACE_ROUTE_USER_PROFILE,
- WORKSPACE_ROUTE_USERS,
- WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,
-} from "@/router/dashboard/workspaceRoutes";
-import {
- SETTING_ROUTE_PROFILE,
- SETTING_ROUTE_WORKSPACE_GENERAL,
- SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,
-} from "@/router/dashboard/workspaceSetting";
-import {
- SQL_EDITOR_DATABASE_MODULE,
- SQL_EDITOR_HOME_MODULE,
- SQL_EDITOR_PROJECT_MODULE,
-} from "@/router/sqlEditor";
+ useLocation,
+ useNavigate as useReactRouterNavigate,
+ useMatches,
+ useParams,
+} from "react-router-dom";
import type { Permission } from "@/types";
+import type { RouterLocation, RouterMatch } from "./navigation";
+import {
+ buildSearchString,
+ getAppRouterState,
+ getRegisteredRoutes,
+ isAppRouterReady,
+ navigateByName,
+ navigateToPath,
+ resolvePath,
+ routerGo,
+ subscribeRoute,
+} from "./navigation";
+// Re-export the route-name constants from the vue-free handles module so React
+// consumers keep importing them from `@/react/router`.
export {
AUTH_SIGNIN_MODULE,
DATABASE_ROUTE_DASHBOARD,
ENVIRONMENT_V1_ROUTE_DASHBOARD,
INSTANCE_ROUTE_DASHBOARD,
PROJECT_V1_ROUTE_DASHBOARD,
- PROJECT_V1_ROUTE_DATABASES,
PROJECT_V1_ROUTE_DATABASE_DETAIL,
+ PROJECT_V1_ROUTE_DATABASES,
PROJECT_V1_ROUTE_DETAIL,
SETTING_ROUTE_PROFILE,
SETTING_ROUTE_WORKSPACE_GENERAL,
@@ -78,71 +54,172 @@ export {
WORKSPACE_ROUTE_USER_PROFILE,
WORKSPACE_ROUTE_USERS,
WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,
-};
+} from "./handles";
export type ReactRoute = {
name?: string;
fullPath: string;
+ hash: string;
params: Record<string, string | string[] | undefined>;
query: Record<string, unknown>;
requiredPermissions: Permission[];
title?: string;
overrideDocumentTitle: boolean;
+ // Mirrors vue-router `route.meta` — carries the per-route handle so legacy
+ // `currentRoute.value.meta.*` reads keep working.
+ meta: Record<string, unknown>;
};
-export type ReactResolvedRoute = {
- href: string;
- fullPath: string;
-};
+// vue-router-style navigation target (kept for source compatibility with the
+// ~existing consumers): a raw path string, or `{ name, params, query }`.
+export type RouteTarget =
+ | string
+ | {
+ name?: string;
+ path?: string;
+ // Pre-resolved full path (e.g. the result of `router.resolve(...)` or a
+ // spread `currentRoute.value`); used when no `name`/`path` is given.
+ fullPath?: string;
+ params?: Record<string, string | string[] | undefined>;
+ query?: Record<string, unknown>;
+ hash?: string;
+ };
-let cachedRoute: ReactRoute | undefined;
+export type ReactResolvedRoute = { href: string; fullPath: string };
+
+// Per-route metadata carried on `handle` (mirrors the legacy vue-router
+// `meta`). Ported route definitions attach these alongside `name`.
+type RouteHandle = {
+ name?: string;
+ requiredPermissionList?: () => Permission[];
+ title?: (route: ReactRoute) => string | undefined;
+ overrideDocumentTitle?: boolean;
+};
function dedupePermissions(permissions: Permission[]): Permission[] {
return [...new Set(permissions)];
}
-function snapshotRoute(): ReactRoute {
- const route = router.currentRoute.value;
- if (cachedRoute?.fullPath === route.fullPath) {
- return cachedRoute;
+function resolveTarget(to: RouteTarget): string {
+ if (typeof to === "string") return to;
+ const hash = to.hash
+ ? to.hash.startsWith("#")
+ ? to.hash
+ : `#${to.hash}`
+ : "";
+ if (to.name) {
+ return `${resolvePath(to.name, { params: to.params, query: to.query })}${hash}`;
+ }
+ if (to.path) {
+ const search = to.query ? buildSearchString(to.query) : "";
+ return `${search ? `${to.path}?${search}` : to.path}${hash}`;
}
- cachedRoute = {
- name: route.name?.toString(),
- fullPath: route.fullPath,
- params: route.params as Record<string, string | string[] | undefined>,
- query: route.query as Record<string, unknown>,
+ // Pre-resolved full path (already carries its own query/hash).
+ if (to.fullPath) {
+ return to.fullPath;
+ }
+ // No name/path/fullPath: a query (and/or hash) update against the *current*
+ // location. vue-router's `router.replace({ query })` keeps the current path;
+ // returning "/" here instead would bounce the user to the workspace root
+ // (and its redirect), e.g. the DatabasesPage URL-sync landing on /issues.
+ const search = to.query ? buildSearchString(to.query) : "";
+ const path = window.location.pathname;
+ return `${search ? `${path}?${search}` : path}${hash}`;
+}
+
+// Shared builder for both the `useCurrentRoute` hook and the non-hook
+// `router.currentRoute.value` snapshot, so the two stay shape-identical.
+// Exported as `buildReactRoute` for the app root's leave-guard blocker, which
+// matches `nextLocation` against the route table (matchRoutes lives in the
+// `.tsx` layer — this module must not import the route table).
+export function buildReactRoute(
+ location: Pick<RouterLocation, "pathname" | "search" | "hash">,
+ matches: ReadonlyArray<{ handle?: unknown }>,
+ params: Record<string, string | string[] | undefined>
+): ReactRoute {
+ return assembleRoute(location, matches, params);
+}
+
+function assembleRoute(
+ location: Pick<RouterLocation, "pathname" | "search" | "hash">,
+ matches: ReadonlyArray<{ handle?: unknown }>,
+ params: Record<string, string | string[] | undefined>
+): ReactRoute {
+ const leafHandle = matches.at(-1)?.handle as RouteHandle | undefined;
+ const route: ReactRoute = {
+ name: leafHandle?.name,
+ fullPath: `${location.pathname}${location.search}${location.hash}`,
+ hash: location.hash,
+ params,
+ query: Object.fromEntries(new URLSearchParams(location.search)),
requiredPermissions: dedupePermissions(
- route.matched.flatMap(
- (record) =>
- (record.meta.requiredPermissionList?.() ?? []) as Permission[]
+ matches.flatMap(
+ (m) =>
+ (m.handle as RouteHandle | undefined)?.requiredPermissionList?.() ??
+ []
)
),
- title: route.meta.title?.(route),
- overrideDocumentTitle: route.meta.overrideDocumentTitle ?? false,
+ overrideDocumentTitle: leafHandle?.overrideDocumentTitle ?? false,
+ meta: (leafHandle as Record<string, unknown> | undefined) ?? {},
};
- return cachedRoute;
+ route.title = leafHandle?.title?.(route);
+ return route;
}
-function subscribeRoute(onStoreChange: () => void) {
- return router.afterEach(() => onStoreChange());
+/** React-router-backed current route, shaped like the legacy bridge. */
+export function useCurrentRoute(): ReactRoute {
+ const location = useLocation();
+ const params = useParams();
+ const matches = useMatches();
+ return assembleRoute(
+ location,
+ matches,
+ params as Record<string, string | string[] | undefined>
+ );
}
-export function useCurrentRoute(): ReactRoute {
- return useSyncExternalStore(subscribeRoute, snapshotRoute, snapshotRoute);
+// Non-hook snapshot of the current route, read from the registered data router
+// (backs `router.currentRoute.value`).
+//
+// Memoized so it returns a referentially STABLE object between actual route
+// changes. `router.currentRoute.value` backs the `useReactiveRoute`
+// `useSyncExternalStore` snapshot (and ~110 imperative call sites); a fresh
+// object on every read makes external stores re-render forever ("The result of
+// getSnapshot should be cached to avoid an infinite loop"). `fullPath` + `name`
+// fully identify the route — params, query and matches all derive from the URL.
+let currentRouteCache: ReactRoute | undefined;
+function currentRouteSnapshot(): ReactRoute {
+ const state = getAppRouterState();
+ const location = state?.location ?? { pathname: "/", search: "", hash: "" };
+ const matches: RouterMatch[] = state?.matches ?? [];
+ const leafParams = (matches.at(-1)?.params ?? {}) as Record<
+ string,
+ string | string[] | undefined
+ >;
+ const next = assembleRoute(location, matches, leafParams);
+ if (
+ !currentRouteCache ||
+ currentRouteCache.fullPath !== next.fullPath ||
+ currentRouteCache.name !== next.name
+ ) {
+ currentRouteCache = next;
+ }
+ return currentRouteCache;
}
-export function resolveRoute(to: RouteLocationRaw): ReactResolvedRoute {
- const route = router.resolve(to);
- return {
- href: route.href,
- fullPath: route.fullPath,
- };
+export function resolveRoute(to: RouteTarget): ReactResolvedRoute {
+ const fullPath = resolveTarget(to);
+ return { href: fullPath, fullPath };
}
export function useNavigate() {
+ // Hook call keeps React's router context wired; navigation itself goes
+ // through the resolver so by-name targets keep working.
+ useReactRouterNavigate();
return {
- push: (to: RouteLocationRaw) => router.push(to),
- replace: (to: RouteLocationRaw) => router.replace(to),
+ push: (to: RouteTarget) => navigateToPath(resolveTarget(to)),
+ replace: (to: RouteTarget) =>
+ navigateToPath(resolveTarget(to), { replace: true }),
resolve: resolveRoute,
};
}
@@ -150,3 +227,80 @@ export function useNavigate() {
export function isSqlEditorRouteName(name: string | undefined): boolean {
return name?.startsWith("sql-editor") ?? false;
}
+
+// --- vue-router-instance drop-in --------------------------------------------
+// A module-level object mirroring the imperative surface of the legacy
+// vue-router instance (`import { router } from "@/router"`), backed by the
+// react-router data router. Lets the ~110 imperative call sites keep their
+// usage unchanged through teardown — only the import path moves to
+// `@/react/router`.
+
+// vue-router `next()` callback: no-arg / `RouteTarget` proceeds, `false`
+// cancels.
+type GuardNext = (target?: boolean | RouteTarget) => void;
+type BeforeEachGuard = (
+ to: ReactRoute,
+ from: ReactRoute,
+ next: GuardNext
+) => void;
+
+const beforeEachGuards = new Set<BeforeEachGuard>();
+
+// Runs every registered `beforeEach` guard against a pending navigation and
+// reports whether it should be BLOCKED (a guard called `next(false)`). The app
+// root consults this from a single `useBlocker`, reproducing vue-router's
+// global guard semantics. Guards that redirect (`next(target)`) are treated as
+// "proceed" here — the existing leave guards only ever proceed or cancel.
+export function runBeforeEachGuards(to: ReactRoute, from: ReactRoute): boolean {
+ for (const guard of beforeEachGuards) {
+ let blocked = false;
+ guard(to, from, (target) => {
+ if (target === false) blocked = true;
+ });
+ if (blocked) return true;
+ }
+ return false;
+}
+
+export const router = {
+ push: (to: RouteTarget) => navigateToPath(resolveTarget(to)),
+ replace: (to: RouteTarget) =>
+ navigateToPath(resolveTarget(to), { replace: true }),
+ resolve: (to: RouteTarget): ReactResolvedRoute => resolveRoute(to),
+ back: () => routerGo(-1),
+ go: (delta: number) => routerGo(delta),
+ isReady: () => isAppRouterReady(),
+ // vue-router exposed `currentRoute` as a Ref; consumers read `.value`.
+ get currentRoute(): { value: ReactRoute } {
+ return {
+ get value() {
+ return currentRouteSnapshot();
+ },
+ };
+ },
+ beforeEach(guard: BeforeEachGuard): () => void {
+ beforeEachGuards.add(guard);
+ return () => {
+ beforeEachGuards.delete(guard);
+ };
+ },
+ afterEach(hook: () => void): () => void {
+ return subscribeRoute(hook);
+ },
+ // Named routes for the agent's route-map listing; shaped like the vue-router
+ // records the agent reads (`path` / `name` / `children`).
+ getRoutes(): { path: string; name?: string; children: unknown[] }[] {
+ return getRegisteredRoutes().map((r) => ({
+ path: r.path,
+ name: r.name,
+ children: [],
+ }));
+ },
+};
+
+// The drop-in router's type, for code that takes the router as a parameter
+// (e.g. the agent tool factories) instead of importing it directly.
+export type AppRouterInstance = typeof router;
+
+// Re-exported so non-hook callers can navigate by name.
+export { navigateByName };
diff --git a/frontend/src/react/router/layoutPlaceholders.tsx b/frontend/src/react/router/layoutPlaceholders.tsx
new file mode 100644
index 0000000000..2887361b4f
--- /dev/null
+++ b/frontend/src/react/router/layoutPlaceholders.tsx
@@ -0,0 +1,15 @@
+// Route-shell placeholder for the react-router route table.
+//
+// The Vue route-shell components (`SettingRouteShell`, `ProjectRouteShell`,
+// `InstanceRouteShell`, `IssuesRouteShell`) render an empty teleport target for
+// the Vue ReactRouteShellBridge and require props supplied by that bridge; they
+// do not render an `<Outlet/>` and so cannot host react-router children yet.
+// Each shell-parent route uses this placeholder so its child leaf routes still
+// render. A later phase replaces these with `<Outlet/>`-aware React shells that
+// own breadcrumbs / permission guards / document title.
+//
+// (The Splash / Body / Dashboard layout placeholders that previously lived here
+// have been replaced by the real layouts in `@/react/app/layouts/*`.)
+import { Outlet } from "react-router-dom";
+
+export const RouteShellOutletPlaceholder = () => <Outlet />;
diff --git a/frontend/src/react/router/lazyPage.ts b/frontend/src/react/router/lazyPage.ts
new file mode 100644
index 0000000000..af8ebe5894
--- /dev/null
+++ b/frontend/src/react/router/lazyPage.ts
@@ -0,0 +1,42 @@
+import { type ComponentType, createElement, useMemo } from "react";
+import { useLocation, useMatches, useParams } from "react-router-dom";
+
+// Adapter for react-router's `lazy` route field.
+//
+// Page components were authored for the Vue layer, which injected route data as
+// props. react-router renders a route's `Component` with no props, so we wrap
+// the resolved page in a thin component that forwards the current route data:
+// - `useParams()` → the `:param` props (projectId, instanceId, databaseName,
+// issueId, …). Without these the project issue dashboard built a
+// `project:<projectId>` scope from `undefined` and crashed.
+// - `routeName` → the matched leaf route's `handle.name`, and `routeQuery` →
+// the parsed query string. Pages like the plan detail decide which phase /
+// stage / task / spec to show from these (mirroring the Vue `route.name` /
+// `route.query`); without injection that selection silently never fires.
+// Pages that don't declare these props simply ignore the extras.
+export const lazyPage =
+ <T extends Record<string, unknown>>(
+ loader: () => Promise<T>,
+ pick: (m: T) => unknown
+ ) =>
+ async (): Promise<{ Component: ComponentType }> => {
+ const m = await loader();
+ const Page = pick(m) as ComponentType<Record<string, unknown>>;
+ const WithRouteProps = () => {
+ const params = useParams();
+ const matches = useMatches();
+ const { search } = useLocation();
+ const routeName = (
+ matches.at(-1)?.handle as { name?: string } | undefined
+ )?.name;
+ // Memoize on the raw search string so the query object keeps a stable
+ // identity across re-renders that don't change the query (a fresh object
+ // every render would needlessly re-run query-driven effects downstream).
+ const routeQuery = useMemo(
+ () => Object.fromEntries(new URLSearchParams(search)),
+ [search]
+ );
+ return createElement(Page, { ...params, routeName, routeQuery });
+ };
+ return { Component: WithRouteProps };
+ };
diff --git a/frontend/src/react/router/navigation.test.ts b/frontend/src/react/router/navigation.test.ts
new file mode 100644
index 0000000000..f8dbc66b9c
--- /dev/null
+++ b/frontend/src/react/router/navigation.test.ts
@@ -0,0 +1,66 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import {
+ navigateByName,
+ navigateToPath,
+ resolvePath,
+ setAppRouter,
+ setRouteNameIndex,
+} from "./navigation";
+
+beforeEach(() => {
+ setRouteNameIndex(
+ new Map<string, string>([
+ ["auth.signin", "/auth"],
+ ["project.detail", "/projects/:projectId"],
+ ])
+ );
+});
+
+describe("navigation resolvePath", () => {
+ test("resolves a known route name to its path", () => {
+ expect(resolvePath("auth.signin")).toBe("/auth");
+ });
+
+ test("fills :params", () => {
+ expect(resolvePath("project.detail", { params: { projectId: "p1" } })).toBe(
+ "/projects/p1"
+ );
+ });
+
+ test("appends a query string", () => {
+ expect(resolvePath("auth.signin", { query: { redirect: "/x" } })).toBe(
+ "/auth?redirect=%2Fx"
+ );
+ });
+
+ test("drops undefined query values", () => {
+ expect(resolvePath("auth.signin", { query: { redirect: undefined } })).toBe(
+ "/auth"
+ );
+ });
+
+ test("unknown name falls back to / (never throws mid-guard)", () => {
+ expect(resolvePath("does.not.exist")).toBe("/");
+ });
+});
+
+describe("navigation dispatch", () => {
+ test("navigateByName resolves then calls the registered router", () => {
+ const navigate = vi.fn();
+ setAppRouter({ navigate });
+ navigateByName("auth.signin", {
+ query: { redirect: "/x" },
+ replace: true,
+ });
+ expect(navigate).toHaveBeenCalledWith("/auth?redirect=%2Fx", {
+ replace: true,
+ });
+ });
+
+ test("navigateToPath passes the raw path through", () => {
+ const navigate = vi.fn();
+ setAppRouter({ navigate });
+ navigateToPath("/raw", { replace: false });
+ expect(navigate).toHaveBeenCalledWith("/raw", { replace: false });
+ });
+});
diff --git a/frontend/src/react/router/navigation.ts b/frontend/src/react/router/navigation.ts
new file mode 100644
index 0000000000..1d8801a4ca
--- /dev/null
+++ b/frontend/src/react/router/navigation.ts
@@ -0,0 +1,159 @@
+// Structural type for the createBrowserRouter instance (avoids depending on
+// @remix-run/router's exported name across react-router versions).
+export type RouterMatch = {
+ handle?: unknown;
+ params: Record<string, string | undefined>;
+};
+export type RouterLocation = { pathname: string; search: string; hash: string };
+export type RouterState = {
+ location: RouterLocation;
+ matches: RouterMatch[];
+ initialized: boolean;
+};
+type AppRouterLike = {
+ // Overloaded to match the data router (`navigate(delta)` /
+ // `navigate(to, opts)`), so the concrete instance is assignable.
+ navigate: {
+ (delta: number): Promise<void>;
+ (to: string, opts?: { replace?: boolean }): Promise<void>;
+ };
+ subscribe?: (fn: (state: RouterState) => void) => () => void;
+ state?: RouterState;
+};
+
+// vue-router navigated by route *name*; react-router navigates by *path*. To
+// keep the ported guard + auth lifecycle a faithful translation (they redirect
+// by name), we resolve names to concrete paths via a `name -> path pattern`
+// index. The index is BUILT from the route table on the React (.tsx) side and
+// REGISTERED here (`setRouteNameIndex`) — this module stays a pure `.ts` so the
+// app store (also `.ts`, checked by vue-tsc) can import it without pulling the
+// `.tsx` route/page graph across the type-check project boundary.
+
+// vue-router accepted strings, numbers and arrays as query/param values.
+type NavParams = Record<string, string | string[] | undefined>;
+type NavQuery = Record<string, unknown>;
+
+let nameIndex = new Map<string, string>();
+
+export function setRouteNameIndex(index: Map<string, string>): void {
+ nameIndex = index;
+}
+
+// All registered named routes as `{ name, path }` pairs (backs the agent's
+// `router.getRoutes()` route-map listing).
+export function getRegisteredRoutes(): { name: string; path: string }[] {
+ return [...nameIndex.entries()].map(([name, path]) => ({ name, path }));
+}
+
+// Coerce a vue-router-style query (values may be strings, numbers, arrays,
+// null/undefined) into a URL search string.
+export function buildSearchString(query: NavQuery): string {
+ const search = new URLSearchParams();
+ for (const [key, value] of Object.entries(query)) {
+ if (value === undefined || value === null) continue;
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ if (item !== undefined && item !== null)
+ search.append(key, String(item));
+ }
+ } else {
+ search.set(key, String(value));
+ }
+ }
+ return search.toString();
+}
+
+// Fill `:param` placeholders and append a query string.
+export function resolvePath(
+ name: string,
+ options: { params?: NavParams; query?: NavQuery } = {}
+): string {
+ const pattern = nameIndex.get(name);
+ if (!pattern) {
+ // Unknown name → root, so a misconfigured redirect can't throw mid-guard.
+ console.warn(`resolvePath: no route registered for name "${name}"`);
+ return "/";
+ }
+ let path = pattern;
+ if (options.params) {
+ for (const [key, value] of Object.entries(options.params)) {
+ if (value === undefined) continue;
+ const single = Array.isArray(value) ? (value[0] ?? "") : value;
+ path = path.replace(`:${key}`, encodeURIComponent(single));
+ }
+ }
+ if (options.query) {
+ const qs = buildSearchString(options.query);
+ if (qs) path = `${path}?${qs}`;
+ }
+ return path;
+}
+
+// The createBrowserRouter instance, registered by the app root in Phase 4 so
+// non-component code (the auth slice) can navigate without importing the root
+// (which would cycle through the route lazies / app store).
+let appRouter: AppRouterLike | undefined;
+
+export function setAppRouter(router: AppRouterLike): void {
+ appRouter = router;
+}
+
+// Navigate by route name (mirrors vue-router `router.push({ name, query })`).
+export function navigateByName(
+ name: string,
+ options: {
+ params?: NavParams;
+ query?: NavQuery;
+ replace?: boolean;
+ } = {}
+): Promise<void> {
+ const path = resolvePath(name, options);
+ return Promise.resolve(
+ appRouter?.navigate(path, { replace: options.replace })
+ );
+}
+
+// Navigate to a raw path (mirrors `router.push(path)` / `router.replace(path)`).
+export function navigateToPath(
+ path: string,
+ options: { replace?: boolean } = {}
+): Promise<void> {
+ return Promise.resolve(
+ appRouter?.navigate(path, { replace: options.replace })
+ );
+}
+
+// Current data-router state (location + matches), for non-hook snapshots used
+// by the `router.currentRoute.value` drop-in.
+export function getAppRouterState(): RouterState | undefined {
+ return appRouter?.state;
+}
+
+// Subscribe to route changes (mirrors vue-router `router.afterEach`); returns
+// an unregister fn.
+export function subscribeRoute(onChange: () => void): () => void {
+ if (!appRouter?.subscribe) return () => {};
+ return appRouter.subscribe(() => onChange());
+}
+
+// History delta navigation (mirrors `router.back()` / `router.go(n)`).
+export function routerGo(delta: number): void {
+ appRouter?.navigate(delta);
+}
+
+// Resolves once the data router has completed its initial load (mirrors
+// vue-router `router.isReady()`).
+export function isAppRouterReady(): Promise<void> {
+ if (!appRouter || appRouter.state?.initialized !== false) {
+ return Promise.resolve();
+ }
+ return new Promise((resolve) => {
+ const unsubscribe = appRouter?.subscribe?.((state) => {
+ if (state.initialized) {
+ unsubscribe?.();
+ resolve();
+ }
+ });
+ if (!unsubscribe) resolve();
+ });
+}
diff --git a/frontend/src/react/router/routeHelpers.ts b/frontend/src/react/router/routeHelpers.ts
new file mode 100644
index 0000000000..ec48e074e8
--- /dev/null
+++ b/frontend/src/react/router/routeHelpers.ts
@@ -0,0 +1,98 @@
+import type { RouteTarget } from "@/react/router";
+import {
+ PLAN_DETAIL_PHASE_DEPLOY,
+ PROJECT_V1_ROUTE_PLAN_DETAIL,
+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
+} from "@/react/router/handles";
+import { extractPlanUID } from "@/utils/v1/issue/plan";
+import {
+ extractPlanUIDFromRolloutName,
+ extractStageNameFromTaskName,
+ extractStageUID,
+ extractTaskUID,
+} from "@/utils/v1/issue/rollout";
+import { extractProjectResourceName } from "@/utils/v1/project";
+
+// Route-target builders ported vue-free from
+// `@/router/dashboard/projectV1RouteHelpers`. Return the structural
+// `RouteTarget` ({ name, params, query }) consumed by the React navigation
+// shim's push/replace/resolve.
+
+type BuildPlanDeployRouteParams = {
+ projectId: string;
+ planId: string;
+ stageId?: string;
+ taskId?: string;
+};
+
+export const buildPlanDeployRoute = ({
+ projectId,
+ planId,
+ stageId,
+ taskId,
+}: BuildPlanDeployRouteParams): RouteTarget => ({
+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,
+ params: { projectId, planId },
+ query: {
+ phase: PLAN_DETAIL_PHASE_DEPLOY,
+ ...(stageId ? { stageId } : {}),
+ ...(taskId ? { taskId } : {}),
+ },
+});
+
+export const buildSpecDetailRouteForCurrentPage = (
+ currentRoute: {
+ params?: Record<string, string | string[] | undefined>;
+ query?: Record<string, unknown>;
+ },
+ specId: string
+): RouteTarget => ({
+ name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
+ params: {
+ ...(Object.fromEntries(
+ Object.entries(currentRoute.params || {}).map(([k, v]) => [
+ k,
+ Array.isArray(v) ? (v[0] ?? "") : (v ?? ""),
+ ])
+ ) as Record<string, string>),
+ specId,
+ },
+ query: (currentRoute.query || {}) as Record<string, string | undefined>,
+});
+
+export const buildPlanDeployRouteFromPlanName = (
+ planName: string,
+ options?: Omit<BuildPlanDeployRouteParams, "projectId" | "planId">
+): RouteTarget =>
+ buildPlanDeployRoute({
+ projectId: extractProjectResourceName(planName),
+ planId: extractPlanUID(planName) || "_",
+ ...options,
+ });
+
+export const buildPlanDeployRouteFromRolloutName = (
+ rolloutName: string,
+ options?: Omit<BuildPlanDeployRouteParams, "projectId" | "planId">
+): RouteTarget =>
+ buildPlanDeployRoute({
+ projectId: extractProjectResourceName(rolloutName),
+ planId: extractPlanUIDFromRolloutName(rolloutName) || "_",
+ ...options,
+ });
+
+export const buildTaskDetailRoute = (taskName: string): RouteTarget => {
+ const stageName = extractStageNameFromTaskName(taskName);
+ return buildPlanDeployRoute({
+ projectId: extractProjectResourceName(taskName),
+ planId: extractPlanUIDFromRolloutName(taskName) || "-",
+ stageId: extractStageUID(stageName) || "-",
+ taskId: extractTaskUID(taskName) || "-",
+ });
+};
+
+export const buildStageRoute = (stageName: string): RouteTarget =>
+ buildPlanDeployRoute({
+ projectId: extractProjectResourceName(stageName),
+ planId: extractPlanUIDFromRolloutName(stageName) || "_",
+ stageId: extractStageUID(stageName) || "_",
+ });
diff --git a/frontend/src/react/router/routes.test.tsx b/frontend/src/react/router/routes.test.tsx
new file mode 100644
index 0000000000..c7b116e2aa
--- /dev/null
+++ b/frontend/src/react/router/routes.test.tsx
@@ -0,0 +1,72 @@
+import type { RouteObject } from "react-router-dom";
+import { describe, expect, it } from "vitest";
+import { routes } from "./routes";
+
+// Guardrail for the "blank body" route bug class. During the Vue→React router
+// migration, several leaf routes were ported as bare `{ path, handle }` objects
+// with no `element`/`lazy`/`Component`. react-router renders such a leaf as an
+// empty `<Outlet/>`, so the page shows nothing (e.g. `/projects/bbdev` and the
+// legacy rollout/environment-detail routes). A leaf must therefore either
+// render something or redirect:
+// - `lazy` / `element` / `Component` — renders a page
+// - `loader` — performs a (typically param-aware) redirect()
+// - an ancestor flagged `handle.layoutAsPage` — the ancestor renders the
+// content itself and the child Outlet is intentionally empty (SQL Editor)
+// - `handle.guardRedirect` — `rootGuard` always redirects this route (the
+// dynamic workspace-root "/" redirect that can't be a static <Navigate>)
+// Any new bare leaf that doesn't fit one of these will fail this test instead
+// of silently shipping a blank page.
+
+type RouteHandle = {
+ name?: string;
+ layoutAsPage?: boolean;
+ guardRedirect?: boolean;
+};
+
+function joinPath(parent: string, child: string): string {
+ if (!child) return parent || "/";
+ const left = parent.endsWith("/") ? parent.slice(0, -1) : parent;
+ const right = child.startsWith("/") ? child : `/${child}`;
+ return `${left}${right}` || "/";
+}
+
+function collectBareLeaves(
+ list: RouteObject[],
+ parentPath = "",
+ underLayoutAsPage = false
+): string[] {
+ const bare: string[] = [];
+ for (const route of list) {
+ const handle = route.handle as RouteHandle | undefined;
+ const segment = route.path ?? "";
+ const fullPath = route.path?.startsWith("/")
+ ? segment
+ : joinPath(parentPath, segment);
+ const layoutAsPage = underLayoutAsPage || handle?.layoutAsPage === true;
+ const children = route.children;
+ const isLeaf = !children || children.length === 0;
+ if (isLeaf) {
+ const rendersOrRedirects =
+ Boolean(route.lazy) ||
+ Boolean(route.element) ||
+ Boolean(route.Component) ||
+ Boolean(route.loader) ||
+ layoutAsPage ||
+ handle?.guardRedirect === true;
+ if (!rendersOrRedirects) {
+ bare.push(
+ `${fullPath || "(index)"} [name=${handle?.name ?? "unnamed"}]`
+ );
+ }
+ } else {
+ bare.push(...collectBareLeaves(children, fullPath, layoutAsPage));
+ }
+ }
+ return bare;
+}
+
+describe("react route table reachability", () => {
+ it("every leaf route renders something or redirects (no blank-body bare leaves)", () => {
+ expect(collectBareLeaves(routes)).toEqual([]);
+ });
+});
diff --git a/frontend/src/react/router/routes.tsx b/frontend/src/react/router/routes.tsx
new file mode 100644
index 0000000000..2dcfcba8b3
--- /dev/null
+++ b/frontend/src/react/router/routes.tsx
@@ -0,0 +1,57 @@
+import type { RouteObject } from "react-router-dom";
+import { RootLayout } from "@/react/app/RootLayout";
+import { authRoutes } from "@/react/router/routes/auth";
+import { dashboardRoutes } from "@/react/router/routes/dashboard";
+import { sqlEditorRoutes } from "@/react/router/routes/sqlEditor";
+
+// React-router route table translated from the vue-router route definitions
+// (`@/router/auth.ts`, `@/router/setup.ts`, `@/router/sqlEditor.ts`,
+// `@/router/dashboard/**`). Composed in the same order as the vue router's
+// `routes: [...authRoutes, ...setupRoutes, ...dashboardRoutes,
+// ...sqlEditorRoutes]` (setup is folded into authRoutes here, both rendering
+// the SplashLayout). The whole table hangs off a single `RootLayout` route that
+// hosts the global overlays + `<AuthGate>`. Wiring this table into the
+// application root happens in a later phase.
+export const routes: RouteObject[] = [
+ {
+ element: <RootLayout />,
+ children: [...authRoutes, ...dashboardRoutes, ...sqlEditorRoutes],
+ },
+];
+
+function joinPath(parent: string, child: string): string {
+ if (!child) return parent || "/";
+ const left = parent.endsWith("/") ? parent.slice(0, -1) : parent;
+ const right = child.startsWith("/") ? child : `/${child}`;
+ return `${left}${right}` || "/";
+}
+
+// Flatten the nested route table into a `name -> full path pattern` map,
+// joining parent/child segments. Registered into `navigation.ts` at app boot so
+// the ported guard + auth lifecycle can resolve their by-name redirects to
+// paths. Lives here (a `.tsx` module) so `navigation.ts` stays a pure `.ts`.
+export function buildRouteNameIndex(
+ list: RouteObject[] = routes,
+ parentPath = ""
+): Map<string, string> {
+ const index = new Map<string, string>();
+ for (const route of list) {
+ const segment = route.path ?? "";
+ const fullPath = route.path?.startsWith("/")
+ ? segment
+ : joinPath(parentPath, segment);
+ const name = (route.handle as { name?: string } | undefined)?.name;
+ if (name && !index.has(name)) {
+ index.set(name, fullPath || "/");
+ }
+ if (route.children) {
+ for (const [childName, childPath] of buildRouteNameIndex(
+ route.children,
+ fullPath
+ )) {
+ if (!index.has(childName)) index.set(childName, childPath);
+ }
+ }
+ }
+ return index;
+}
diff --git a/frontend/src/react/router/routes/auth.tsx b/frontend/src/react/router/routes/auth.tsx
new file mode 100644
index 0000000000..5af931d829
--- /dev/null
+++ b/frontend/src/react/router/routes/auth.tsx
@@ -0,0 +1,149 @@
+import type { RouteObject } from "react-router-dom";
+import { SplashLayout } from "@/react/app/layouts/SplashLayout";
+import {
+ AUTH_2FA_SETUP_MODULE,
+ AUTH_MFA_MODULE,
+ AUTH_OAUTH_CALLBACK_MODULE,
+ AUTH_OIDC_CALLBACK_MODULE,
+ AUTH_PASSWORD_FORGOT_MODULE,
+ AUTH_PASSWORD_RESET_MODULE,
+ AUTH_PROFILE_SETUP_MODULE,
+ AUTH_SIGNIN_ADMIN_MODULE,
+ AUTH_SIGNIN_MODULE,
+ AUTH_SIGNUP_MODULE,
+ OAUTH2_CONSENT_MODULE,
+ SETUP_MODULE,
+} from "@/react/router/handles";
+import { lazyPage } from "@/react/router/lazyPage";
+
+// Translated from `@/router/auth.ts` and `@/router/setup.ts`. Every auth /
+// consent / setup leaf renders a self-contained React page under the
+// SplashLayout chrome.
+export const authRoutes: RouteObject[] = [
+ {
+ path: "/oauth2/consent",
+ element: <SplashLayout />,
+ children: [
+ {
+ index: true,
+ handle: { name: OAUTH2_CONSENT_MODULE },
+ lazy: lazyPage(
+ () => import("@/react/pages/auth/OAuth2ConsentPage"),
+ (m) => m.OAuth2ConsentPage
+ ),
+ },
+ ],
+ },
+ {
+ path: "/auth",
+ handle: { name: "auth" },
+ element: <SplashLayout />,
+ children: [
+ {
+ index: true,
+ handle: { name: AUTH_SIGNIN_MODULE },
+ lazy: lazyPage(
+ () => import("@/react/pages/auth/SigninPage"),
+ (m) => m.SigninPage
+ ),
+ },
+ {
+ // vue used `alias: "signin"` on the index child; react-router has no
+ // alias, so `/auth/signin` is an explicit sibling rendering the same
+ // page under the same route name.
+ path: "signin",
+ handle: { name: AUTH_SIGNIN_MODULE },
+ lazy: lazyPage(
+ () => import("@/react/pages/auth/SigninPage"),
+ (m) => m.SigninPage
+ ),
+ },
+ {
+ path: "admin",
+ handle: { name: AUTH_SIGNIN_ADMIN_MODULE },
+ lazy: lazyPage(
+ () => import("@/react/pages/auth/SigninAdminPage"),
+ (m) => m.SigninAdminPage
+ ),
+ },
+ {
+ path: "signup",
+ handle: { name: AUTH_SIGNUP_MODULE },
+ lazy: lazyPage(
+ () => import("@/react/pages/auth/SignupPage"),
+ (m) => m.SignupPage
+ ),
+ },
+ {
+ path: "password-forgot",
+ handle: { name: AUTH_PASSWORD_FORGOT_MODULE },
+ lazy: lazyPage(
+ () => import("@/react/pages/auth/PasswordForgotPage"),
+ (m) => m.PasswordForgotPage
+ ),
+ },
+ {
+ path: "password-reset",
+ handle: { name: AUTH_PASSWORD_RESET_MODULE },
+ lazy: lazyPage(
+ () => import("@/react/pages/auth/PasswordResetPage"),
+ (m) => m.PasswordResetPage
+ ),
+ },
+ {
+ path: "mfa",
+ handle: { name: AUTH_MFA_MODULE },
+ lazy: lazyPage(
+ () => import("@/react/pages/auth/MultiFactorPage"),
+ (m) => m.MultiFactorPage
+ ),
+ },
+ {
+ path: "profile-setup",
+ handle: { name: AUTH_PROFILE_SETUP_MODULE },
+ lazy: lazyPage(
+ () => import("@/react/pages/auth/ProfileSetupPage"),
+ (m) => m.ProfileSetupPage
+ ),
+ },
+ ],
+ },
+ {
+ path: "/oauth/callback",
+ handle: { name: AUTH_OAUTH_CALLBACK_MODULE },
+ lazy: lazyPage(
+ () => import("@/react/pages/auth/OAuthCallbackPage"),
+ (m) => m.OAuthCallbackPage
+ ),
+ },
+ {
+ path: "/oidc/callback",
+ handle: { name: AUTH_OIDC_CALLBACK_MODULE },
+ lazy: lazyPage(
+ () => import("@/react/pages/auth/OAuthCallbackPage"),
+ (m) => m.OAuthCallbackPage
+ ),
+ },
+ {
+ path: "/2fa/setup",
+ handle: { name: AUTH_2FA_SETUP_MODULE },
+ lazy: lazyPage(
+ () => import("@/react/pages/auth/TwoFactorRequiredPage"),
+ (m) => m.TwoFactorRequiredPage
+ ),
+ },
+ {
+ path: "/setup",
+ element: <SplashLayout />,
+ children: [
+ {
+ index: true,
+ handle: { name: SETUP_MODULE },
+ lazy: lazyPage(
+ () => import("@/react/pages/auth/SetupPage"),
+ (m) => m.SetupPage
+ ),
+ },
+ ],
+ },
+];
diff --git a/frontend/src/react/router/routes/dashboard.tsx b/frontend/src/react/router/routes/dashboard.tsx
new file mode 100644
index 0000000000..94a821ade7
--- /dev/null
+++ b/frontend/src/react/router/routes/dashboard.tsx
@@ -0,0 +1,1034 @@
+import { Navigate, type RouteObject, redirect } from "react-router-dom";
+import { BodyLayout } from "@/react/app/layouts/BodyLayout";
+import { DashboardLayout } from "@/react/app/layouts/DashboardLayout";
+import { rootGuard } from "@/react/router/guard";
+import {
+ DATABASE_ROUTE_DASHBOARD,
+ ENVIRONMENT_V1_ROUTE_DASHBOARD,
+ INSTANCE_ROUTE_CREATE,
+ INSTANCE_ROUTE_DASHBOARD,
+ INSTANCE_ROUTE_DATABASE_DETAIL,
+ INSTANCE_ROUTE_DETAIL,
+ PROJECT_V1_ROUTE_ACCESS_GRANTS,
+ PROJECT_V1_ROUTE_AUDIT_LOGS,
+ PROJECT_V1_ROUTE_DASHBOARD,
+ PROJECT_V1_ROUTE_DATA_EXPORT,
+ PROJECT_V1_ROUTE_DATABASE_CHANGELOG_DETAIL,
+ PROJECT_V1_ROUTE_DATABASE_DETAIL,
+ PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,
+ PROJECT_V1_ROUTE_DATABASE_GROUPS,
+ PROJECT_V1_ROUTE_DATABASE_GROUPS_CREATE,
+ PROJECT_V1_ROUTE_DATABASE_REVISION_DETAIL,
+ PROJECT_V1_ROUTE_DATABASES,
+ PROJECT_V1_ROUTE_DETAIL,
+ PROJECT_V1_ROUTE_GITOPS,
+ PROJECT_V1_ROUTE_ISSUE_DETAIL,
+ PROJECT_V1_ROUTE_ISSUES,
+ PROJECT_V1_ROUTE_MASKING_EXEMPTION,
+ PROJECT_V1_ROUTE_MASKING_EXEMPTION_CREATE,
+ PROJECT_V1_ROUTE_MEMBERS,
+ PROJECT_V1_ROUTE_PLAN_DETAIL,
+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,
+ PROJECT_V1_ROUTE_PLAN_ROLLOUT,
+ PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE,
+ PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,
+ PROJECT_V1_ROUTE_PLANS,
+ PROJECT_V1_ROUTE_RELEASE_DETAIL,
+ PROJECT_V1_ROUTE_RELEASES,
+ PROJECT_V1_ROUTE_SERVICE_ACCOUNTS,
+ PROJECT_V1_ROUTE_SETTINGS,
+ PROJECT_V1_ROUTE_SYNC_SCHEMA,
+ PROJECT_V1_ROUTE_WEBHOOK_CREATE,
+ PROJECT_V1_ROUTE_WEBHOOK_DETAIL,
+ PROJECT_V1_ROUTE_WEBHOOKS,
+ PROJECT_V1_ROUTE_WORKLOAD_IDENTITIES,
+ SETTING_ROUTE_PROFILE,
+ SETTING_ROUTE_PROFILE_TWO_FACTOR,
+ SETTING_ROUTE_WORKSPACE,
+ SETTING_ROUTE_WORKSPACE_GENERAL,
+ SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,
+ WORKSPACE_ROOT_MODULE,
+ WORKSPACE_ROUTE_403,
+ WORKSPACE_ROUTE_404,
+ WORKSPACE_ROUTE_AUDIT_LOG,
+ WORKSPACE_ROUTE_CUSTOM_APPROVAL,
+ WORKSPACE_ROUTE_DATA_CLASSIFICATION,
+ WORKSPACE_ROUTE_GLOBAL_MASKING,
+ WORKSPACE_ROUTE_GROUPS,
+ WORKSPACE_ROUTE_IDENTITY_PROVIDER_DETAIL,
+ WORKSPACE_ROUTE_IDENTITY_PROVIDERS,
+ WORKSPACE_ROUTE_IM,
+ WORKSPACE_ROUTE_LANDING,
+ WORKSPACE_ROUTE_MCP,
+ WORKSPACE_ROUTE_MEMBERS,
+ WORKSPACE_ROUTE_MY_ISSUES,
+ WORKSPACE_ROUTE_RISK_ASSESSMENT,
+ WORKSPACE_ROUTE_ROLES,
+ WORKSPACE_ROUTE_SEMANTIC_TYPES,
+ WORKSPACE_ROUTE_SERVICE_ACCOUNTS,
+ WORKSPACE_ROUTE_SQL_REVIEW,
+ WORKSPACE_ROUTE_SQL_REVIEW_CREATE,
+ WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,
+ WORKSPACE_ROUTE_USER_PROFILE,
+ WORKSPACE_ROUTE_USERS,
+ WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,
+} from "@/react/router/handles";
+import { RouteShellOutletPlaceholder } from "@/react/router/layoutPlaceholders";
+import { lazyPage } from "@/react/router/lazyPage";
+import { ProjectRouteGate } from "@/react/router/ProjectRouteGate";
+import type { Permission } from "@/types";
+
+// Translated from `@/router/dashboard/**`. Vue named views (`content`,
+// `leftSidebar`, `body`) collapse to the single `<Outlet/>` of each layout
+// route. The Vue route-shell parents (`SettingRouteShell` /
+// `ProjectRouteShell` / `InstanceRouteShell` / `IssuesRouteShell`) render an
+// empty teleport target and require ReactRouteShellBridge props; they do not
+// render an `<Outlet/>`, so each shell-parent route here uses
+// `RouteShellOutletPlaceholder` to keep child leaves rendering until a later
+// phase swaps in `<Outlet/>`-aware shells. Leaf routes lazy-import their page
+// component.
+
+// Workspace-level pages (the BodyLayout children).
+const workspaceLevelRoutes: RouteObject[] = [
+ {
+ index: true,
+ // The bare workspace root ("/") has no page; it redirects dynamically
+ // (change-mode → SQL Editor, else last visit / landing). The global guard
+ // on the root route only re-runs on initial document load, NOT on
+ // client-side navigations (the root route is already matched, so its loader
+ // is not revalidated) — so after an in-app `navigate("/")` (e.g. post-login)
+ // "/" would render this element-less index and show a blank page until a
+ // manual refresh. This index-route loader runs `rootGuard` whenever "/" is
+ // freshly matched (client nav AND initial load, since the index route is
+ // newly matched each time), so the redirect always fires. `guardRedirect`
+ // records the no-element redirect for the route-reachability test.
+ handle: { name: WORKSPACE_ROOT_MODULE, guardRedirect: true },
+ loader: ({ request }) =>
+ rootGuard({
+ name: WORKSPACE_ROOT_MODULE,
+ url: new URL(request.url),
+ }),
+ },
+ {
+ path: "landing",
+ handle: { name: WORKSPACE_ROUTE_LANDING },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/LandingPage"),
+ (m) => m.LandingPage
+ ),
+ },
+ {
+ path: "projects",
+ handle: { name: PROJECT_V1_ROUTE_DASHBOARD },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/ProjectsPage"),
+ (m) => m.ProjectsPage
+ ),
+ },
+ {
+ path: "instances",
+ handle: {
+ name: INSTANCE_ROUTE_DASHBOARD,
+ requiredPermissionList: (): Permission[] => ["bb.instances.list"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/InstancesPage"),
+ (m) => m.InstancesPage
+ ),
+ },
+ {
+ path: "databases",
+ handle: {
+ name: DATABASE_ROUTE_DASHBOARD,
+ requiredPermissionList: (): Permission[] => ["bb.databases.list"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/DatabasesPage"),
+ (m) => m.DatabasesPage
+ ),
+ },
+ {
+ path: "environments",
+ handle: {
+ name: ENVIRONMENT_V1_ROUTE_DASHBOARD,
+ requiredPermissionList: (): Permission[] => [
+ "bb.settings.getEnvironment",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/EnvironmentsPage"),
+ (m) => m.EnvironmentsPage
+ ),
+ },
+ {
+ path: "users/:principalEmail",
+ handle: { name: WORKSPACE_ROUTE_USER_PROFILE },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/ProfilePage"),
+ (m) => m.ProfilePage
+ ),
+ },
+ {
+ path: "403",
+ handle: { name: WORKSPACE_ROUTE_403 },
+ lazy: lazyPage(
+ () => import("@/react/pages/workspace/Page403"),
+ (m) => m.Page403
+ ),
+ },
+ {
+ path: "404",
+ handle: { name: WORKSPACE_ROUTE_404 },
+ lazy: lazyPage(
+ () => import("@/react/pages/workspace/Page404"),
+ (m) => m.Page404
+ ),
+ },
+ // /sql-review — SettingRouteShell layout owns these leaves.
+ {
+ path: "sql-review",
+ element: <RouteShellOutletPlaceholder />,
+ children: [
+ {
+ index: true,
+ handle: {
+ name: WORKSPACE_ROUTE_SQL_REVIEW,
+ requiredPermissionList: (): Permission[] => [
+ "bb.reviewConfigs.list",
+ "bb.policies.get",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/SQLReviewPage"),
+ (m) => m.SQLReviewPage
+ ),
+ },
+ {
+ path: "new",
+ handle: {
+ name: WORKSPACE_ROUTE_SQL_REVIEW_CREATE,
+ requiredPermissionList: (): Permission[] => [
+ "bb.reviewConfigs.create",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/SQLReviewCreatePage"),
+ (m) => m.SQLReviewCreatePage
+ ),
+ },
+ {
+ path: ":sqlReviewPolicySlug",
+ handle: {
+ name: WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,
+ requiredPermissionList: (): Permission[] => [
+ "bb.reviewConfigs.get",
+ "bb.policies.get",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/SQLReviewDetailPage"),
+ (m) => m.SQLReviewDetailPage
+ ),
+ },
+ ],
+ },
+ // /idps — SettingRouteShell layout. The parent carries the route permission
+ // so both children (list + detail) inherit it via the matched-chain
+ // aggregation in `assembleRoute`.
+ {
+ path: "idps",
+ handle: {
+ requiredPermissionList: (): Permission[] => ["bb.identityProviders.get"],
+ },
+ element: <RouteShellOutletPlaceholder />,
+ children: [
+ {
+ index: true,
+ handle: { name: WORKSPACE_ROUTE_IDENTITY_PROVIDERS },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/IDPsPage"),
+ (m) => m.IDPsPage
+ ),
+ },
+ {
+ path: ":idpId",
+ handle: { name: WORKSPACE_ROUTE_IDENTITY_PROVIDER_DETAIL },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/IDPDetailPage"),
+ (m) => m.IDPDetailPage
+ ),
+ },
+ ],
+ },
+ // Empty-path SettingRouteShell group (risk-assessment, members, roles, …).
+ {
+ path: "",
+ element: <RouteShellOutletPlaceholder />,
+ children: [
+ {
+ path: "risk-assessment",
+ handle: { name: WORKSPACE_ROUTE_RISK_ASSESSMENT },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/RiskAssessmentPage"),
+ (m) => m.RiskAssessmentPage
+ ),
+ },
+ {
+ path: "custom-approval",
+ handle: {
+ name: WORKSPACE_ROUTE_CUSTOM_APPROVAL,
+ requiredPermissionList: (): Permission[] => ["bb.settings.get"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/CustomApprovalPage"),
+ (m) => m.CustomApprovalPage
+ ),
+ },
+ {
+ path: "global-masking",
+ handle: {
+ name: WORKSPACE_ROUTE_GLOBAL_MASKING,
+ requiredPermissionList: (): Permission[] => [
+ "bb.policies.getMaskingRulePolicy",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/GlobalMaskingPage"),
+ (m) => m.GlobalMaskingPage
+ ),
+ },
+ {
+ path: "semantic-types",
+ handle: {
+ name: WORKSPACE_ROUTE_SEMANTIC_TYPES,
+ requiredPermissionList: (): Permission[] => ["bb.settings.get"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/SemanticTypesPage"),
+ (m) => m.SemanticTypesPage
+ ),
+ },
+ {
+ path: "data-classification",
+ handle: {
+ name: WORKSPACE_ROUTE_DATA_CLASSIFICATION,
+ requiredPermissionList: (): Permission[] => ["bb.settings.get"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/DataClassificationPage"),
+ (m) => m.DataClassificationPage
+ ),
+ },
+ {
+ path: "audit-log",
+ handle: {
+ name: WORKSPACE_ROUTE_AUDIT_LOG,
+ requiredPermissionList: (): Permission[] => ["bb.auditLogs.search"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/AuditLogPage"),
+ (m) => m.AuditLogPage
+ ),
+ },
+ {
+ path: "users",
+ handle: {
+ name: WORKSPACE_ROUTE_USERS,
+ requiredPermissionList: (): Permission[] => ["bb.users.list"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/UsersPage"),
+ (m) => m.UsersPage
+ ),
+ },
+ {
+ path: "service-accounts",
+ handle: {
+ name: WORKSPACE_ROUTE_SERVICE_ACCOUNTS,
+ requiredPermissionList: (): Permission[] => [
+ "bb.serviceAccounts.list",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/ServiceAccountsPage"),
+ (m) => m.ServiceAccountsPage
+ ),
+ },
+ {
+ path: "workload-identities",
+ handle: {
+ name: WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,
+ requiredPermissionList: (): Permission[] => [
+ "bb.workloadIdentities.list",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/WorkloadIdentitiesPage"),
+ (m) => m.WorkloadIdentitiesPage
+ ),
+ },
+ {
+ path: "members",
+ handle: {
+ name: WORKSPACE_ROUTE_MEMBERS,
+ requiredPermissionList: (): Permission[] => [
+ "bb.workspaces.getIamPolicy",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/MembersPage"),
+ (m) => m.MembersPage
+ ),
+ },
+ {
+ path: "groups",
+ handle: {
+ name: WORKSPACE_ROUTE_GROUPS,
+ requiredPermissionList: (): Permission[] => ["bb.groups.list"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/GroupsPage"),
+ (m) => m.GroupsPage
+ ),
+ },
+ {
+ path: "roles",
+ handle: {
+ name: WORKSPACE_ROUTE_ROLES,
+ requiredPermissionList: (): Permission[] => ["bb.roles.list"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/RolesPage"),
+ (m) => m.RolesPage
+ ),
+ },
+ ],
+ },
+ // /integration — SettingRouteShell layout.
+ {
+ path: "integration",
+ element: <RouteShellOutletPlaceholder />,
+ children: [
+ {
+ path: "im",
+ handle: {
+ name: WORKSPACE_ROUTE_IM,
+ requiredPermissionList: (): Permission[] => ["bb.settings.get"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/IMPage"),
+ (m) => m.IMPage
+ ),
+ },
+ {
+ path: "mcp",
+ handle: {
+ name: WORKSPACE_ROUTE_MCP,
+ requiredPermissionList: (): Permission[] => ["bb.settings.get"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/MCPPage"),
+ (m) => m.MCPPage
+ ),
+ },
+ ],
+ },
+];
+
+// Workspace settings routes (`/setting/**`), SettingRouteShell layout.
+const workspaceSettingRoutes: RouteObject[] = [
+ {
+ path: "setting",
+ handle: { name: SETTING_ROUTE_WORKSPACE },
+ element: <RouteShellOutletPlaceholder />,
+ children: [
+ {
+ path: "profile",
+ handle: { name: SETTING_ROUTE_PROFILE },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/ProfilePage"),
+ (m) => m.ProfilePage
+ ),
+ },
+ {
+ path: "profile/two-factor",
+ handle: { name: SETTING_ROUTE_PROFILE_TWO_FACTOR },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/TwoFactorSetupPage"),
+ (m) => m.TwoFactorSetupPage
+ ),
+ },
+ {
+ path: "general",
+ handle: {
+ name: SETTING_ROUTE_WORKSPACE_GENERAL,
+ requiredPermissionList: (): Permission[] => [
+ "bb.settings.getWorkspaceProfile",
+ "bb.policies.get",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/GeneralPage"),
+ (m) => m.GeneralPage
+ ),
+ },
+ {
+ path: "subscription",
+ handle: {
+ name: SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,
+ requiredPermissionList: (): Permission[] => ["bb.settings.get"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/SubscriptionPage"),
+ (m) => m.SubscriptionPage
+ ),
+ },
+ ],
+ },
+];
+
+// Environment detail — redirect-only route in vue (it redirected to the
+// environments dashboard with the environment name as a `#hash`). A leaf with
+// no element/lazy renders a blank body, so the redirect is the element here.
+const environmentV1Routes: RouteObject[] = [
+ {
+ path: "environments/:environmentName",
+ handle: {
+ name: "workspace.environment.detail",
+ requiredPermissionList: (): Permission[] => [
+ "bb.settings.getEnvironment",
+ ],
+ },
+ loader: ({ params }) =>
+ redirect(`/environments#${params.environmentName ?? ""}`),
+ },
+];
+
+// Instance routes (`/instances/new`, `/instances/:instanceId/**`).
+const instanceRoutes: RouteObject[] = [
+ {
+ path: "instances/new",
+ handle: {
+ name: INSTANCE_ROUTE_CREATE,
+ requiredPermissionList: (): Permission[] => ["bb.instances.create"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/CreateInstancePage"),
+ (m) => m.CreateInstancePage
+ ),
+ },
+ {
+ path: "instances/:instanceId",
+ element: <RouteShellOutletPlaceholder />,
+ children: [
+ {
+ index: true,
+ handle: {
+ name: INSTANCE_ROUTE_DETAIL,
+ requiredPermissionList: (): Permission[] => ["bb.instances.get"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/InstanceDetailPage"),
+ (m) => m.InstanceDetailPage
+ ),
+ },
+ {
+ path: "databases/:databaseName",
+ handle: {
+ name: INSTANCE_ROUTE_DATABASE_DETAIL,
+ requiredPermissionList: (): Permission[] => [
+ "bb.projects.get",
+ "bb.databases.get",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/InstanceDatabaseRedirectPage"),
+ (m) => m.InstanceDatabaseRedirectPage
+ ),
+ },
+ ],
+ },
+];
+
+// Project routes (`/projects/:projectId/**`).
+//
+// The `requiredPermissionList` entries on the parent (`bb.projects.get`) and
+// each leaf are ported 1:1 from the legacy vue routes and aggregate via
+// `assembleRoute` into `route.requiredPermissions`. `ProjectRouteGate` (the
+// parent element) loads the project and enforces those permissions before its
+// `<Outlet/>` mounts the leaf — project-scoped checks need the loaded `Project`
+// resource, which is why `BodyLayout` routes project routes straight to this
+// gate instead of its generic workspace-level `RoutePermissionGuardShell`.
+const projectV1Routes: RouteObject[] = [
+ {
+ path: "projects/:projectId",
+ handle: {
+ requiredPermissionList: (): Permission[] => ["bb.projects.get"],
+ },
+ element: <ProjectRouteGate />,
+ children: [
+ {
+ index: true,
+ handle: { name: PROJECT_V1_ROUTE_DETAIL },
+ // The project root has no page of its own — redirect to the Issues
+ // tab (mirrors the legacy vue-router DETAIL → ISSUES redirect). `issues`
+ // is relative to the parent `projects/:projectId`.
+ element: <Navigate to="issues" replace />,
+ },
+ {
+ path: "databases",
+ handle: {
+ name: PROJECT_V1_ROUTE_DATABASES,
+ requiredPermissionList: (): Permission[] => ["bb.databases.list"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/ProjectDatabasesPage"),
+ (m) => m.ProjectDatabasesPage
+ ),
+ },
+ {
+ path: "access-grants",
+ handle: { name: PROJECT_V1_ROUTE_ACCESS_GRANTS },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/ProjectAccessGrantsPage"),
+ (m) => m.ProjectAccessGrantsPage
+ ),
+ },
+ {
+ path: "masking-exemption",
+ children: [
+ {
+ index: true,
+ handle: {
+ name: PROJECT_V1_ROUTE_MASKING_EXEMPTION,
+ requiredPermissionList: (): Permission[] => [
+ "bb.databases.get",
+ "bb.policies.getMaskingExemptionPolicy",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/ProjectMaskingExemptionPage"),
+ (m) => m.ProjectMaskingExemptionPage
+ ),
+ },
+ {
+ path: "create",
+ handle: {
+ name: PROJECT_V1_ROUTE_MASKING_EXEMPTION_CREATE,
+ requiredPermissionList: (): Permission[] => [
+ "bb.policies.createMaskingExemptionPolicy",
+ "bb.policies.updateMaskingExemptionPolicy",
+ "bb.databases.list",
+ "bb.databaseCatalogs.get",
+ ],
+ },
+ lazy: lazyPage(
+ () =>
+ import(
+ "@/react/pages/project/ProjectMaskingExemptionCreatePage"
+ ),
+ (m) => m.ProjectMaskingExemptionCreatePage
+ ),
+ },
+ ],
+ },
+ {
+ path: "database-groups",
+ children: [
+ {
+ index: true,
+ handle: {
+ name: PROJECT_V1_ROUTE_DATABASE_GROUPS,
+ requiredPermissionList: (): Permission[] => [
+ "bb.databaseGroups.list",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/ProjectDatabaseGroupsPage"),
+ (m) => m.ProjectDatabaseGroupsPage
+ ),
+ },
+ {
+ path: "create",
+ handle: {
+ name: PROJECT_V1_ROUTE_DATABASE_GROUPS_CREATE,
+ requiredPermissionList: (): Permission[] => [
+ "bb.databaseGroups.create",
+ "bb.databases.list",
+ ],
+ },
+ lazy: lazyPage(
+ () =>
+ import("@/react/pages/project/ProjectDatabaseGroupCreatePage"),
+ (m) => m.ProjectDatabaseGroupCreatePage
+ ),
+ },
+ {
+ path: ":databaseGroupName",
+ handle: {
+ name: PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,
+ requiredPermissionList: (): Permission[] => [
+ "bb.databaseGroups.get",
+ "bb.databases.list",
+ ],
+ },
+ lazy: lazyPage(
+ () =>
+ import("@/react/pages/project/ProjectDatabaseGroupDetailPage"),
+ (m) => m.ProjectDatabaseGroupDetailPage
+ ),
+ },
+ ],
+ },
+ {
+ path: "issues",
+ handle: {
+ name: PROJECT_V1_ROUTE_ISSUES,
+ requiredPermissionList: (): Permission[] => ["bb.issues.list"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/ProjectIssueDashboardPage"),
+ (m) => m.ProjectIssueDashboardPage
+ ),
+ },
+ {
+ path: "plans",
+ handle: {
+ name: PROJECT_V1_ROUTE_PLANS,
+ requiredPermissionList: (): Permission[] => [
+ "bb.databases.list",
+ "bb.plans.list",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/ProjectPlanDashboardPage"),
+ (m) => m.ProjectPlanDashboardPage
+ ),
+ },
+ {
+ path: "sync-schema",
+ handle: {
+ name: PROJECT_V1_ROUTE_SYNC_SCHEMA,
+ requiredPermissionList: (): Permission[] => [
+ "bb.databases.sync",
+ "bb.databases.list",
+ "bb.databases.get",
+ "bb.databases.getSchema",
+ "bb.changelogs.get",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/ProjectSyncSchemaPage"),
+ (m) => m.ProjectSyncSchemaPage
+ ),
+ },
+ {
+ path: "audit-logs",
+ handle: {
+ name: PROJECT_V1_ROUTE_AUDIT_LOGS,
+ requiredPermissionList: (): Permission[] => ["bb.auditLogs.search"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/ProjectAuditLogPage"),
+ (m) => m.ProjectAuditLogPage
+ ),
+ },
+ {
+ path: "webhooks",
+ children: [
+ {
+ index: true,
+ handle: { name: PROJECT_V1_ROUTE_WEBHOOKS },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/ProjectWebhooksPage"),
+ (m) => m.ProjectWebhooksPage
+ ),
+ },
+ {
+ path: "new",
+ handle: {
+ name: PROJECT_V1_ROUTE_WEBHOOK_CREATE,
+ requiredPermissionList: (): Permission[] => [
+ "bb.projects.update",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/ProjectWebhookCreatePage"),
+ (m) => m.ProjectWebhookCreatePage
+ ),
+ },
+ {
+ path: ":webhookResourceId",
+ handle: { name: PROJECT_V1_ROUTE_WEBHOOK_DETAIL },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/ProjectWebhookDetailPage"),
+ (m) => m.ProjectWebhookDetailPage
+ ),
+ },
+ ],
+ },
+ {
+ path: "members",
+ handle: {
+ name: PROJECT_V1_ROUTE_MEMBERS,
+ requiredPermissionList: (): Permission[] => [
+ "bb.projects.getIamPolicy",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/MembersPage"),
+ (m) => m.MembersPage
+ ),
+ },
+ {
+ path: "service-accounts",
+ handle: {
+ name: PROJECT_V1_ROUTE_SERVICE_ACCOUNTS,
+ requiredPermissionList: (): Permission[] => [
+ "bb.serviceAccounts.list",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/ServiceAccountsPage"),
+ (m) => m.ServiceAccountsPage
+ ),
+ },
+ {
+ path: "workload-identities",
+ handle: {
+ name: PROJECT_V1_ROUTE_WORKLOAD_IDENTITIES,
+ requiredPermissionList: (): Permission[] => [
+ "bb.workloadIdentities.list",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/settings/WorkloadIdentitiesPage"),
+ (m) => m.WorkloadIdentitiesPage
+ ),
+ },
+ {
+ path: "settings",
+ handle: { name: PROJECT_V1_ROUTE_SETTINGS },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/ProjectSettingsPage"),
+ (m) => m.ProjectSettingsPage
+ ),
+ },
+ {
+ path: "instances/:instanceId/databases/:databaseName",
+ handle: {
+ name: PROJECT_V1_ROUTE_DATABASE_DETAIL,
+ requiredPermissionList: (): Permission[] => ["bb.databases.get"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/ProjectDatabaseDetailPage"),
+ (m) => m.ProjectDatabaseDetailPage
+ ),
+ },
+ {
+ path: "instances/:instanceId/databases/:databaseName/changelogs/:changelogId",
+ handle: {
+ name: PROJECT_V1_ROUTE_DATABASE_CHANGELOG_DETAIL,
+ requiredPermissionList: (): Permission[] => [
+ "bb.databases.get",
+ "bb.changelogs.get",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/DatabaseChangelogDetailPage"),
+ (m) => m.DatabaseChangelogDetailPage
+ ),
+ },
+ {
+ path: "instances/:instanceId/databases/:databaseName/revisions/:revisionId",
+ handle: {
+ name: PROJECT_V1_ROUTE_DATABASE_REVISION_DETAIL,
+ requiredPermissionList: (): Permission[] => ["bb.databases.get"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/DatabaseRevisionDetailPage"),
+ (m) => m.DatabaseRevisionDetailPage
+ ),
+ },
+ {
+ path: "data-export",
+ handle: {
+ name: PROJECT_V1_ROUTE_DATA_EXPORT,
+ requiredPermissionList: (): Permission[] => [
+ "bb.issues.list",
+ "bb.databases.list",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/ProjectDataExportPage"),
+ (m) => m.ProjectDataExportPage
+ ),
+ },
+ {
+ path: "releases",
+ children: [
+ {
+ index: true,
+ handle: {
+ name: PROJECT_V1_ROUTE_RELEASES,
+ requiredPermissionList: (): Permission[] => ["bb.releases.list"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/ProjectReleaseDashboardPage"),
+ (m) => m.ProjectReleaseDashboardPage
+ ),
+ },
+ {
+ path: ":releaseId",
+ handle: {
+ name: PROJECT_V1_ROUTE_RELEASE_DETAIL,
+ requiredPermissionList: (): Permission[] => ["bb.releases.get"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/ProjectReleaseDetailPage"),
+ (m) => m.ProjectReleaseDetailPage
+ ),
+ },
+ ],
+ },
+ {
+ path: "gitops",
+ handle: {
+ name: PROJECT_V1_ROUTE_GITOPS,
+ requiredPermissionList: (): Permission[] => [
+ "bb.workloadIdentities.list",
+ "bb.databases.list",
+ ],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/ProjectGitOpsPage"),
+ (m) => m.ProjectGitOpsPage
+ ),
+ },
+ // Plan detail — three routes share ProjectPlanDetailPage.
+ {
+ path: "plans/:planId",
+ handle: {
+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,
+ requiredPermissionList: (): Permission[] => [
+ "bb.plans.get",
+ "bb.planCheckRuns.get",
+ "bb.taskRuns.list",
+ ],
+ },
+ lazy: lazyPage(
+ () =>
+ import("@/react/pages/project/plan-detail/ProjectPlanDetailPage"),
+ (m) => m.ProjectPlanDetailPage
+ ),
+ },
+ {
+ path: "plans/:planId/specs",
+ handle: {
+ name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,
+ requiredPermissionList: (): Permission[] => [
+ "bb.plans.get",
+ "bb.planCheckRuns.get",
+ "bb.taskRuns.list",
+ ],
+ },
+ lazy: lazyPage(
+ () =>
+ import("@/react/pages/project/plan-detail/ProjectPlanDetailPage"),
+ (m) => m.ProjectPlanDetailPage
+ ),
+ },
+ {
+ path: "plans/:planId/specs/:specId",
+ handle: {
+ name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
+ requiredPermissionList: (): Permission[] => [
+ "bb.plans.get",
+ "bb.planCheckRuns.get",
+ "bb.taskRuns.list",
+ ],
+ },
+ lazy: lazyPage(
+ () =>
+ import("@/react/pages/project/plan-detail/ProjectPlanDetailPage"),
+ (m) => m.ProjectPlanDetailPage
+ ),
+ },
+ // Issue detail.
+ {
+ path: "issues/:issueId",
+ handle: {
+ name: PROJECT_V1_ROUTE_ISSUE_DETAIL,
+ requiredPermissionList: (): Permission[] => ["bb.issues.get"],
+ },
+ lazy: lazyPage(
+ () => import("@/react/pages/project/ProjectIssueDetailPage"),
+ (m) => m.ProjectIssueDetailPage
+ ),
+ },
+ // Legacy rollout paths. The plan detail page now hosts the rollout: it
+ // shows the deploy phase when the plan has a rollout and selects a
+ // stage/task from the `?stageId=`/`?taskId=` query (see
+ // usePlanDetailPage). So these path-based deep links redirect to the plan
+ // detail page, converting the path stage/task into that query form so the
+ // selection is preserved. The route names are kept so bookmarks resolve.
+ {
+ path: "plans/:planId/rollout",
+ handle: { name: PROJECT_V1_ROUTE_PLAN_ROLLOUT },
+ loader: ({ params }) =>
+ redirect(`/projects/${params.projectId}/plans/${params.planId}`),
+ },
+ {
+ path: "plans/:planId/rollout/stages/:stageId",
+ handle: { name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE },
+ loader: ({ params }) =>
+ redirect(
+ `/projects/${params.projectId}/plans/${params.planId}?stageId=${params.stageId}`
+ ),
+ },
+ {
+ path: "plans/:planId/rollout/stages/:stageId/tasks/:taskId",
+ handle: { name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK },
+ loader: ({ params }) =>
+ redirect(
+ `/projects/${params.projectId}/plans/${params.planId}?stageId=${params.stageId}&taskId=${params.taskId}`
+ ),
+ },
+ ],
+ },
+];
+
+// `/` DashboardLayout → BodyLayout child holding the dashboard routes, plus
+// the `/issues` IssuesRouteShell route.
+export const dashboardRoutes: RouteObject[] = [
+ {
+ path: "/",
+ element: <DashboardLayout />,
+ children: [
+ {
+ path: "",
+ element: <BodyLayout />,
+ children: [
+ ...workspaceLevelRoutes,
+ ...workspaceSettingRoutes,
+ ...environmentV1Routes,
+ ...instanceRoutes,
+ ...projectV1Routes,
+ // Workspace "My Issues" — lives under BodyLayout for the shared
+ // dashboard header, but renders as a standalone full-width page
+ // (header with logo, no sidebar): BodyLayout switches it to the
+ // `issues` shell variant.
+ {
+ path: "issues",
+ handle: { name: WORKSPACE_ROUTE_MY_ISSUES },
+ lazy: lazyPage(
+ () => import("@/react/pages/workspace/MyIssuesPage"),
+ (m) => m.MyIssuesPage
+ ),
+ },
+ ],
+ },
+ ],
+ },
+];
diff --git a/frontend/src/react/router/routes/sqlEditor.tsx b/frontend/src/react/router/routes/sqlEditor.tsx
new file mode 100644
index 0000000000..f2587eda91
--- /dev/null
+++ b/frontend/src/react/router/routes/sqlEditor.tsx
@@ -0,0 +1,75 @@
+import { lazy, Suspense } from "react";
+import { Outlet, type RouteObject } from "react-router-dom";
+import {
+ SQL_EDITOR_DATABASE_MODULE,
+ SQL_EDITOR_HOME_MODULE,
+ SQL_EDITOR_INSTANCE_MODULE,
+ SQL_EDITOR_PROJECT_MODULE,
+ SQL_EDITOR_WORKSHEET_MODULE,
+} from "@/react/router/handles";
+import type { Permission } from "@/types";
+
+// `SQLEditorLayout` is a "layout as a page": the React component inspects the
+// current route itself and decides what to render. It does NOT render an
+// `<Outlet/>`, so we wrap it in a small layout-route component that renders
+// the layout alongside an `<Outlet/>`. The child routes carry no element of
+// their own — they exist only so navigation by route name resolves to a path,
+// matching the original vue `NoopRouteComponent` children.
+const SQLEditorLayout = lazy(() =>
+ import("@/react/components/sql-editor/SQLEditorLayout").then((m) => ({
+ default: m.SQLEditorLayout,
+ }))
+);
+
+const SqlEditorLayoutRoute = () => (
+ <Suspense fallback={null}>
+ <SQLEditorLayout />
+ <Outlet />
+ </Suspense>
+);
+
+export const sqlEditorRoutes: RouteObject[] = [
+ {
+ path: "/sql-editor",
+ // `layoutAsPage` marks this parent as rendering its own content (the
+ // `SQLEditorLayout` inspects the route and draws everything); its child
+ // routes are intentionally element-less and render into an empty Outlet.
+ // The route-reachability test relies on this flag to allow those children.
+ // `SQLEditorRouteShell` gates the editor on `route.requiredPermissions`,
+ // so the parent must carry the route permission list (ported 1:1 from the
+ // legacy vue `/sql-editor` route). The child modules inherit it via the
+ // matched-chain aggregation in `assembleRoute`.
+ handle: {
+ name: "sql-editor",
+ layoutAsPage: true,
+ requiredPermissionList: (): Permission[] => [
+ "bb.projects.get",
+ "bb.databases.list",
+ "bb.projects.getIamPolicy",
+ ],
+ },
+ element: <SqlEditorLayoutRoute />,
+ children: [
+ {
+ index: true,
+ handle: { name: SQL_EDITOR_HOME_MODULE },
+ },
+ {
+ path: "projects/:project",
+ handle: { name: SQL_EDITOR_PROJECT_MODULE },
+ },
+ {
+ path: "projects/:project/instances/:instance/databases/:database",
+ handle: { name: SQL_EDITOR_DATABASE_MODULE },
+ },
+ {
+ path: "projects/:project/instances/:instance",
+ handle: { name: SQL_EDITOR_INSTANCE_MODULE },
+ },
+ {
+ path: "projects/:project/sheets/:sheet",
+ handle: { name: SQL_EDITOR_WORKSHEET_MODULE },
+ },
+ ],
+ },
+];
diff --git a/frontend/src/react/shims-vue-router.d.ts b/frontend/src/react/shims-vue-router.d.ts
deleted file mode 100644
index 93b3d7d624..0000000000
--- a/frontend/src/react/shims-vue-router.d.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-// Augment vue-router RouteMeta for transitive imports from @/router.
-// Simplified version of src/shims-vue-router.d.ts that avoids
-// referencing RouteLocationNormalized (not available in plain tsc).
-import "vue-router";
-declare module "vue-router" {
- interface RouteMeta {
- // biome-ignore lint/suspicious/noExplicitAny: simplified shim for React tsc
- title?: (...args: any[]) => string; // eslint-disable-line @typescript-eslint/no-explicit-any
- requiredPermissionList?: () => string[];
- overrideDocumentTitle?: boolean;
- }
-}
diff --git a/frontend/src/react/stores/app/auth.ts b/frontend/src/react/stores/app/auth.ts
index f09a53960e..d1df5c5168 100644
--- a/frontend/src/react/stores/app/auth.ts
+++ b/frontend/src/react/stores/app/auth.ts
@@ -1,7 +1,94 @@
+import { create } from "@bufbuild/protobuf";
+import { Code, createContextValues } from "@connectrpc/connect";
+import { uniqueId } from "lodash-es";
import { authServiceClientConnect, userServiceClientConnect } from "@/connect";
+import { ignoredCodesContextKey } from "@/connect/context-key";
+import {
+ AUTH_MFA_MODULE,
+ AUTH_PASSWORD_RESET_MODULE,
+ AUTH_PROFILE_SETUP_MODULE,
+ AUTH_SIGNIN_MODULE,
+ SETUP_MODULE,
+ SQL_EDITOR_HOME_MODULE,
+} from "@/react/router/handles";
+import {
+ navigateByName,
+ navigateToPath,
+ resolvePath,
+} from "@/react/router/navigation";
+import {
+ LoginRequestSchema,
+ SendEmailLoginCodeRequestSchema,
+ SignupRequestSchema,
+} from "@/types/proto-es/v1/auth_service_pb";
+import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";
+import type { User } from "@/types/proto-es/v1/user_service_pb";
+import { UNKNOWN_USER_NAME } from "@/types/v1/user";
+import { storageKeyResetPassword } from "@/utils/storage-keys";
import type { AppSliceCreator, AuthSlice } from "./types";
+// `users/{email}` → `{email}`.
+function emailOf(currentUserName: string | undefined): string {
+ if (!currentUserName) return "";
+ return currentUserName.startsWith("users/")
+ ? currentUserName.slice("users/".length)
+ : currentUserName;
+}
+
+function readResetPassword(email: string): boolean {
+ try {
+ return localStorage.getItem(storageKeyResetPassword(email)) === "true";
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Returns true if the user should be prompted to set up their profile.
+ * First-time login with an auto-generated name (email local-part or full
+ * email). Ported verbatim from the legacy Pinia auth store.
+ */
+function needsProfileSetup(user: User): boolean {
+ if (user.profile?.lastLoginTime) return false;
+ const name = user.title;
+ const email = user.email;
+ if (!name || !email) return false;
+ if (name === email) return true;
+ const atIndex = email.indexOf("@");
+ if (atIndex > 0 && name === email.substring(0, atIndex)) return true;
+ return false;
+}
+
export const createAuthSlice: AppSliceCreator<AuthSlice> = (set, get) => ({
+ unauthenticatedOccurred: false,
+ authSessionKey: uniqueId(),
+ isSelfEmailUpdate: false,
+
+ isLoggedIn: () => {
+ const name = get().currentUserName;
+ return Boolean(name) && name !== UNKNOWN_USER_NAME;
+ },
+
+ requireResetPassword: () => {
+ if (!get().isLoggedIn()) return false;
+ return readResetPassword(emailOf(get().currentUserName));
+ },
+
+ setRequireResetPassword: (value) => {
+ if (!get().isLoggedIn()) return;
+ try {
+ localStorage.setItem(
+ storageKeyResetPassword(emailOf(get().currentUserName)),
+ value ? "true" : "false"
+ );
+ } catch {
+ // localStorage unavailable (private mode / quota) — non-fatal.
+ }
+ },
+
+ setUnauthenticatedOccurred: (value) =>
+ set({ unauthenticatedOccurred: value }),
+
loadCurrentUser: async () => {
const existing = get().currentUser;
if (existing) return existing;
@@ -10,7 +97,11 @@ export const createAuthSlice: AppSliceCreator<AuthSlice> = (set, get) => ({
const request = userServiceClientConnect
.getCurrentUser({})
.then((user) => {
- set({ currentUser: user, currentUserRequest: undefined });
+ set({
+ currentUser: user,
+ currentUserName: user.name,
+ currentUserRequest: undefined,
+ });
return user;
})
.catch(() => {
@@ -24,13 +115,147 @@ export const createAuthSlice: AppSliceCreator<AuthSlice> = (set, get) => ({
return request;
},
- logout: async (signinUrl) => {
+ // Force re-fetch (mirrors the Pinia `fetchCurrentUser`, which always hits
+ // the server — login/signup need the fresh authenticated user).
+ fetchCurrentUser: async () => {
+ try {
+ const user = await userServiceClientConnect.getCurrentUser({});
+ set({ currentUser: user, currentUserName: user.name });
+ return user;
+ } catch {
+ return undefined;
+ }
+ },
+
+ // sometimes we have to redirect users even if we don't want to redirect them.
+ // for example, the user is forced to reset their password,
+ // or the user is using the LDAP to signin.
+ login: async ({ request, redirect = true, redirectUrl }) => {
+ const resp = await authServiceClientConnect.login(
+ create(LoginRequestSchema, { ...request, web: true }),
+ {
+ contextValues: createContextValues().set(ignoredCodesContextKey, [
+ Code.NotFound,
+ ]),
+ }
+ );
+ const getRedirectQuery = () =>
+ new URLSearchParams(window.location.search).get("redirect");
+ let nextPage = redirectUrl ?? (getRedirectQuery() || "/");
+ if (resp.mfaTempToken) {
+ set({ unauthenticatedOccurred: false });
+ navigateByName(AUTH_MFA_MODULE, {
+ query: { mfaTempToken: resp.mfaTempToken, redirect: nextPage },
+ });
+ return;
+ }
+
+ const user = await get().fetchCurrentUser();
+ set({ unauthenticatedOccurred: !user });
+ if (get().unauthenticatedOccurred) {
+ return;
+ }
+
+ get().setRequireResetPassword(resp.requireResetPassword);
+ await get().fetchServerInfo(user?.workspace);
+ // Re-fetch the current workspace now that we're authenticated.
+ await get().loadWorkspace();
+
+ // After user login, reset the auth session key.
+ set({ authSessionKey: uniqueId() });
+
+ if (
+ get().appFeatures["bb.feature.database-change-mode"] ===
+ DatabaseChangeMode.EDITOR
+ ) {
+ nextPage = resolvePath(SQL_EDITOR_HOME_MODULE);
+ }
+ if (resp.requireResetPassword) {
+ navigateByName(AUTH_PASSWORD_RESET_MODULE, {
+ query: { redirect: nextPage },
+ });
+ return;
+ }
+ if (get().isSaaSMode() && resp.user && needsProfileSetup(resp.user)) {
+ navigateByName(AUTH_PROFILE_SETUP_MODULE, {
+ query: { redirect: nextPage },
+ });
+ return;
+ }
+ if (redirect) {
+ navigateToPath(nextPage, { replace: true });
+ }
+ },
+
+ signup: async (request) => {
+ await authServiceClientConnect.signup(
+ create(SignupRequestSchema, {
+ email: request.email,
+ title: request.name,
+ password: request.password,
+ })
+ );
+
+ // Signup sets HTTP-only cookies automatically. Fetch the current user and
+ // proceed with the post-login flow.
+ const user = await get().fetchCurrentUser();
+ set({ unauthenticatedOccurred: !user });
+ if (get().unauthenticatedOccurred) {
+ return;
+ }
+
+ await get().fetchServerInfo(user?.workspace);
+ set({ authSessionKey: uniqueId() });
+
+ if (get().enableOnboarding()) {
+ navigateByName(SETUP_MODULE, { replace: true });
+ return;
+ }
+
+ const getRedirectQuery = () =>
+ new URLSearchParams(window.location.search).get("redirect");
+ let nextPage = getRedirectQuery() || "/";
+ if (
+ get().appFeatures["bb.feature.database-change-mode"] ===
+ DatabaseChangeMode.EDITOR
+ ) {
+ nextPage = resolvePath(SQL_EDITOR_HOME_MODULE);
+ }
+ navigateToPath(nextPage, { replace: true });
+ },
+
+ logout: async () => {
try {
await authServiceClientConnect.logout({});
} catch {
- // Ignore logout errors and clear the local session by redirecting anyway.
+ // nothing
} finally {
- window.location.href = signinUrl;
+ set({ unauthenticatedOccurred: false });
+ const pathname = location.pathname;
+ const getRedirectQuery = () =>
+ new URLSearchParams(window.location.search).get("redirect");
+ // Replace and reload the page to clear frontend state directly.
+ window.location.href = resolvePath(AUTH_SIGNIN_MODULE, {
+ query: {
+ redirect:
+ getRedirectQuery() ||
+ (pathname.startsWith("/auth") ? undefined : pathname),
+ },
+ });
}
},
+
+ sendEmailLoginCode: async (email, workspace) => {
+ await authServiceClientConnect.sendEmailLoginCode(
+ create(SendEmailLoginCodeRequestSchema, { email, workspace })
+ );
+ },
+
+ // Update currentUserName after a self email change. Sets the flag to
+ // suppress the "logged in as another user" notification.
+ updateCurrentUserNameForEmailChange: (newName) => {
+ set({ isSelfEmailUpdate: true, currentUserName: newName });
+ },
+
+ setIsSelfEmailUpdate: (value) => set({ isSelfEmailUpdate: value }),
});
diff --git a/frontend/src/react/stores/app/dbSchema.ts b/frontend/src/react/stores/app/dbSchema.ts
index 253adb8a48..cf85d25b9d 100644
--- a/frontend/src/react/stores/app/dbSchema.ts
+++ b/frontend/src/react/stores/app/dbSchema.ts
@@ -34,8 +34,8 @@ const cacheKey = (metadataName: string, filter: string, limit: number) =>
// same reference keeps `useAppStore((s) => s.getXxxMetadata(...))`
// selectors stable across renders so React's `Object.is` check doesn't
// fire on every unrelated store update. The legacy Pinia store created a
-// fresh proto each call, but Pinia consumers wrapped the call in
-// `usePiniaBridge` (Vue `watch`) which papered over the instability.
+// fresh proto each call, but its Vue-reactivity bridge papered over the
+// resulting instability.
const EMPTY_TABLE_METADATA: TableMetadata = createProto(
TableMetadataSchema,
{}
diff --git a/frontend/src/react/stores/app/iam.ts b/frontend/src/react/stores/app/iam.ts
index e4df22c64c..bce059415a 100644
--- a/frontend/src/react/stores/app/iam.ts
+++ b/frontend/src/react/stores/app/iam.ts
@@ -162,21 +162,6 @@ export const createIamSlice: AppSliceCreator<IamSlice> = (set, get) => ({
get().batchGetOrFetchGroups(groupMembers),
get().batchGetOrFetchUsers(userMembers),
]);
-
- // Bridge to the Pinia projectIamPolicy store so the legacy
- // `usePermissionStore.currentPermissionsInProjectV1` chain sees
- // the policy without a second fetch. Dynamic import to avoid a
- // static module-load cycle (Pinia projectIamPolicy transitively
- // imports `@/store` chains that would re-enter this app store).
- try {
- const { useProjectIamPolicyStore } = await import(
- "@/store/modules/v1/projectIamPolicy"
- );
- useProjectIamPolicyStore().setProjectIamPolicy(project, policy);
- } catch {
- // Pinia not available (e.g. some isolated test). Safe to ignore —
- // the app-store cache is already populated.
- }
return policy;
})
.catch(() => {
@@ -224,21 +209,24 @@ export const createIamSlice: AppSliceCreator<IamSlice> = (set, get) => ({
[project]: updated,
},
}));
- // Bridge to the Pinia projectIamPolicy store so the legacy
- // permission chain sees the updated policy. setProjectIamPolicy also
- // invalidates the Pinia permission cache by project. composePolicyBindings
- // refreshes the Pinia user / group / service-account / workload-identity
- // stores that getMemberBindings reads — without it the members table
- // could render stale titles for newly granted members.
- try {
- const { useProjectIamPolicyStore, composePolicyBindings } = await import(
- "@/store/modules/v1/projectIamPolicy"
- );
- useProjectIamPolicyStore().setProjectIamPolicy(project, updated);
- await composePolicyBindings(updated.bindings);
- } catch {
- // Pinia not available — app-store cache is already populated.
+ // Prefetch the updated policy's members into the app-store group/user
+ // caches so the members table (getMemberBindings) resolves titles for
+ // newly granted members without a stale render.
+ const groupMembers: string[] = [];
+ const userMembers: string[] = [];
+ for (const binding of updated.bindings) {
+ for (const member of binding.members) {
+ if (member.startsWith(groupBindingPrefix)) {
+ groupMembers.push(member);
+ } else {
+ userMembers.push(member);
+ }
+ }
}
+ await Promise.allSettled([
+ get().batchGetOrFetchGroups(groupMembers),
+ get().batchGetOrFetchUsers(userMembers),
+ ]);
return updated;
},
diff --git a/frontend/src/react/stores/app/index.ts b/frontend/src/react/stores/app/index.ts
index 06eae60d81..48d15bca91 100644
--- a/frontend/src/react/stores/app/index.ts
+++ b/frontend/src/react/stores/app/index.ts
@@ -38,6 +38,8 @@ export {
projectResourceNameFromId,
} from "./utils";
export type { ProjectListParams } from "./types";
+import { registerAppStoreUtilBridge } from "@/utils/app-store-bridge";
+import { registerPermissionCheckers } from "@/utils/iam/permission";
import type { AppStoreState } from "./types";
export const createAppStore = () =>
@@ -77,6 +79,40 @@ export const createAppStore = () =>
export const useAppStore = createAppStore();
+// Back the legacy `hasWorkspacePermissionV2` / `hasProjectPermissionV2` shared
+// utils with the app store, so all callers resolve permissions from this store
+// without importing it (which would create an init cycle through `@/utils`).
+registerPermissionCheckers({
+ hasWorkspacePermission: (permission) =>
+ useAppStore.getState().hasWorkspacePermission(permission),
+ hasProjectPermission: (project, permission) =>
+ useAppStore.getState().hasProjectPermission(project, permission),
+});
+
+// Back the subscription / environment reads in shared `@/utils` helpers with
+// this store, replacing the legacy Pinia stores those helpers used to read.
+registerAppStoreUtilBridge({
+ currentUser: () => useAppStore.getState().currentUser,
+ isLoggedIn: () => useAppStore.getState().isLoggedIn(),
+ setUnauthenticatedOccurred: (value) =>
+ useAppStore.getState().setUnauthenticatedOccurred(value),
+ defaultProjectName: () =>
+ useAppStore.getState().serverInfo?.defaultProject ?? "",
+ currentPlan: () => useAppStore.getState().currentPlan(),
+ hasFeature: (feature) => useAppStore.getState().hasFeature(feature),
+ environmentList: () => useAppStore.getState().environmentList,
+ getEnvironmentByName: (name, fallback) =>
+ useAppStore.getState().getEnvironmentByName(name, fallback),
+ roleList: () => useAppStore.getState().roleList,
+ getRoleByName: (name) => useAppStore.getState().getRoleByName(name),
+ getGroupByIdentifier: (identifier) =>
+ useAppStore.getState().getGroupByIdentifier(identifier),
+ workspaceRoleMapToUsers: () =>
+ useAppStore.getState().workspaceRoleMapToUsers(),
+ getProjectIamPolicy: (project) =>
+ useAppStore.getState().getProjectIamPolicy(project),
+});
+
export function isDefaultProjectName(name: string) {
return name === useAppStore.getState().serverInfo?.defaultProject;
}
diff --git a/frontend/src/react/stores/app/types.ts b/frontend/src/react/stores/app/types.ts
index ce251fdcc9..149384b3b8 100644
--- a/frontend/src/react/stores/app/types.ts
+++ b/frontend/src/react/stores/app/types.ts
@@ -7,6 +7,7 @@ import type { Permission } from "@/types/iam/permission";
import type { NotificationCreate } from "@/types/notification";
import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";
import type { ActuatorInfo } from "@/types/proto-es/v1/actuator_service_pb";
+import type { LoginRequest } from "@/types/proto-es/v1/auth_service_pb";
import type { Engine, State } from "@/types/proto-es/v1/common_pb";
import type { DatabaseCatalog } from "@/types/proto-es/v1/database_catalog_service_pb";
import type {
@@ -174,8 +175,28 @@ export type ListAccessGrantsParams = {
export type AuthSlice = {
currentUser?: User;
currentUserRequest?: Promise<User | undefined>;
+ // Resource name `users/{email}` of the signed-in user. Mirrors the legacy
+ // Pinia auth store's `currentUserName`; drives `isLoggedIn`.
+ currentUserName?: string;
+ unauthenticatedOccurred: boolean;
+ authSessionKey: string;
+ isSelfEmailUpdate: boolean;
loadCurrentUser: () => Promise<User | undefined>;
- logout: (signinUrl: string) => Promise<void>;
+ isLoggedIn: () => boolean;
+ requireResetPassword: () => boolean;
+ setRequireResetPassword: (value: boolean) => void;
+ setUnauthenticatedOccurred: (value: boolean) => void;
+ fetchCurrentUser: () => Promise<User | undefined>;
+ login: (params: {
+ request: LoginRequest;
+ redirect?: boolean;
+ redirectUrl?: string;
+ }) => Promise<void>;
+ signup: (request: Partial<User>) => Promise<void>;
+ logout: () => Promise<void>;
+ sendEmailLoginCode: (email: string, workspace?: string) => Promise<void>;
+ updateCurrentUserNameForEmailChange: (newName: string) => void;
+ setIsSelfEmailUpdate: (value: boolean) => void;
};
export type WorkspaceSlice = {
diff --git a/frontend/src/react/stores/app/workspace.ts b/frontend/src/react/stores/app/workspace.ts
index 767f01264a..0bc62f3a59 100644
--- a/frontend/src/react/stores/app/workspace.ts
+++ b/frontend/src/react/stores/app/workspace.ts
@@ -8,7 +8,6 @@ import {
authServiceClientConnect,
settingServiceClientConnect,
subscriptionServiceClientConnect,
- userServiceClientConnect,
workspaceServiceClientConnect,
} from "@/connect";
import { silentContextKey } from "@/connect/context-key";
@@ -43,7 +42,6 @@ import {
UpdateSettingRequestSchema,
WorkspaceProfileSettingSchema,
} from "@/types/proto-es/v1/setting_service_pb";
-import type { Subscription } from "@/types/proto-es/v1/subscription_service_pb";
import {
CancelPurchaseRequestSchema,
CreatePurchaseRequestSchema,
@@ -73,26 +71,6 @@ import {
import { formatAbsoluteDateTime } from "@/utils/datetime";
import type { AppSliceCreator, WorkspaceSlice } from "./types";
-// Propagate subscription updates to the parallel Pinia subscription
-// store. Without this, components that read feature gates via
-// `featureToRef` / `hasFeature` (Pinia path) stay stale after the user
-// uploads a license or completes a SaaS purchase — they would have to
-// refresh the page to see the new plan take effect. The Pinia store is
-// loaded lazily to avoid a static module cycle (`@/store/modules/v1/*`
-// transitively re-imports this app store).
-const syncSubscriptionToPinia = (subscription: Subscription): void => {
- void import("@/store/modules/v1/subscription").then(
- ({ useSubscriptionV1Store }) => {
- try {
- useSubscriptionV1Store().setSubscription(subscription);
- } catch {
- // Pinia not initialized yet (very early app boot); the Pinia
- // store reads from the same endpoint on its own first call.
- }
- }
- );
-};
-
// Listen on the shared cross-tab channel (see store/workspaceSwitchChannel.ts).
// Using `addEventListener` rather than `onmessage = ...` allows the Vue-side
// store to register its own handler on the same object, and source-object
@@ -236,14 +214,13 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (
},
loadWorkspace: async () => {
- // Always re-fetch currentUser to get the latest auth context.
- // The cached currentUser may be from before login (undefined or stale).
- const user = await userServiceClientConnect
- .getCurrentUser({})
- .catch(() => undefined);
- if (user) {
- set({ currentUser: user });
- }
+ // Resolve the authenticated user via the cached loader. It returns the
+ // existing currentUser when present (login / fetchCurrentUser refresh it
+ // on the auth transition), so we must NOT mint a fresh currentUser object
+ // here: a raw getCurrentUser() response is a new reference every call,
+ // which thrashes effects keyed on `currentUser` (e.g. AuthGate's mount
+ // gate) into an unmount/remount fetch loop.
+ const user = await get().loadCurrentUser();
const name =
user?.workspace ||
get().currentUser?.workspace ||
@@ -489,7 +466,6 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (
.getSubscription(createProto(GetSubscriptionRequestSchema, {}))
.then((subscription) => {
set({ subscription, subscriptionRequest: undefined });
- syncSubscriptionToPinia(subscription);
return subscription;
})
.catch(() => {
@@ -505,7 +481,6 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (
.getSubscription(createProto(GetSubscriptionRequestSchema, {}))
.then((subscription) => {
set({ subscription, subscriptionRequest: undefined });
- syncSubscriptionToPinia(subscription);
return subscription;
})
.catch(() => {
@@ -521,7 +496,6 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (
createProto(UploadLicenseRequestSchema, { license })
);
set({ subscription });
- syncSubscriptionToPinia(subscription);
return subscription;
},
@@ -818,7 +792,6 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (
setSubscription: (subscription) => {
set({ subscription });
- syncSubscriptionToPinia(subscription);
},
hasSplitInstanceLicense: () =>
diff --git a/frontend/src/router/auth.ts b/frontend/src/router/auth.ts
deleted file mode 100644
index 21a685d2e9..0000000000
--- a/frontend/src/router/auth.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import type { RouteRecordRaw } from "vue-router";
-import SplashLayout from "@/layouts/SplashLayout.vue";
-import { t } from "@/plugins/i18n";
-
-export const AUTH_SIGNIN_MODULE = "auth.signin";
-export const AUTH_SIGNIN_ADMIN_MODULE = "auth.signin.admin";
-export const AUTH_SIGNUP_MODULE = "auth.signup";
-export const AUTH_MFA_MODULE = "auth.mfa";
-export const AUTH_PASSWORD_RESET_MODULE = "auth.password.reset";
-export const AUTH_PASSWORD_FORGOT_MODULE = "auth.password.forgot";
-export const AUTH_OAUTH_CALLBACK_MODULE = "auth.oauth.callback";
-export const AUTH_OIDC_CALLBACK_MODULE = "auth.oidc.callback";
-export const AUTH_PROFILE_SETUP_MODULE = "auth.profile.setup";
-export const AUTH_2FA_SETUP_MODULE = "auth.2fa.setup";
-export const OAUTH2_CONSENT_MODULE = "oauth2.consent";
-
-// Every auth/consent route renders a React page mounted by ReactPageMount.vue.
-// The `page` prop names the React component registered in @/react/mount.ts.
-const reactPage = () => import("@/react/ReactPageMount.vue");
-
-const authRoutes: RouteRecordRaw[] = [
- {
- path: "/oauth2/consent",
- component: SplashLayout,
- children: [
- {
- path: "",
- name: OAUTH2_CONSENT_MODULE,
- meta: { title: () => t("oauth2.consent.title") },
- component: reactPage,
- props: { page: "OAuth2ConsentPage" },
- },
- ],
- },
- {
- path: "/auth",
- name: "auth",
- component: SplashLayout,
- children: [
- {
- path: "",
- alias: "signin",
- name: AUTH_SIGNIN_MODULE,
- meta: { title: () => t("common.sign-in") },
- component: reactPage,
- props: { page: "SigninPage" },
- },
- {
- // We need the admin as the backdoor for the workspace admin.
- path: "admin",
- name: AUTH_SIGNIN_ADMIN_MODULE,
- meta: { title: () => t("common.sign-in-as-admin") },
- component: reactPage,
- props: { page: "SigninAdminPage" },
- },
- {
- path: "signup",
- name: AUTH_SIGNUP_MODULE,
- meta: { title: () => t("common.sign-up") },
- component: reactPage,
- props: { page: "SignupPage" },
- },
- {
- path: "password-forgot",
- name: AUTH_PASSWORD_FORGOT_MODULE,
- meta: { title: () => `${t("auth.password-forgot")}` },
- component: reactPage,
- props: { page: "PasswordForgotPage" },
- },
- {
- path: "password-reset",
- name: AUTH_PASSWORD_RESET_MODULE,
- meta: { title: () => `${t("auth.password-reset.title")}` },
- component: reactPage,
- props: { page: "PasswordResetPage" },
- },
- {
- path: "mfa",
- name: AUTH_MFA_MODULE,
- meta: { title: () => t("multi-factor.self") },
- component: reactPage,
- props: { page: "MultiFactorPage" },
- },
- {
- path: "profile-setup",
- name: AUTH_PROFILE_SETUP_MODULE,
- meta: { title: () => t("auth.profile-setup") },
- component: reactPage,
- props: { page: "ProfileSetupPage" },
- },
- ],
- },
- {
- path: "/oauth/callback",
- name: AUTH_OAUTH_CALLBACK_MODULE,
- component: reactPage,
- props: { page: "OAuthCallbackPage" },
- },
- {
- path: "/oidc/callback",
- name: AUTH_OIDC_CALLBACK_MODULE,
- component: reactPage,
- props: { page: "OAuthCallbackPage" },
- },
- {
- path: "/2fa/setup",
- name: AUTH_2FA_SETUP_MODULE,
- meta: { title: () => t("two-factor.self") },
- component: reactPage,
- props: { page: "TwoFactorRequiredPage" },
- },
-];
-
-export default authRoutes;
diff --git a/frontend/src/router/dashboard/environmentV1.ts b/frontend/src/router/dashboard/environmentV1.ts
deleted file mode 100644
index e28c54ad67..0000000000
--- a/frontend/src/router/dashboard/environmentV1.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import type { RouteRecordRaw } from "vue-router";
-import { t } from "@/plugins/i18n";
-import { ENVIRONMENT_V1_ROUTE_DASHBOARD } from "./workspaceRoutes";
-
-export const ENVIRONMENT_V1_ROUTE_DETAIL = `${ENVIRONMENT_V1_ROUTE_DASHBOARD}.detail`;
-
-const environmentV1Routes: RouteRecordRaw[] = [
- {
- path: "environments/:environmentName",
- name: ENVIRONMENT_V1_ROUTE_DETAIL,
- meta: {
- title: () => t("common.environment"),
- requiredPermissionList: () => ["bb.settings.getEnvironment"],
- },
- redirect: (to) => ({
- name: ENVIRONMENT_V1_ROUTE_DASHBOARD,
- hash: `#${to.params.environmentName}`,
- }),
- },
-];
-
-export default environmentV1Routes;
diff --git a/frontend/src/router/dashboard/index.ts b/frontend/src/router/dashboard/index.ts
deleted file mode 100644
index 2fbc1c0957..0000000000
--- a/frontend/src/router/dashboard/index.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import type { RouteRecordRaw } from "vue-router";
-import BodyLayout from "@/layouts/BodyLayout.vue";
-import DashboardLayout from "@/layouts/DashboardLayout.vue";
-import { t } from "@/plugins/i18n";
-import environmentV1Routes from "./environmentV1";
-import instanceRoutes from "./instance";
-import projectV1Routes from "./projectV1";
-import workspaceRoutes from "./workspace";
-import { WORKSPACE_ROUTE_MY_ISSUES } from "./workspaceRoutes";
-import workspaceSettingRoutes from "./workspaceSetting";
-
-const dashboardRoutes: RouteRecordRaw[] = [
- {
- path: "/",
- component: DashboardLayout,
- children: [
- {
- path: "",
- components: { body: BodyLayout },
- children: [
- ...workspaceRoutes,
- ...workspaceSettingRoutes,
- ...environmentV1Routes,
- ...instanceRoutes,
- ...projectV1Routes,
- ],
- },
- {
- path: "issues",
- components: { body: () => import("@/react/ReactRouteShellBridge.vue") },
- props: {
- body: () => ({
- page: "IssuesRouteShell",
- routerViewName: "content",
- }),
- },
- meta: {
- title: () => t("common.issues"),
- },
- children: [
- {
- path: "",
- name: WORKSPACE_ROUTE_MY_ISSUES,
- components: {
- content: () => import("@/react/ReactPageMount.vue"),
- },
- props: {
- content: () => ({
- page: "MyIssuesPage",
- }),
- },
- },
- ],
- },
- ],
- },
-];
-
-export default dashboardRoutes;
diff --git a/frontend/src/router/dashboard/instance.ts b/frontend/src/router/dashboard/instance.ts
deleted file mode 100644
index bbde9c731f..0000000000
--- a/frontend/src/router/dashboard/instance.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import type { RouteLocationNormalized, RouteRecordRaw } from "vue-router";
-import { t } from "@/plugins/i18n";
-import { INSTANCE_ROUTE_DASHBOARD } from "./workspaceRoutes";
-
-export const INSTANCE_ROUTE_CREATE = `${INSTANCE_ROUTE_DASHBOARD}.create`;
-export const INSTANCE_ROUTE_DETAIL = `${INSTANCE_ROUTE_DASHBOARD}.detail`;
-export const INSTANCE_ROUTE_DATABASE_DETAIL = `${INSTANCE_ROUTE_DASHBOARD}.database.detail`;
-
-const instanceRoutes: RouteRecordRaw[] = [
- {
- path: "instances/new",
- name: INSTANCE_ROUTE_CREATE,
- meta: {
- title: () => t("instance.new-instance"),
- requiredPermissionList: () => ["bb.instances.create"],
- getQuickActionList: () => [],
- },
- components: {
- content: () => import("@/react/ReactPageMount.vue"),
- leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
- },
- props: {
- content: () => ({ page: "CreateInstancePage" }),
- },
- },
- {
- path: "instances/:instanceId",
- components: {
- content: () => import("@/react/ReactRouteShellBridge.vue"),
- leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
- },
- meta: {
- title: () => t("common.instance"),
- },
- props: {
- content: (route: RouteLocationNormalized) => ({
- page: "InstanceRouteShell",
- pageProps: {
- instanceId: route.params.instanceId,
- },
- }),
- },
- children: [
- {
- path: "",
- name: INSTANCE_ROUTE_DETAIL,
- meta: {
- requiredPermissionList: () => ["bb.instances.get"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "InstanceDetailPage",
- instanceId: route.params.instanceId,
- }),
- },
- {
- path: "databases/:databaseName",
- name: INSTANCE_ROUTE_DATABASE_DETAIL,
- meta: {
- requiredPermissionList: () => ["bb.projects.get", "bb.databases.get"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "InstanceDatabaseRedirectPage",
- instanceId: route.params.instanceId,
- databaseName: route.params.databaseName,
- }),
- },
- ],
- },
-];
-
-export default instanceRoutes;
diff --git a/frontend/src/router/dashboard/projectV1.ts b/frontend/src/router/dashboard/projectV1.ts
deleted file mode 100644
index 1461d5c983..0000000000
--- a/frontend/src/router/dashboard/projectV1.ts
+++ /dev/null
@@ -1,558 +0,0 @@
-import type { RouteLocationNormalized, RouteRecordRaw } from "vue-router";
-import { t } from "@/plugins/i18n";
-import ReactProjectSidebarMount from "@/react/ReactProjectSidebarMount.vue";
-import { PROJECT_V1_ROUTE_DASHBOARD } from "./workspaceRoutes";
-
-export const PROJECT_V1_ROUTE_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.detail`;
-export const PROJECT_V1_ROUTE_DATABASES = `${PROJECT_V1_ROUTE_DASHBOARD}.database`;
-export const PROJECT_V1_ROUTE_MASKING_EXEMPTION = `${PROJECT_V1_ROUTE_DASHBOARD}.masking-exemption`;
-export const PROJECT_V1_ROUTE_MASKING_EXEMPTION_CREATE = `${PROJECT_V1_ROUTE_DASHBOARD}.masking-exemption.create`;
-export const PROJECT_V1_ROUTE_DATABASE_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.database.detail`;
-export const PROJECT_V1_ROUTE_DATABASE_CHANGELOG_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.database.changelog.detail`;
-export const PROJECT_V1_ROUTE_DATABASE_REVISION_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.database.revision.detail`;
-export const PROJECT_V1_ROUTE_DATABASE_GROUPS = `${PROJECT_V1_ROUTE_DASHBOARD}.database-group`;
-export const PROJECT_V1_ROUTE_DATABASE_GROUPS_CREATE = `${PROJECT_V1_ROUTE_DASHBOARD}.database-group.create`;
-export const PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.database-group.detail`;
-export const PROJECT_V1_ROUTE_ISSUES = `${PROJECT_V1_ROUTE_DASHBOARD}.issue`;
-export const PROJECT_V1_ROUTE_ISSUE_DETAIL = `${PROJECT_V1_ROUTE_ISSUES}.detail`;
-export const PROJECT_V1_ROUTE_PLANS = `${PROJECT_V1_ROUTE_DASHBOARD}.plan`;
-export const PROJECT_V1_ROUTE_PLAN_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.plan.detail`;
-export const PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS = `${PROJECT_V1_ROUTE_PLAN_DETAIL}.specs`;
-export const PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL = `${PROJECT_V1_ROUTE_PLAN_DETAIL}.spec.detail`;
-export const PROJECT_V1_ROUTE_SYNC_SCHEMA = `${PROJECT_V1_ROUTE_DASHBOARD}.sync-schema`;
-export const PROJECT_V1_ROUTE_AUDIT_LOGS = `${PROJECT_V1_ROUTE_DASHBOARD}.audit-logs`;
-export const PROJECT_V1_ROUTE_WEBHOOKS = `${PROJECT_V1_ROUTE_DASHBOARD}.webhook`;
-export const PROJECT_V1_ROUTE_WEBHOOK_CREATE = `${PROJECT_V1_ROUTE_DASHBOARD}.webhook.create`;
-export const PROJECT_V1_ROUTE_WEBHOOK_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.webhook.detail`;
-export const PROJECT_V1_ROUTE_ACCESS_GRANTS = `${PROJECT_V1_ROUTE_DASHBOARD}.access-grants`;
-export const PROJECT_V1_ROUTE_MEMBERS = `${PROJECT_V1_ROUTE_DASHBOARD}.members`;
-export const PROJECT_V1_ROUTE_SERVICE_ACCOUNTS = `${PROJECT_V1_ROUTE_DASHBOARD}.service-accounts`;
-export const PROJECT_V1_ROUTE_WORKLOAD_IDENTITIES = `${PROJECT_V1_ROUTE_DASHBOARD}.workload-identities`;
-export const PROJECT_V1_ROUTE_SETTINGS = `${PROJECT_V1_ROUTE_DASHBOARD}.settings`;
-export const PROJECT_V1_ROUTE_DATA_EXPORT = `${PROJECT_V1_ROUTE_DASHBOARD}.data-export`;
-export const PROJECT_V1_ROUTE_RELEASES = `${PROJECT_V1_ROUTE_DASHBOARD}.release`;
-export const PROJECT_V1_ROUTE_RELEASE_DETAIL = `${PROJECT_V1_ROUTE_DASHBOARD}.release.detail`;
-export const PROJECT_V1_ROUTE_ROLLOUTS = `${PROJECT_V1_ROUTE_DASHBOARD}.rollouts`;
-export const PROJECT_V1_ROUTE_PLAN_ROLLOUT = `${PROJECT_V1_ROUTE_ROLLOUTS}.rollout`;
-export const PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE = `${PROJECT_V1_ROUTE_PLAN_ROLLOUT}.stage`;
-export const PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK = `${PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE}.task`;
-export const PROJECT_V1_ROUTE_GITOPS = `${PROJECT_V1_ROUTE_DASHBOARD}.gitops`;
-
-const planDetailComponent = () => import("@/react/ReactPageMount.vue");
-
-const planDetailMeta: RouteRecordRaw["meta"] = {
- requiredPermissionList: () => [
- "bb.plans.get",
- "bb.planCheckRuns.get",
- "bb.taskRuns.list",
- ],
-};
-
-// Plan Detail Page — standalone layout, decoupled from Issue
-// All three routes render the same component; route name determines
-// whether changes section is auto-expanded and which spec is selected.
-const planRoutes: RouteRecordRaw[] = [
- {
- path: "plans/:planId",
- name: PROJECT_V1_ROUTE_PLAN_DETAIL,
- component: planDetailComponent,
- meta: planDetailMeta,
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectPlanDetailPage",
- routeName: route.name?.toString(),
- routeQuery: route.query,
- ...route.params,
- }),
- },
- {
- path: "plans/:planId/specs",
- name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,
- component: planDetailComponent,
- meta: planDetailMeta,
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectPlanDetailPage",
- routeName: route.name?.toString(),
- routeQuery: route.query,
- ...route.params,
- }),
- },
- {
- path: "plans/:planId/specs/:specId",
- name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
- component: planDetailComponent,
- meta: planDetailMeta,
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectPlanDetailPage",
- routeName: route.name?.toString(),
- routeQuery: route.query,
- ...route.params,
- }),
- },
-];
-
-// Issue routes
-const issueRoutes: RouteRecordRaw[] = [
- {
- path: "issues/:issueId(\\d+)",
- name: PROJECT_V1_ROUTE_ISSUE_DETAIL,
- meta: {
- requiredPermissionList: () => ["bb.issues.get"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectIssueDetailPage",
- ...route.params,
- }),
- },
-];
-
-// Legacy rollout paths → redirect to the canonical Plan Detail deploy view.
-const rolloutRoutes: RouteRecordRaw[] = [
- {
- path: "plans/:planId/rollout",
- name: PROJECT_V1_ROUTE_PLAN_ROLLOUT,
- redirect: (to) => ({
- name: PROJECT_V1_ROUTE_PLAN_DETAIL,
- params: { projectId: to.params.projectId, planId: to.params.planId },
- query: { phase: "deploy" },
- }),
- },
- {
- path: "plans/:planId/rollout/stages/:stageId",
- name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE,
- redirect: (to) => ({
- name: PROJECT_V1_ROUTE_PLAN_DETAIL,
- params: { projectId: to.params.projectId, planId: to.params.planId },
- query: { phase: "deploy", stageId: to.params.stageId },
- }),
- },
- {
- path: "plans/:planId/rollout/stages/:stageId/tasks/:taskId",
- name: PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK,
- redirect: (to) => ({
- name: PROJECT_V1_ROUTE_PLAN_DETAIL,
- params: { projectId: to.params.projectId, planId: to.params.planId },
- query: {
- phase: "deploy",
- stageId: to.params.stageId,
- taskId: to.params.taskId,
- },
- }),
- },
-];
-
-const projectV1Routes: RouteRecordRaw[] = [
- {
- path: "projects/:projectId",
- components: {
- content: () => import("@/react/ReactRouteShellBridge.vue"),
- leftSidebar: ReactProjectSidebarMount,
- },
- props: {
- content: (route: RouteLocationNormalized) => ({
- page: "ProjectRouteShell",
- pageProps: {
- projectId: route.params.projectId,
- },
- }),
- leftSidebar: true,
- },
- meta: {
- requiredPermissionList: () => ["bb.projects.get"],
- },
- children: [
- {
- path: "",
- name: PROJECT_V1_ROUTE_DETAIL,
- // Redirect to the issues page synchronously via beforeEnter instead
- // of rendering ProjectLandingPage (which did an async useEffect →
- // router.replace that raced with ReactPageMount's render queue).
- redirect: (to) => ({
- name: PROJECT_V1_ROUTE_ISSUES,
- params: to.params,
- }),
- },
- {
- path: "databases",
- name: PROJECT_V1_ROUTE_DATABASES,
- meta: {
- title: () => t("common.databases"),
- requiredPermissionList: () => ["bb.databases.list"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectDatabasesPage",
- ...route.params,
- }),
- },
- {
- path: "access-grants",
- name: PROJECT_V1_ROUTE_ACCESS_GRANTS,
- meta: {
- title: () => t("sql-editor.access-grants"),
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectAccessGrantsPage",
- ...route.params,
- }),
- },
- {
- path: "masking-exemption",
- meta: {
- title: () => t("project.masking-exemption.self"),
- },
- props: true,
- children: [
- {
- path: "",
- name: PROJECT_V1_ROUTE_MASKING_EXEMPTION,
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectMaskingExemptionPage",
- ...route.params,
- }),
- meta: {
- requiredPermissionList: () => [
- "bb.databases.get",
- "bb.policies.getMaskingExemptionPolicy",
- ],
- },
- },
- {
- path: "create",
- name: PROJECT_V1_ROUTE_MASKING_EXEMPTION_CREATE,
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectMaskingExemptionCreatePage",
- ...route.params,
- }),
- meta: {
- requiredPermissionList: () => [
- "bb.policies.createMaskingExemptionPolicy",
- "bb.policies.updateMaskingExemptionPolicy",
- "bb.databases.list",
- "bb.databaseCatalogs.get",
- ],
- },
- },
- ],
- },
- {
- path: "database-groups",
- meta: {
- title: () => t("common.groups"),
- },
- props: true,
- children: [
- {
- path: "",
- name: PROJECT_V1_ROUTE_DATABASE_GROUPS,
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectDatabaseGroupsPage",
- ...route.params,
- }),
- meta: {
- requiredPermissionList: () => ["bb.databaseGroups.list"],
- },
- },
- {
- path: "create",
- name: PROJECT_V1_ROUTE_DATABASE_GROUPS_CREATE,
- meta: {
- requiredPermissionList: () => [
- "bb.databaseGroups.create",
- "bb.databases.list",
- ],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectDatabaseGroupCreatePage",
- ...route.params,
- }),
- },
- {
- path: ":databaseGroupName",
- name: PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectDatabaseGroupDetailPage",
- ...route.params,
- }),
- meta: {
- requiredPermissionList: () => [
- "bb.databaseGroups.get",
- "bb.databases.list",
- ],
- },
- },
- ],
- },
- {
- path: "issues",
- name: PROJECT_V1_ROUTE_ISSUES,
- meta: {
- title: () => t("common.issues"),
- requiredPermissionList: () => ["bb.issues.list"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectIssueDashboardPage",
- ...route.params,
- }),
- },
- {
- path: "plans",
- name: PROJECT_V1_ROUTE_PLANS,
- meta: {
- title: () => t("plan.plans"),
- requiredPermissionList: () => ["bb.databases.list", "bb.plans.list"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectPlanDashboardPage",
- ...route.params,
- }),
- },
- {
- path: "sync-schema",
- name: PROJECT_V1_ROUTE_SYNC_SCHEMA,
- meta: {
- title: () => t("database.sync-schema.title"),
- requiredPermissionList: () => [
- "bb.databases.sync",
- "bb.databases.list",
- "bb.databases.get",
- "bb.databases.getSchema",
- "bb.changelogs.get",
- ],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectSyncSchemaPage",
- ...route.params,
- }),
- },
- {
- path: "audit-logs",
- name: PROJECT_V1_ROUTE_AUDIT_LOGS,
- meta: {
- title: () => t("settings.sidebar.audit-log"),
- requiredPermissionList: () => ["bb.auditLogs.search"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectAuditLogPage",
- ...route.params,
- }),
- },
- {
- path: "webhooks",
- meta: {
- title: () => t("common.webhooks"),
- },
- children: [
- {
- path: "",
- name: PROJECT_V1_ROUTE_WEBHOOKS,
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectWebhooksPage",
- ...route.params,
- }),
- },
- {
- path: "new",
- name: PROJECT_V1_ROUTE_WEBHOOK_CREATE,
- meta: {
- title: () => t("project.webhook.create-webhook"),
- requiredPermissionList: () => ["bb.projects.update"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectWebhookCreatePage",
- ...route.params,
- }),
- },
- {
- path: ":webhookResourceId",
- name: PROJECT_V1_ROUTE_WEBHOOK_DETAIL,
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectWebhookDetailPage",
- ...route.params,
- }),
- },
- ],
- },
- {
- path: "members",
- name: PROJECT_V1_ROUTE_MEMBERS,
- meta: {
- title: () => t("common.members", 2 /* multiply*/),
- requiredPermissionList: () => ["bb.projects.getIamPolicy"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "MembersPage",
- ...route.params,
- }),
- },
- {
- path: "service-accounts",
- name: PROJECT_V1_ROUTE_SERVICE_ACCOUNTS,
- meta: {
- title: () => t("settings.members.service-accounts"),
- requiredPermissionList: () => ["bb.serviceAccounts.list"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ServiceAccountsPage",
- ...route.params,
- }),
- },
- {
- path: "workload-identities",
- name: PROJECT_V1_ROUTE_WORKLOAD_IDENTITIES,
- meta: {
- title: () => t("settings.members.workload-identities"),
- requiredPermissionList: () => ["bb.workloadIdentities.list"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "WorkloadIdentitiesPage",
- ...route.params,
- }),
- },
- {
- path: "settings",
- name: PROJECT_V1_ROUTE_SETTINGS,
- meta: {
- title: () => t("common.settings"),
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "ProjectSettingsPage" }),
- },
- {
- path: "instances/:instanceId/databases/:databaseName",
- name: PROJECT_V1_ROUTE_DATABASE_DETAIL,
- meta: {
- title: () => t("common.database"),
- requiredPermissionList: () => ["bb.databases.get"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectDatabaseDetailPage",
- ...route.params,
- hash: route.hash,
- query: route.query,
- }),
- },
- {
- path: "instances/:instanceId/databases/:databaseName/changelogs/:changelogId",
- name: PROJECT_V1_ROUTE_DATABASE_CHANGELOG_DETAIL,
- meta: {
- title: () => t("common.database"),
- requiredPermissionList: () => [
- "bb.databases.get",
- "bb.changelogs.get",
- ],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "DatabaseChangelogDetailPage",
- ...route.params,
- project: `projects/${route.params.projectId}`,
- instance: `instances/${route.params.instanceId}`,
- database: `instances/${route.params.instanceId}/databases/${route.params.databaseName}`,
- changelogId: route.params.changelogId,
- }),
- },
- {
- path: "instances/:instanceId/databases/:databaseName/revisions/:revisionId",
- name: PROJECT_V1_ROUTE_DATABASE_REVISION_DETAIL,
- meta: {
- title: () => t("common.database"),
- requiredPermissionList: () => ["bb.databases.get"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "DatabaseRevisionDetailPage",
- ...route.params,
- project: `projects/${route.params.projectId}`,
- instance: `instances/${route.params.instanceId}`,
- database: `instances/${route.params.instanceId}/databases/${route.params.databaseName}`,
- revisionId: route.params.revisionId,
- }),
- },
- {
- path: "data-export",
- name: PROJECT_V1_ROUTE_DATA_EXPORT,
- meta: {
- title: () => t("export-center.self"),
- requiredPermissionList: () => ["bb.issues.list", "bb.databases.list"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route) => ({
- page: "ProjectDataExportPage",
- ...route.params,
- }),
- },
- {
- path: "releases",
- meta: {
- title: () => t("release.releases"),
- },
- props: true,
- children: [
- {
- path: "",
- name: PROJECT_V1_ROUTE_RELEASES,
- meta: {
- requiredPermissionList: () => ["bb.releases.list"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectReleaseDashboardPage",
- ...route.params,
- }),
- },
- {
- path: ":releaseId",
- name: PROJECT_V1_ROUTE_RELEASE_DETAIL,
- meta: {
- requiredPermissionList: () => ["bb.releases.get"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectReleaseDetailPage",
- ...route.params,
- }),
- },
- ],
- },
- {
- path: "gitops",
- name: PROJECT_V1_ROUTE_GITOPS,
- meta: {
- title: () => t("gitops.self"),
- requiredPermissionList: () => [
- "bb.workloadIdentities.list",
- "bb.databases.list",
- ],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "ProjectGitOpsPage",
- ...route.params,
- }),
- },
- ...planRoutes,
- ...issueRoutes,
- ...rolloutRoutes,
- ],
- },
-];
-
-export default projectV1Routes;
diff --git a/frontend/src/router/dashboard/projectV1RouteHelpers.ts b/frontend/src/router/dashboard/projectV1RouteHelpers.ts
deleted file mode 100644
index 21cb317a32..0000000000
--- a/frontend/src/router/dashboard/projectV1RouteHelpers.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-import type {
- LocationQueryValue,
- RouteLocationNormalizedLoaded,
- RouteLocationRaw,
-} from "vue-router";
-import {
- extractPlanUID,
- extractPlanUIDFromRolloutName,
- extractProjectResourceName,
- extractStageNameFromTaskName,
- extractStageUID,
- extractTaskUID,
-} from "@/utils";
-import {
- PROJECT_V1_ROUTE_PLAN_DETAIL,
- PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
-} from "./projectV1";
-
-export const PLAN_DETAIL_PHASE_CHANGES = "changes";
-export const PLAN_DETAIL_PHASE_REVIEW = "review";
-export const PLAN_DETAIL_PHASE_DEPLOY = "deploy";
-
-export const getRouteQueryString = (
- value?: LocationQueryValue | LocationQueryValue[]
-): string | undefined => {
- if (typeof value === "string") {
- return value;
- }
- if (Array.isArray(value)) {
- return typeof value[0] === "string" ? value[0] : undefined;
- }
- return undefined;
-};
-
-type BuildPlanDeployRouteParams = {
- projectId: string;
- planId: string;
- stageId?: string;
- taskId?: string;
-};
-
-export const buildPlanDeployRoute = ({
- projectId,
- planId,
- stageId,
- taskId,
-}: BuildPlanDeployRouteParams): RouteLocationRaw => {
- return {
- name: PROJECT_V1_ROUTE_PLAN_DETAIL,
- params: { projectId, planId },
- query: {
- phase: PLAN_DETAIL_PHASE_DEPLOY,
- ...(stageId ? { stageId } : {}),
- ...(taskId ? { taskId } : {}),
- },
- };
-};
-
-export const buildSpecDetailRouteForCurrentPage = (
- currentRoute: Pick<RouteLocationNormalizedLoaded, "params" | "query">,
- specId: string
-): RouteLocationRaw => {
- return {
- name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
- params: {
- ...(currentRoute.params || {}),
- specId,
- },
- query: currentRoute.query || {},
- };
-};
-
-export const buildPlanDeployRouteFromPlanName = (
- planName: string,
- options?: Omit<BuildPlanDeployRouteParams, "projectId" | "planId">
-): RouteLocationRaw => {
- return buildPlanDeployRoute({
- projectId: extractProjectResourceName(planName),
- planId: extractPlanUID(planName) || "_",
- ...options,
- });
-};
-
-export const buildPlanDeployRouteFromRolloutName = (
- rolloutName: string,
- options?: Omit<BuildPlanDeployRouteParams, "projectId" | "planId">
-): RouteLocationRaw => {
- return buildPlanDeployRoute({
- projectId: extractProjectResourceName(rolloutName),
- planId: extractPlanUIDFromRolloutName(rolloutName) || "_",
- ...options,
- });
-};
-
-export const buildTaskDetailRoute = (taskName: string): RouteLocationRaw => {
- const stageName = extractStageNameFromTaskName(taskName);
-
- return buildPlanDeployRoute({
- projectId: extractProjectResourceName(taskName),
- planId: extractPlanUIDFromRolloutName(taskName) || "-",
- stageId: extractStageUID(stageName) || "-",
- taskId: extractTaskUID(taskName) || "-",
- });
-};
-
-export const buildStageRoute = (stageName: string): RouteLocationRaw => {
- return buildPlanDeployRoute({
- projectId: extractProjectResourceName(stageName),
- planId: extractPlanUIDFromRolloutName(stageName) || "_",
- stageId: extractStageUID(stageName) || "_",
- });
-};
diff --git a/frontend/src/router/dashboard/workspace.ts b/frontend/src/router/dashboard/workspace.ts
deleted file mode 100644
index 48b0dc41a5..0000000000
--- a/frontend/src/router/dashboard/workspace.ts
+++ /dev/null
@@ -1,432 +0,0 @@
-import type { RouteLocationNormalized, RouteRecordRaw } from "vue-router";
-import DummyRootView from "@/DummyRootView";
-import { t } from "@/plugins/i18n";
-import {
- DATABASE_ROUTE_DASHBOARD,
- ENVIRONMENT_V1_ROUTE_DASHBOARD,
- INSTANCE_ROUTE_DASHBOARD,
- PROJECT_V1_ROUTE_DASHBOARD,
- WORKSPACE_ROOT_MODULE,
- WORKSPACE_ROUTE_403,
- WORKSPACE_ROUTE_404,
- WORKSPACE_ROUTE_AUDIT_LOG,
- WORKSPACE_ROUTE_CUSTOM_APPROVAL,
- WORKSPACE_ROUTE_DATA_CLASSIFICATION,
- WORKSPACE_ROUTE_GLOBAL_MASKING,
- WORKSPACE_ROUTE_GROUPS,
- WORKSPACE_ROUTE_IDENTITY_PROVIDER_DETAIL,
- WORKSPACE_ROUTE_IDENTITY_PROVIDERS,
- WORKSPACE_ROUTE_IM,
- WORKSPACE_ROUTE_LANDING,
- WORKSPACE_ROUTE_MCP,
- WORKSPACE_ROUTE_MEMBERS,
- WORKSPACE_ROUTE_RISK_ASSESSMENT,
- WORKSPACE_ROUTE_ROLES,
- WORKSPACE_ROUTE_SEMANTIC_TYPES,
- WORKSPACE_ROUTE_SERVICE_ACCOUNTS,
- WORKSPACE_ROUTE_SQL_REVIEW,
- WORKSPACE_ROUTE_SQL_REVIEW_CREATE,
- WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,
- WORKSPACE_ROUTE_USER_PROFILE,
- WORKSPACE_ROUTE_USERS,
- WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,
-} from "./workspaceRoutes";
-
-const rootRoute: RouteRecordRaw = {
- path: "",
- name: WORKSPACE_ROOT_MODULE,
- components: {
- content: DummyRootView,
- },
-};
-
-const workspaceRoutes: RouteRecordRaw[] = [
- rootRoute,
- {
- path: "landing",
- name: WORKSPACE_ROUTE_LANDING,
- meta: {
- title: () => t("common.home"),
- },
- components: {
- content: () => import("@/react/LandingPageMount.vue"),
- leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
- },
- },
- {
- path: "projects",
- name: PROJECT_V1_ROUTE_DASHBOARD,
- meta: {
- title: () => t("common.projects"),
- },
- components: {
- content: () => import("@/react/ReactPageMount.vue"),
- leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
- },
- props: {
- content: () => ({ page: "ProjectsPage" }),
- leftSidebar: true,
- },
- },
- {
- path: "instances",
- name: INSTANCE_ROUTE_DASHBOARD,
- meta: {
- title: () => t("common.instances"),
- requiredPermissionList: () => ["bb.instances.list"],
- },
- components: {
- content: () => import("@/react/ReactPageMount.vue"),
- leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
- },
- props: {
- content: () => ({ page: "InstancesPage" }),
- leftSidebar: true,
- },
- },
- {
- path: "databases",
- name: DATABASE_ROUTE_DASHBOARD,
- meta: {
- title: () => t("common.databases"),
- requiredPermissionList: () => ["bb.databases.list"],
- },
- components: {
- content: () => import("@/react/ReactPageMount.vue"),
- leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
- },
- props: {
- content: () => ({ page: "DatabasesPage" }),
- leftSidebar: true,
- },
- },
- {
- path: "environments",
- name: ENVIRONMENT_V1_ROUTE_DASHBOARD,
- meta: {
- title: () => t("common.environments"),
- requiredPermissionList: () => ["bb.settings.getEnvironment"],
- },
- components: {
- content: () => import("@/react/ReactPageMount.vue"),
- leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
- },
- props: {
- content: () => ({ page: "EnvironmentsPage" }),
- leftSidebar: true,
- },
- },
- {
- path: "users/:principalEmail",
- name: WORKSPACE_ROUTE_USER_PROFILE,
- components: {
- content: () => import("@/react/ReactPageMount.vue"),
- leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
- },
- props: {
- content: (route: RouteLocationNormalized) => ({
- page: "ProfilePage",
- principalEmail: route.params.principalEmail,
- }),
- leftSidebar: true,
- },
- },
- {
- path: "403",
- name: WORKSPACE_ROUTE_403,
- meta: {
- title: () => t("error-page.forbidden"),
- },
- components: {
- content: () => import("@/react/ReactPageMount.vue"),
- leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
- },
- props: {
- content: () => ({ page: "Page403" }),
- leftSidebar: true,
- },
- },
- {
- path: "404",
- name: WORKSPACE_ROUTE_404,
- meta: {
- title: () => t("error-page.not-found"),
- },
- components: {
- content: () => import("@/react/ReactPageMount.vue"),
- leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
- },
- props: {
- content: () => ({ page: "Page404" }),
- leftSidebar: true,
- },
- },
- {
- path: "sql-review",
- meta: {
- title: () => t("sql-review.title"),
- overrideDocumentTitle: true,
- },
- components: {
- content: () => import("@/react/ReactRouteShellBridge.vue"),
- leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
- },
- props: {
- content: () => ({
- page: "SettingRouteShell",
- }),
- leftSidebar: true,
- },
- children: [
- {
- path: "",
- name: WORKSPACE_ROUTE_SQL_REVIEW,
- meta: {
- title: () => t("sql-review.title"),
- requiredPermissionList: () => [
- "bb.reviewConfigs.list",
- "bb.policies.get",
- ],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "SQLReviewPage" }),
- },
- {
- path: "new",
- name: WORKSPACE_ROUTE_SQL_REVIEW_CREATE,
- meta: {
- title: () => t("sql-review.create.breadcrumb"),
- requiredPermissionList: () => ["bb.reviewConfigs.create"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "SQLReviewCreatePage" }),
- },
- {
- path: ":sqlReviewPolicySlug",
- name: WORKSPACE_ROUTE_SQL_REVIEW_DETAIL,
- meta: {
- title: () => t("sql-review.title"),
- requiredPermissionList: () => [
- "bb.reviewConfigs.get",
- "bb.policies.get",
- ],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: (route: RouteLocationNormalized) => ({
- page: "SQLReviewDetailPage",
- ...route.params,
- }),
- },
- ],
- },
- {
- path: "idps",
- meta: {
- title: () => t("settings.sidebar.sso"),
- requiredPermissionList: () => ["bb.identityProviders.get"],
- overrideDocumentTitle: true,
- },
- components: {
- content: () => import("@/react/ReactRouteShellBridge.vue"),
- leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
- },
- props: {
- content: () => ({
- page: "SettingRouteShell",
- }),
- leftSidebar: true,
- },
- children: [
- {
- path: "",
- name: WORKSPACE_ROUTE_IDENTITY_PROVIDERS,
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "IDPsPage" }),
- },
- {
- path: ":idpId",
- name: WORKSPACE_ROUTE_IDENTITY_PROVIDER_DETAIL,
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "IDPDetailPage" }),
- },
- ],
- },
- {
- path: "",
- meta: {
- overrideDocumentTitle: true,
- },
- components: {
- content: () => import("@/react/ReactRouteShellBridge.vue"),
- leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
- },
- props: {
- content: () => ({
- page: "SettingRouteShell",
- }),
- leftSidebar: true,
- },
- children: [
- {
- path: "risk-assessment",
- name: WORKSPACE_ROUTE_RISK_ASSESSMENT,
- meta: {
- title: () => t("custom-approval.risk.self"),
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "RiskAssessmentPage" }),
- },
- {
- path: "custom-approval",
- name: WORKSPACE_ROUTE_CUSTOM_APPROVAL,
- meta: {
- title: () => t("custom-approval.self"),
- requiredPermissionList: () => ["bb.settings.get"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "CustomApprovalPage" }),
- },
- {
- path: "global-masking",
- name: WORKSPACE_ROUTE_GLOBAL_MASKING,
- meta: {
- title: () => t("settings.sidebar.global-masking"),
- requiredPermissionList: () => ["bb.policies.getMaskingRulePolicy"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "GlobalMaskingPage" }),
- },
- {
- path: "semantic-types",
- name: WORKSPACE_ROUTE_SEMANTIC_TYPES,
- meta: {
- title: () => t("settings.sensitive-data.semantic-types.self"),
- requiredPermissionList: () => ["bb.settings.get"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "SemanticTypesPage" }),
- },
- {
- path: "data-classification",
- name: WORKSPACE_ROUTE_DATA_CLASSIFICATION,
- meta: {
- title: () => t("settings.sidebar.data-classification"),
- requiredPermissionList: () => ["bb.settings.get"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "DataClassificationPage" }),
- },
- {
- path: "audit-log",
- name: WORKSPACE_ROUTE_AUDIT_LOG,
- meta: {
- title: () => t("settings.sidebar.audit-log"),
- requiredPermissionList: () => ["bb.auditLogs.search"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "AuditLogPage" }),
- },
- {
- path: "users",
- name: WORKSPACE_ROUTE_USERS,
- meta: {
- title: () => t("common.users"),
- requiredPermissionList: () => ["bb.users.list"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "UsersPage" }),
- },
- {
- path: "service-accounts",
- name: WORKSPACE_ROUTE_SERVICE_ACCOUNTS,
- meta: {
- title: () => t("settings.members.service-accounts"),
- requiredPermissionList: () => ["bb.serviceAccounts.list"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "ServiceAccountsPage" }),
- },
- {
- path: "workload-identities",
- name: WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,
- meta: {
- title: () => t("settings.members.workload-identities"),
- requiredPermissionList: () => ["bb.workloadIdentities.list"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "WorkloadIdentitiesPage" }),
- },
- {
- path: "members",
- name: WORKSPACE_ROUTE_MEMBERS,
- meta: {
- title: () => t("settings.sidebar.members"),
- requiredPermissionList: () => ["bb.workspaces.getIamPolicy"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "MembersPage" }),
- },
- {
- path: "groups",
- name: WORKSPACE_ROUTE_GROUPS,
- meta: {
- title: () => t("settings.members.groups.self"),
- requiredPermissionList: () => ["bb.groups.list"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "GroupsPage" }),
- },
- {
- path: "roles",
- name: WORKSPACE_ROUTE_ROLES,
- meta: {
- title: () => t("settings.sidebar.custom-roles"),
- requiredPermissionList: () => ["bb.roles.list"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "RolesPage" }),
- },
- ],
- },
- {
- path: "integration",
- meta: {
- title: () => t("settings.sidebar.integration"),
- overrideDocumentTitle: true,
- },
- components: {
- content: () => import("@/react/ReactRouteShellBridge.vue"),
- leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
- },
- props: {
- content: () => ({
- page: "SettingRouteShell",
- }),
- leftSidebar: true,
- },
- children: [
- {
- path: "im",
- name: WORKSPACE_ROUTE_IM,
- meta: {
- title: () => t("settings.sidebar.im-integration"),
- requiredPermissionList: () => ["bb.settings.get"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "IMPage" }),
- },
- {
- path: "mcp",
- name: WORKSPACE_ROUTE_MCP,
- meta: {
- title: () => t("settings.sidebar.mcp"),
- requiredPermissionList: () => ["bb.settings.get"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "MCPPage" }),
- },
- ],
- },
-];
-
-export default workspaceRoutes;
diff --git a/frontend/src/router/dashboard/workspaceRoutes.ts b/frontend/src/router/dashboard/workspaceRoutes.ts
deleted file mode 100644
index 6a4eb56441..0000000000
--- a/frontend/src/router/dashboard/workspaceRoutes.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-export const WORKSPACE_ROOT_MODULE = "workspace.root";
-export const WORKSPACE_ROUTE_LANDING = "workspace.landing";
-export const WORKSPACE_ROUTE_MY_ISSUES = "workspace.my-issues";
-export const WORKSPACE_ROUTE_DATA_EXPORT = "workspace.data-export";
-export const WORKSPACE_ROUTE_USER_PROFILE = "workspace.user-profile";
-
-export const DATABASE_ROUTE_DASHBOARD = "workspace.database";
-export const INSTANCE_ROUTE_DASHBOARD = "workspace.instance";
-export const PROJECT_V1_ROUTE_DASHBOARD = "workspace.project";
-export const ENVIRONMENT_V1_ROUTE_DASHBOARD = "workspace.environment";
-
-export const WORKSPACE_ROUTE_SQL_REVIEW = "workspace.sql-review";
-export const WORKSPACE_ROUTE_SQL_REVIEW_CREATE = `${WORKSPACE_ROUTE_SQL_REVIEW}.create`;
-export const WORKSPACE_ROUTE_SQL_REVIEW_DETAIL = `${WORKSPACE_ROUTE_SQL_REVIEW}.detail`;
-
-export const WORKSPACE_ROUTE_RISK_ASSESSMENT = "workspace.risk-assessment";
-export const WORKSPACE_ROUTE_CUSTOM_APPROVAL = "workspace.custom-approval";
-export const WORKSPACE_ROUTE_GLOBAL_MASKING = "workspace.global-masking";
-export const WORKSPACE_ROUTE_SEMANTIC_TYPES = "workspace.semantic-types";
-export const WORKSPACE_ROUTE_DATA_CLASSIFICATION =
- "workspace.data-classification";
-export const WORKSPACE_ROUTE_AUDIT_LOG = "workspace.audit-log";
-export const WORKSPACE_ROUTE_USERS = "workspace.users";
-export const WORKSPACE_ROUTE_SERVICE_ACCOUNTS = "workspace.service-accounts";
-export const WORKSPACE_ROUTE_WORKLOAD_IDENTITIES =
- "workspace.workload-identities";
-export const WORKSPACE_ROUTE_MEMBERS = "workspace.members";
-export const WORKSPACE_ROUTE_GROUPS = "workspace.groups";
-export const WORKSPACE_ROUTE_ROLES = "workspace.roles";
-
-export const WORKSPACE_ROUTE_IDENTITY_PROVIDERS =
- "workspace.identity-providers";
-export const WORKSPACE_ROUTE_IDENTITY_PROVIDER_DETAIL = `${WORKSPACE_ROUTE_IDENTITY_PROVIDERS}.detail`;
-
-export const WORKSPACE_ROUTE_INTEGRATION = "workspace.integration";
-export const WORKSPACE_ROUTE_IM = `${WORKSPACE_ROUTE_INTEGRATION}.im`;
-export const WORKSPACE_ROUTE_MCP = `${WORKSPACE_ROUTE_INTEGRATION}.mcp`;
-
-export const WORKSPACE_ROUTE_403 = "error.403";
-export const WORKSPACE_ROUTE_404 = "error.404";
diff --git a/frontend/src/router/dashboard/workspaceSetting.ts b/frontend/src/router/dashboard/workspaceSetting.ts
deleted file mode 100644
index 43c1cb70c6..0000000000
--- a/frontend/src/router/dashboard/workspaceSetting.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import type { RouteRecordRaw } from "vue-router";
-import { t } from "@/plugins/i18n";
-
-export const SETTING_ROUTE = "setting";
-export const SETTING_ROUTE_WORKSPACE = `${SETTING_ROUTE}.workspace`;
-export const SETTING_ROUTE_PROFILE = `${SETTING_ROUTE}.profile`;
-export const SETTING_ROUTE_PROFILE_TWO_FACTOR = `${SETTING_ROUTE_PROFILE}.two-factor`;
-export const SETTING_ROUTE_WORKSPACE_GENERAL = `${SETTING_ROUTE_WORKSPACE}.general`;
-export const SETTING_ROUTE_WORKSPACE_SUBSCRIPTION = `${SETTING_ROUTE_WORKSPACE}.subscription`;
-
-const workspaceSettingRoutes: RouteRecordRaw[] = [
- {
- path: "setting",
- name: SETTING_ROUTE_WORKSPACE,
- meta: { title: () => t("common.settings") },
- components: {
- content: () => import("@/react/ReactRouteShellBridge.vue"),
- leftSidebar: () => import("@/react/ReactSidebarMount.vue"),
- },
- props: {
- content: () => ({
- page: "SettingRouteShell",
- }),
- leftSidebar: true,
- },
- children: [
- {
- path: "profile",
- name: SETTING_ROUTE_PROFILE,
- meta: { title: () => t("settings.sidebar.profile") },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "ProfilePage" }),
- },
- {
- path: "profile/two-factor",
- name: SETTING_ROUTE_PROFILE_TWO_FACTOR,
- meta: { title: () => t("two-factor.self") },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "TwoFactorSetupPage" }),
- },
- {
- path: "general",
- name: SETTING_ROUTE_WORKSPACE_GENERAL,
- meta: {
- title: () => t("settings.sidebar.general"),
- requiredPermissionList: () => [
- "bb.settings.getWorkspaceProfile",
- "bb.policies.get",
- ],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "GeneralPage" }),
- },
- {
- path: "subscription",
- name: SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,
- meta: {
- title: () => t("settings.sidebar.subscription"),
- requiredPermissionList: () => ["bb.settings.get"],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: () => ({ page: "SubscriptionPage" }),
- },
- ],
- },
-];
-
-export default workspaceSettingRoutes;
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
deleted file mode 100644
index 5e28f7a4b8..0000000000
--- a/frontend/src/router/index.ts
+++ /dev/null
@@ -1,293 +0,0 @@
-import { nextTick } from "vue";
-import { setDocumentTitle, STORAGE_KEY_BACK_PATH } from "@/utils";
-import {
- createRouter,
- createWebHistory,
- type LocationQueryRaw,
-} from "vue-router";
-import {
- hasFeature,
- useAuthStore,
- useCurrentUserV1,
- useSettingV1Store,
-} from "@/store";
-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
-import { isAuthRelatedRoute } from "@/utils/auth";
-import authRoutes, {
- AUTH_2FA_SETUP_MODULE,
- AUTH_OAUTH_CALLBACK_MODULE,
- AUTH_OIDC_CALLBACK_MODULE,
- AUTH_PASSWORD_RESET_MODULE,
- AUTH_PROFILE_SETUP_MODULE,
- AUTH_SIGNIN_MODULE,
- OAUTH2_CONSENT_MODULE,
-} from "./auth";
-
-// Query params that are only meaningful on the signin page (pre-login).
-// They're forwarded from the original URL to signin and stripped from the post-login redirect.
-const SIGNIN_QUERY_PARAMS = [
- "idp",
- "workspace",
- "email",
- "token",
- "invitation",
-] as const;
-
-const stripSigninQueryParams = (fullPath: string): string => {
- const url = new URL(fullPath, window.location.origin);
- for (const param of SIGNIN_QUERY_PARAMS) {
- url.searchParams.delete(param);
- }
- return url.pathname + url.search + url.hash;
-};
-import dashboardRoutes from "./dashboard";
-import {
- DATABASE_ROUTE_DASHBOARD,
- ENVIRONMENT_V1_ROUTE_DASHBOARD,
- INSTANCE_ROUTE_DASHBOARD,
- PROJECT_V1_ROUTE_DASHBOARD,
- WORKSPACE_ROOT_MODULE,
- WORKSPACE_ROUTE_403,
- WORKSPACE_ROUTE_404,
-} from "./dashboard/workspaceRoutes";
-import { SETTING_ROUTE } from "./dashboard/workspaceSetting";
-import setupRoutes, { SETUP_MODULE } from "./setup";
-import sqlEditorRoutes from "./sqlEditor";
-
-export const router = createRouter({
- history: createWebHistory(import.meta.env.BASE_URL),
- routes: [
- ...authRoutes,
- ...setupRoutes,
- ...dashboardRoutes,
- ...sqlEditorRoutes,
- ],
- scrollBehavior(to /*, from, savedPosition */) {
- if (to.hash) {
- try {
- const el = document.querySelector(to.hash);
- if (el) {
- return {
- el: to.hash,
- behavior: "smooth",
- };
- }
- } catch {
- // nothing todo
- }
- }
- },
-});
-
-router.beforeEach((to, from, next) => {
- console.debug("Router %s -> %s", from.name, to.name);
-
- // === SPECIAL CASES - Allow direct access ===
-
- // Prevent infinite loops only for identical routes without parameter changes
- if (from.name === to.name && from.fullPath === to.fullPath) {
- next(false);
- return;
- }
-
- // Error pages can be accessed directly
- if (to.name === WORKSPACE_ROUTE_403 || to.name === WORKSPACE_ROUTE_404) {
- next();
- return;
- }
-
- // Auth callbacks can be accessed directly
- if (
- to.name === AUTH_OAUTH_CALLBACK_MODULE ||
- to.name === AUTH_OIDC_CALLBACK_MODULE
- ) {
- next();
- return;
- }
-
- // OAuth2 consent page requires login but should not redirect away
- if (to.name === OAUTH2_CONSENT_MODULE) {
- next();
- return;
- }
-
- const authStore = useAuthStore();
- const settingV1Store = useSettingV1Store();
-
- // Allow access to 2FA setup and password reset for logged-in users
- if (
- authStore.isLoggedIn &&
- (to.name === AUTH_2FA_SETUP_MODULE ||
- to.name === AUTH_PASSWORD_RESET_MODULE ||
- to.name === AUTH_PROFILE_SETUP_MODULE)
- ) {
- next();
- return;
- }
-
- // === MODULE NAVIGATION TRACKING ===
-
- const fromModule =
- from.name?.toString().split(".")[0] || WORKSPACE_ROOT_MODULE;
- const toModule = to.name?.toString().split(".")[0] || WORKSPACE_ROOT_MODULE;
-
- if (toModule !== fromModule) {
- // Inline write — the previous `useRouterStore().setBackPath(...)` was a
- // thin wrapper around the same localStorage key, and no consumer reads
- // `backPath`, so cross-tab reactivity wasn't actually needed.
- localStorage.setItem(STORAGE_KEY_BACK_PATH, from.fullPath);
- }
-
- // === AUTHENTICATION LOGIC ===
-
- // If user is logged in and tries to access auth pages, redirect to main app
- if (
- isAuthRelatedRoute(to.name as string) &&
- authStore.isLoggedIn &&
- !authStore.unauthenticatedOccurred
- ) {
- // For IdP-initiated SSO, use relay_state parameter
- // For other auth routes, use redirect parameter
- const relayState = to.query["relay_state"] as string | undefined;
- const redirectParam = to.query["redirect"] as string | undefined;
-
- // Validate relay_state to prevent open redirect attacks
- let redirect = "/";
- if (relayState && typeof relayState === "string") {
- // Only allow relative URLs, reject protocol-relative URLs (//)
- if (relayState.startsWith("/") && !relayState.startsWith("//")) {
- redirect = relayState;
- }
- } else if (redirectParam) {
- redirect = redirectParam;
- }
-
- next(redirect);
- return;
- }
-
- // Auth pages: Reset stores and allow access
- if (isAuthRelatedRoute(to.name as string)) {
- void import("@/react/stores/app").then(({ useAppStore }) => {
- useAppStore.getState().resetDatabases();
- useAppStore.getState().resetInstances();
- useAppStore.getState().resetProjects();
- });
- import("@/plugins/ai/store").then(({ useConversationStore }) => {
- useConversationStore().reset();
- });
- next();
- return;
- }
-
- // Require authentication for all other pages
- if (!authStore.isLoggedIn) {
- const query: LocationQueryRaw = {};
-
- // Forward signin-only query params (consumed by the signin page itself).
- for (const param of SIGNIN_QUERY_PARAMS) {
- if (to.query[param]) {
- query[param] = to.query[param];
- }
- }
-
- // Set redirect URL if not root path and not already set.
- // Strip signin-only params from the redirect — they're meaningless after login.
- if (to.fullPath !== "/" && !to.query["redirect"]) {
- query["redirect"] = stripSigninQueryParams(to.fullPath);
- }
-
- next({
- name: AUTH_SIGNIN_MODULE,
- query,
- replace: true,
- });
- return;
- }
-
- // Enforce 2FA setup if required
- const currentUserV1 = useCurrentUserV1();
- if (
- hasFeature(PlanFeature.FEATURE_TWO_FA) &&
- settingV1Store.workspaceProfile.requireMfa &&
- currentUserV1.value &&
- !currentUserV1.value.mfaEnabled &&
- to.name !== AUTH_2FA_SETUP_MODULE // Prevent redirect loop
- ) {
- next({
- name: AUTH_2FA_SETUP_MODULE,
- replace: true,
- });
- return;
- }
-
- // Enforce password reset if required
- if (
- authStore.requireResetPassword &&
- to.name !== AUTH_PASSWORD_RESET_MODULE // Prevent redirect loop
- ) {
- next({
- name: AUTH_PASSWORD_RESET_MODULE,
- replace: true,
- });
- return;
- }
-
- // === ROUTE ACCESS CONTROL ===
-
- // Allow access to main application routes
- const allowedRoutePatterns = [
- ENVIRONMENT_V1_ROUTE_DASHBOARD,
- INSTANCE_ROUTE_DASHBOARD,
- PROJECT_V1_ROUTE_DASHBOARD,
- DATABASE_ROUTE_DASHBOARD,
- SETTING_ROUTE,
- SETUP_MODULE,
- "workspace",
- "sql-editor",
- ];
-
- if (
- allowedRoutePatterns.some((pattern) =>
- to.name?.toString().startsWith(pattern)
- )
- ) {
- next();
- return;
- }
-
- // Allow same-path navigation (e.g. anchor changes)
- if (to.path === from.path) {
- next();
- return;
- }
-
- // === FALLBACK ===
-
- // Log unexpected route for debugging
- console.warn("Router: Unexpected route", {
- to: to.name,
- path: to.path,
- fullPath: to.fullPath,
- });
-
- next({
- name: WORKSPACE_ROUTE_404,
- replace: false,
- });
-});
-
-router.afterEach((to /*, from */) => {
- // Skip routes where the React route shell manages the document title:
- // - ProjectRouteShell handles project-scoped routes (have projectId param)
- // - SettingRouteShell handles settings routes (marked with overrideDocumentTitle)
- if (to.params.projectId || to.meta.overrideDocumentTitle) return;
-
- nextTick(() => {
- if (to.meta.title) {
- setDocumentTitle(to.meta.title(to));
- } else {
- setDocumentTitle();
- }
- });
-});
diff --git a/frontend/src/router/setup.ts b/frontend/src/router/setup.ts
deleted file mode 100644
index b62125d7b1..0000000000
--- a/frontend/src/router/setup.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import type { RouteRecordRaw } from "vue-router";
-import SplashLayout from "@/layouts/SplashLayout.vue";
-import { t } from "@/plugins/i18n";
-
-export const SETUP_MODULE = "setup";
-
-const setupRoutes: RouteRecordRaw[] = [
- {
- path: "/setup",
- component: SplashLayout,
- children: [
- {
- path: "",
- name: SETUP_MODULE,
- meta: {
- title: () => t("setup.self"),
- requiredPermissionList: () => [
- "bb.settings.get",
- "bb.settings.setWorkspaceProfile",
- "bb.projects.create",
- "bb.roles.list",
- "bb.workspaces.getIamPolicy",
- ],
- },
- component: () => import("@/react/ReactPageMount.vue"),
- props: { page: "SetupPage" },
- },
- ],
- },
-];
-
-export default setupRoutes;
diff --git a/frontend/src/router/sqlEditor.ts b/frontend/src/router/sqlEditor.ts
deleted file mode 100644
index 108fa323b2..0000000000
--- a/frontend/src/router/sqlEditor.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { defineComponent, h } from "vue";
-import type { RouteRecordRaw } from "vue-router";
-import { t } from "@/plugins/i18n";
-import ReactPageMount from "@/react/ReactPageMount.vue";
-
-export const SQL_EDITOR_HOME_MODULE = "sql-editor.home";
-export const SQL_EDITOR_PROJECT_MODULE = "sql-editor.project";
-export const SQL_EDITOR_INSTANCE_MODULE = "sql-editor.instance";
-export const SQL_EDITOR_DATABASE_MODULE = "sql-editor.database";
-export const SQL_EDITOR_WORKSHEET_MODULE = "sql-editor.worksheet";
-
-// Parent route component: a one-line Vue render-only shell that mounts
-// the React `SQLEditorLayout` tree. The full layout (debug teleport
-// target, banners wrapper, route shell, home page, AI bridge, etc.)
-// lives React-side; this shim exists only because Vue Router still
-// owns the route entry. Migrating the route itself to React Router is
-// out of scope per Stage 21 design § 4.8 option A.
-const SQLEditorLayoutComponent = defineComponent({
- name: "SQLEditorLayoutRoute",
- render: () =>
- h(ReactPageMount, {
- page: "SQLEditorLayout",
- containerClass: "w-full h-full flex flex-col",
- }),
-});
-
-// Child routes don't render anything of their own — the React layout
-// inspects `useCurrentRoute()` and decides what to show. We only need
-// each child to exist so `router.push({ name: SQL_EDITOR_*_MODULE })`
-// resolves to a valid path. Vue Router requires a `component` field;
-// rendering nothing is the closest match to "no body".
-const NoopRouteComponent = defineComponent({
- name: "SQLEditorChildRoute",
- render: () => null,
-});
-
-const sqlEditorRoutes: RouteRecordRaw[] = [
- {
- path: "/sql-editor",
- name: "sql-editor",
- component: SQLEditorLayoutComponent,
- meta: {
- requiredPermissionList: () => [
- "bb.projects.get",
- "bb.databases.list",
- "bb.projects.getIamPolicy",
- ],
- },
- children: [
- {
- path: "",
- name: SQL_EDITOR_HOME_MODULE,
- meta: { title: () => t("sql-editor.self") },
- component: NoopRouteComponent,
- },
- {
- path: "projects/:project",
- name: SQL_EDITOR_PROJECT_MODULE,
- meta: { title: () => t("sql-editor.self") },
- component: NoopRouteComponent,
- },
- {
- path: "projects/:project/instances/:instance/databases/:database",
- name: SQL_EDITOR_DATABASE_MODULE,
- meta: { title: () => t("sql-editor.self") },
- component: NoopRouteComponent,
- },
- {
- path: "projects/:project/instances/:instance",
- name: SQL_EDITOR_INSTANCE_MODULE,
- meta: { title: () => t("sql-editor.self") },
- component: NoopRouteComponent,
- },
- {
- path: "projects/:project/sheets/:sheet",
- name: SQL_EDITOR_WORKSHEET_MODULE,
- meta: { title: () => t("sql-editor.self") },
- component: NoopRouteComponent,
- },
- ],
- },
-];
-
-export default sqlEditorRoutes;
diff --git a/frontend/src/router/useRecentVisit.ts b/frontend/src/router/useRecentVisit.ts
deleted file mode 100644
index 7dba56ceb0..0000000000
--- a/frontend/src/router/useRecentVisit.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import { computed } from "vue";
-import { useCurrentUserV1 } from "@/store";
-import { useActuatorV1Store } from "@/store/modules/v1/actuator";
-import { projectNamePrefix } from "@/store/modules/v1/common";
-import {
- storageKeyRecentVisit,
- useDynamicLocalStorage,
- workspaceCacheScope,
-} from "@/utils";
-
-const MAX_HISTORY = 10;
-
-export function useRecentVisit() {
- const currentUser = useCurrentUserV1();
- const actuatorStore = useActuatorV1Store();
-
- const recentVisit = useDynamicLocalStorage<string[]>(
- computed(() =>
- storageKeyRecentVisit(
- workspaceCacheScope(
- actuatorStore.isSaaSMode,
- currentUser.value.workspace
- ),
- currentUser.value.email
- )
- ),
- []
- );
-
- const lastVisit = computed(() => {
- if (recentVisit.value.length === 0) {
- return;
- }
- return recentVisit.value[0];
- });
-
- const lastVisitProjectPath = computed(() => {
- for (const visit of recentVisit.value) {
- if (visit.startsWith(`/${projectNamePrefix}`)) {
- return visit;
- }
- }
- return "";
- });
-
- const remove = (path: string) => {
- const index = recentVisit.value.findIndex((item) => {
- // We treat the two URLs "the same" when their urls'
- // `path` are the same (means ignoring querystring and hash).
- // e.g. "/db?environment=5003" & "/db?environment=5005"
- // Because usually they are just different tab-panes
- // or filters on the page.
- return getPath(item) === getPath(path);
- });
- if (index >= 0) {
- recentVisit.value.splice(index, 1);
- }
- };
-
- const record = (path: string) => {
- // current page exists in the history already
- // pull it out before next step
- remove(path);
-
- // ensure the queue's length
- // should be no more than (MAX_HISTORY + 1)
- // because current page will always be the first one in the list
- while (recentVisit.value.length > MAX_HISTORY + 1) {
- recentVisit.value.pop();
- }
-
- recentVisit.value.unshift(path);
- };
-
- return {
- remove,
- record,
- lastVisit,
- lastVisitProjectPath,
- };
-}
-
-function getPath(url: string): string {
- return url.replace(/[?#].*$/, "");
-}
diff --git a/frontend/src/shell-bridge.test.ts b/frontend/src/shell-bridge.test.ts
deleted file mode 100644
index 459424d455..0000000000
--- a/frontend/src/shell-bridge.test.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-import { mount } from "@vue/test-utils";
-import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
-import { nextTick } from "vue";
-import {
- emitReactLocaleChange,
- emitReactQuickstartReset,
-} from "@/react/shell-bridge";
-
-const mocks = vi.hoisted(() => ({
- locale: { value: "en-US" },
- route: {
- meta: {
- title: () => "Workspace",
- },
- query: {},
- },
- previousRoute: {
- query: {},
- },
- replace: vi.fn(),
- setDocumentTitle: vi.fn(),
- overrideAppProfile: vi.fn(),
- pushNotification: vi.fn(),
- introState: {} as Record<string, boolean>,
- saveIntroStateByKey: vi.fn(
- async ({ key, newState }: { key: string; newState: boolean }) => {
- mocks.introState[key] = newState;
- return newState;
- }
- ),
-}));
-
-vi.mock("@/react/ReactPageMount.vue", async () => {
- const { defineComponent, h } = await import("vue");
- return {
- default: defineComponent({
- name: "MockReactPageMount",
- props: ["page", "pageProps", "containerClass"],
- setup() {
- return () => h("div");
- },
- }),
- };
-});
-
-vi.mock("./AuthContext.vue", async () => {
- const { defineComponent, h } = await import("vue");
- return {
- default: defineComponent({
- name: "MockAuthContext",
- setup(_, { slots }) {
- return () => h("div", slots.default?.());
- },
- }),
- };
-});
-
-vi.mock("./customAppProfile", () => ({
- overrideAppProfile: mocks.overrideAppProfile,
-}));
-
-vi.mock("./plugins/i18n", () => ({
- locale: mocks.locale,
- t: (key: string) => key,
-}));
-
-vi.mock("./store", () => ({
- useNotificationStore: () => ({
- pushNotification: mocks.pushNotification,
- }),
- useUIStateStore: () => ({
- introState: mocks.introState,
- saveIntroStateByKey: mocks.saveIntroStateByKey,
- }),
-}));
-
-vi.mock("./utils", () => ({
- isDev: () => false,
- setDocumentTitle: mocks.setDocumentTitle,
-}));
-
-vi.mock("vue-router", async () => {
- const actual =
- await vi.importActual<typeof import("vue-router")>("vue-router");
- const { reactive } = await import("vue");
- const route = reactive(mocks.route);
- return {
- ...actual,
- useRoute: () => route,
- useRouter: () => ({
- replace: mocks.replace,
- }),
- };
-});
-
-import App from "./App.vue";
-
-beforeEach(() => {
- vi.clearAllMocks();
- mocks.locale.value = "en-US";
- mocks.route.meta.title = () => "Workspace";
- mocks.route.query = {};
- mocks.previousRoute.query = {};
- mocks.introState = {};
-});
-
-afterEach(() => {
- document.body.innerHTML = "";
-});
-
-describe("React shell bridge", () => {
- test("updates Vue locale and document title from locale events", async () => {
- const wrapper = mount(App, {
- attachTo: document.body,
- global: {
- stubs: {
- RouterView: { template: "<div />" },
- },
- },
- });
- await nextTick();
-
- emitReactLocaleChange("ja-JP");
-
- expect(mocks.locale.value).toBe("ja-JP");
- expect(mocks.setDocumentTitle).toHaveBeenCalledWith("Workspace");
-
- wrapper.unmount();
- });
-
- test("updates quickstart intro state from reset events", async () => {
- const wrapper = mount(App, {
- attachTo: document.body,
- global: {
- stubs: {
- RouterView: { template: "<div />" },
- },
- },
- });
- await nextTick();
-
- emitReactQuickstartReset({ keys: ["hidden", "data.query"] });
- await nextTick();
-
- expect(mocks.introState).toMatchObject({
- hidden: false,
- "data.query": false,
- });
- expect(mocks.saveIntroStateByKey).toHaveBeenCalledTimes(2);
-
- wrapper.unmount();
- });
-});
diff --git a/frontend/src/shims-vue-globals.d.ts b/frontend/src/shims-vue-globals.d.ts
index 7d51bc6e42..d686fb412f 100644
--- a/frontend/src/shims-vue-globals.d.ts
+++ b/frontend/src/shims-vue-globals.d.ts
@@ -1,5 +1,4 @@
import type dayjs from "dayjs";
-import type { Composer } from "vue-i18n";
import type { humanizeDate, humanizeTs } from "./utils";
export {};
@@ -13,8 +12,5 @@ declare module "vue" {
humanizeDate: typeof humanizeDate;
isDev: boolean;
isRelease: boolean;
- $t: Composer["t"];
- $te: Composer["te"];
- $tm: Composer["tm"];
}
}
diff --git a/frontend/src/shims-vue-router.d.ts b/frontend/src/shims-vue-router.d.ts
deleted file mode 100644
index 3ad1762fd1..0000000000
--- a/frontend/src/shims-vue-router.d.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import type { Permission } from "./types";
-
-export {};
-
-declare module "vue-router" {
- interface RouteMeta {
- title?: (route: RouteLocationNormalized) => string;
- requiredPermissionList?: () => Permission[];
- // When true, a React route shell manages document.title for this route,
- // so the router afterEach skips it.
- overrideDocumentTitle?: boolean;
- }
-}
diff --git a/frontend/src/store/index.ts b/frontend/src/store/index.ts
index 3df5704f05..ee7f6fa6a3 100644
--- a/frontend/src/store/index.ts
+++ b/frontend/src/store/index.ts
@@ -1,6 +1,2 @@
-import { createPinia } from "pinia";
-
-export const pinia = createPinia();
-
export * from "./modules";
export * from "./cache";
diff --git a/frontend/src/store/modules/index.ts b/frontend/src/store/modules/index.ts
index fa8c7440ff..1feb255b0f 100644
--- a/frontend/src/store/modules/index.ts
+++ b/frontend/src/store/modules/index.ts
@@ -1,8 +1,7 @@
-export * from "./v1/auth";
+// Pinia stores removed (migrated to the React app store at
+// `@/react/stores/app`). Only pinia-free helpers remain here.
export * from "./notification";
-export * from "./uistate";
-export * from "./user";
-export * from "./role";
export * from "./utils";
+export * from "./migration-helpers";
export * from "./v1";
diff --git a/frontend/src/store/modules/migration-helpers.ts b/frontend/src/store/modules/migration-helpers.ts
new file mode 100644
index 0000000000..d87d61769c
--- /dev/null
+++ b/frontend/src/store/modules/migration-helpers.ts
@@ -0,0 +1,18 @@
+import { unknownUser } from "@/types";
+import type { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+import type { User } from "@/types/proto-es/v1/user_service_pb";
+import { appStoreUtilBridge } from "@/utils/app-store-bridge";
+
+// Pinia-free replacements for helpers that used to live in the deleted legacy
+// Pinia stores (`v1/auth`, `v1/subscription`). They read the React app store
+// (the single source of truth) via the util bridge — the old Pinia stores were
+// never populated in the React shell, so the previous implementations silently
+// returned unknownUser() / no features.
+
+export const getCurrentUserV1 = (): User => {
+ return appStoreUtilBridge()?.currentUser() ?? unknownUser();
+};
+
+export const hasFeature = (feature: PlanFeature): boolean => {
+ return appStoreUtilBridge()?.hasFeature(feature) ?? false;
+};
diff --git a/frontend/src/store/modules/notification.ts b/frontend/src/store/modules/notification.ts
index 39154662fc..46086d6164 100644
--- a/frontend/src/store/modules/notification.ts
+++ b/frontend/src/store/modules/notification.ts
@@ -1,30 +1,18 @@
-import { defineStore } from "pinia";
import { VueShellBridgeEvent } from "@/react/shell-bridge";
import type { NotificationCreate } from "@/types";
/**
- * Notification store — kept as a Pinia store for backward compatibility
- * with the 17 Vue-side pushNotification() callers. No internal queue: each
- * push dispatches a window CustomEvent that the React toast manager
- * (frontend/src/react/lib/toast.ts) catches and renders. The Pinia layer
- * dies entirely in Phase B3 (Pinia -> Zustand).
+ * Dispatches a notification as a window CustomEvent that the React toast
+ * manager (frontend/src/react/lib/toast.ts) catches and renders. Pinia-free:
+ * the former `useNotificationStore` was an empty-state shim around this same
+ * dispatch and has been removed.
*/
-export const useNotificationStore = defineStore("notification", {
- state: () => ({}),
- actions: {
- pushNotification(notification: NotificationCreate) {
- if (typeof window !== "undefined") {
- window.dispatchEvent(
- new CustomEvent<NotificationCreate>(
- VueShellBridgeEvent.notification,
- { detail: notification }
- )
- );
- }
- },
- },
-});
-
export const pushNotification = (notification: NotificationCreate) => {
- useNotificationStore().pushNotification(notification);
+ if (typeof window !== "undefined") {
+ window.dispatchEvent(
+ new CustomEvent<NotificationCreate>(VueShellBridgeEvent.notification, {
+ detail: notification,
+ })
+ );
+ }
};
diff --git a/frontend/src/store/modules/role.ts b/frontend/src/store/modules/role.ts
deleted file mode 100644
index c8b0036a49..0000000000
--- a/frontend/src/store/modules/role.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { defineStore } from "pinia";
-import { ref } from "vue";
-import { roleServiceClientConnect } from "@/connect";
-import type { Role } from "@/types/proto-es/v1/role_service_pb";
-import {
- DeleteRoleRequestSchema,
- ListRolesRequestSchema,
- UpdateRoleRequestSchema,
-} from "@/types/proto-es/v1/role_service_pb";
-import { useGracefulRequest } from "./utils";
-
-export const useRoleStore = defineStore("role", () => {
- const roleList = ref<Role[]>([]);
-
- const fetchRoleList = async () => {
- const request = create(ListRolesRequestSchema, {});
- const response = await roleServiceClientConnect.listRoles(request);
- roleList.value = response.roles;
- return roleList.value;
- };
-
- const getRoleByName = (name: string) => {
- return roleList.value.find((r) => r.name === name);
- };
-
- const upsertRole = async (role: Role) => {
- const request = create(UpdateRoleRequestSchema, {
- role: role,
- updateMask: {
- paths: ["title", "description", "permissions"],
- },
- allowMissing: true,
- });
- const response = await roleServiceClientConnect.updateRole(request);
- const index = roleList.value.findIndex((r) => r.name === role.name);
- if (index >= 0) {
- roleList.value.splice(index, 1, response);
- } else {
- roleList.value.push(response);
- }
- return response;
- };
-
- const deleteRole = async (role: Role) => {
- await useGracefulRequest(async () => {
- const request = create(DeleteRoleRequestSchema, {
- name: role.name,
- });
- await roleServiceClientConnect.deleteRole(request);
- const index = roleList.value.findIndex((r) => r.name === role.name);
- if (index >= 0) {
- roleList.value.splice(index, 1);
- }
- });
- };
-
- return {
- roleList,
- fetchRoleList,
- getRoleByName,
- upsertRole,
- deleteRole,
- };
-});
diff --git a/frontend/src/store/modules/sqlEditor/legacy/extendedTab.ts b/frontend/src/store/modules/sqlEditor/legacy/extendedTab.ts
index b71c420b26..82503321bc 100644
--- a/frontend/src/store/modules/sqlEditor/legacy/extendedTab.ts
+++ b/frontend/src/store/modules/sqlEditor/legacy/extendedTab.ts
@@ -1,5 +1,4 @@
import { pick } from "lodash-es";
-import { defineStore } from "pinia";
import PouchDB from "pouchdb";
import PouchDBFind from "pouchdb-find";
import type { SQLEditorTab } from "@/types";
@@ -23,58 +22,63 @@ type ExtendedTabEntity = ExtendedTab & {
PouchDB.plugin(PouchDBFind);
-export const useExtendedTabStore = defineStore("sqlEditorExtendedTab", () => {
- // stores
- const extendedTabDB = new PouchDB<ExtendedTabEntity>(
- "bb.sql-editor.extended-tab",
- {
+// Pinia-free: a stateless wrapper over a PouchDB instance used only by the
+// one-time legacy SQL-editor cache migration (`./migration`). The PouchDB
+// instance is created lazily on first use (the former `useExtendedTabStore`
+// Pinia store deferred creation to first access the same way) so importing
+// this module does not eagerly touch IndexedDB.
+let db: PouchDB.Database<ExtendedTabEntity> | null = null;
+let ready: Promise<unknown> | null = null;
+
+const getDB = () => {
+ if (!db) {
+ db = new PouchDB<ExtendedTabEntity>("bb.sql-editor.extended-tab", {
// Remove unused and old data automatically.
auto_compaction: true,
// Do not save and track old revisions, this is for saving storage usage.
revs_limit: 1,
- }
- );
- const ready = Promise.all([
- extendedTabDB.createIndex({
- index: { name: "idx_tab_user", fields: ["user"] },
- }),
- extendedTabDB.createIndex({
- index: { name: "idx_tab_project", fields: ["project"] },
- }),
- ]);
-
- const fetchExtendedTab = async (tab: SQLEditorTab, fallback?: () => void) => {
- try {
- await ready;
- const doc = await extendedTabDB.get(tab.id);
- Object.assign(tab, {
- _rev: doc._rev,
- _user: doc.user,
- _project: doc.project,
- ...pick(doc, EXTENDED_TAB_FIELDS),
- });
- } catch (err) {
- if (fallback) {
- fallback();
- }
+ });
+ ready = Promise.all([
+ db.createIndex({ index: { name: "idx_tab_user", fields: ["user"] } }),
+ db.createIndex({
+ index: { name: "idx_tab_project", fields: ["project"] },
+ }),
+ ]);
+ }
+ return { db, ready: ready as Promise<unknown> };
+};
- if ((err as PouchDBError)?.status === 404) return;
- console.debug("[SQLEditorExtendedTabStore] fetchExtendedTab", err);
+export const fetchExtendedTab = async (
+ tab: SQLEditorTab,
+ fallback?: () => void
+) => {
+ try {
+ const { db, ready } = getDB();
+ await ready;
+ const doc = await db.get(tab.id);
+ Object.assign(tab, {
+ _rev: doc._rev,
+ _user: doc.user,
+ _project: doc.project,
+ ...pick(doc, EXTENDED_TAB_FIELDS),
+ });
+ } catch (err) {
+ if (fallback) {
+ fallback();
}
- };
- const deleteExtendedTab = async (id: string) => {
- try {
- await ready;
- const doc = await extendedTabDB.get(id);
- await extendedTabDB.remove(doc);
- } catch (err) {
- console.warn("[SQLEditorExtendedTabStore] deleteExtendedTab", err);
- }
- };
+ if ((err as PouchDBError)?.status === 404) return;
+ console.debug("[SQLEditorExtendedTab] fetchExtendedTab", err);
+ }
+};
- return {
- fetchExtendedTab,
- deleteExtendedTab,
- };
-});
+export const deleteExtendedTab = async (id: string) => {
+ try {
+ const { db, ready } = getDB();
+ await ready;
+ const doc = await db.get(id);
+ await db.remove(doc);
+ } catch (err) {
+ console.warn("[SQLEditorExtendedTab] deleteExtendedTab", err);
+ }
+};
diff --git a/frontend/src/store/modules/sqlEditor/legacy/migration.ts b/frontend/src/store/modules/sqlEditor/legacy/migration.ts
index d1f6a2eee4..6b13adc511 100644
--- a/frontend/src/store/modules/sqlEditor/legacy/migration.ts
+++ b/frontend/src/store/modules/sqlEditor/legacy/migration.ts
@@ -14,9 +14,13 @@ import {
useDynamicLocalStorage,
WebStorageHelper,
} from "@/utils";
+import { getCurrentUserV1 } from "../../migration-helpers";
import { extractUserEmail } from "../../v1";
-import { useCurrentUserV1 } from "../../v1/auth";
-import { EXTENDED_TAB_FIELDS, useExtendedTabStore } from "./extendedTab";
+import {
+ deleteExtendedTab,
+ EXTENDED_TAB_FIELDS,
+ fetchExtendedTab,
+} from "./extendedTab";
const LOCAL_STORAGE_KEY_PREFIX = "bb.sql-editor-tab";
@@ -28,13 +32,11 @@ type PersistentTab = Pick<
type LegacyStoredTab = PersistentTab & { statement?: string };
export const migrateLegacyCache = async () => {
- const me = useCurrentUserV1();
- const userUID = computed(() => extractUserEmail(me.value.name));
+ const userUID = computed(() => extractUserEmail(getCurrentUserV1().name));
const keyNamespace = computed(
() => `${LOCAL_STORAGE_KEY_PREFIX}.${userUID.value}`
);
- const extendedTabStore = useExtendedTabStore();
const tabIdListKey = computed(() => `${keyNamespace.value}.tab-id-list`);
const tabIdListMapByProject = useDynamicLocalStorage<
Record<string, string[]>
@@ -68,7 +70,7 @@ export const migrateLegacyCache = async () => {
tab.mode = DEFAULT_SQL_EDITOR_TAB_MODE;
}
- await extendedTabStore.fetchExtendedTab(tab, () => {
+ await fetchExtendedTab(tab, () => {
// When the first time of migration, the extended doc in IndexedDB is not
// found.
// Fallback to the original PersistentTab in LocalStorage if possible.
@@ -101,7 +103,7 @@ export const migrateLegacyCache = async () => {
continue;
}
const tab = await loadStoredTab(tabId);
- await extendedTabStore.deleteExtendedTab(tabId);
+ await deleteExtendedTab(tabId);
if (!tab) {
continue;
}
@@ -113,8 +115,7 @@ export const migrateLegacyCache = async () => {
};
export const migrateDraftsFromCache = async (project: string) => {
- const me = useCurrentUserV1();
- const userUID = computed(() => extractUserEmail(me.value.name));
+ const userUID = computed(() => extractUserEmail(getCurrentUserV1().name));
const viewStateByTab = useDynamicLocalStorage<
Map</* tab.id */ string, EditorPanelViewState>
@@ -168,8 +169,7 @@ export const migrateDraftsFromCache = async (project: string) => {
};
export const migrateTabViewState = (project: string) => {
- const me = useCurrentUserV1();
- const userUID = computed(() => extractUserEmail(me.value.name));
+ const userUID = computed(() => extractUserEmail(getCurrentUserV1().name));
const keyNamespace = computed(
() => `${LOCAL_STORAGE_KEY_PREFIX}.${project}.${userUID.value}`
diff --git a/frontend/src/store/modules/uistate.ts b/frontend/src/store/modules/uistate.ts
deleted file mode 100644
index 44d4f3b952..0000000000
--- a/frontend/src/store/modules/uistate.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { defineStore } from "pinia";
-import { computed } from "vue";
-import { useCurrentUserV1 } from "@/store";
-import {
- storageKeyCollapseState,
- storageKeyIntroState,
- useDynamicLocalStorage,
-} from "@/utils";
-
-export const useUIStateStore = defineStore("uistate", () => {
- const currentUser = useCurrentUserV1();
-
- const collapseState = useDynamicLocalStorage<Record<string, boolean>>(
- computed(() => storageKeyCollapseState(currentUser.value.email)),
- {}
- );
-
- const introState = useDynamicLocalStorage<Record<string, boolean>>(
- computed(() => storageKeyIntroState(currentUser.value.email)),
- {}
- );
-
- const getIntroStateByKey = (key: string): boolean => {
- return introState.value[key] ?? false;
- };
-
- const saveIntroStateByKey = async ({
- key,
- newState,
- }: {
- key: string;
- newState: boolean;
- }) => {
- introState.value = { ...introState.value, [key]: newState };
- return newState;
- };
-
- const restoreState = () => {
- // No-op: useDynamicLocalStorage handles restore automatically
- };
-
- return {
- collapseState,
- introState,
- saveIntroStateByKey,
- restoreState,
- getIntroStateByKey,
- };
-});
diff --git a/frontend/src/store/modules/user.ts b/frontend/src/store/modules/user.ts
deleted file mode 100644
index be41c789b5..0000000000
--- a/frontend/src/store/modules/user.ts
+++ /dev/null
@@ -1,300 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { createContextValues } from "@connectrpc/connect";
-import { isEqual, isUndefined, uniq } from "lodash-es";
-import { defineStore } from "pinia";
-import { computed, ref } from "vue";
-import { userServiceClientConnect } from "@/connect";
-import { silentContextKey } from "@/connect/context-key";
-import {
- allUsersUser,
- isValidProjectName,
- isValidUserName,
- unknownUser,
- userBindingPrefix,
-} from "@/types";
-import { State } from "@/types/proto-es/v1/common_pb";
-import type {
- UpdateUserRequest,
- User,
-} from "@/types/proto-es/v1/user_service_pb";
-import {
- BatchGetUsersRequestSchema,
- CreateUserRequestSchema,
- DeleteUserRequestSchema,
- GetUserRequestSchema,
- ListUsersRequestSchema,
- UndeleteUserRequestSchema,
- UpdateUserRequestSchema,
-} from "@/types/proto-es/v1/user_service_pb";
-import { ensureUserFullName, hasWorkspacePermissionV2 } from "@/utils";
-import { useActuatorV1Store } from "./v1/actuator";
-import { extractUserEmail, userNamePrefix } from "./v1/common";
-import { usePermissionStore } from "./v1/permission";
-
-export interface UserFilter {
- query?: string;
- project?: string;
- state?: State;
-}
-
-const getListUserFilter = (params: UserFilter) => {
- const filter = [];
- const search = params.query?.trim()?.toLowerCase();
- if (search) {
- filter.push(`(name.contains("${search}") || email.contains("${search}"))`);
- }
- if (isValidProjectName(params.project)) {
- filter.push(`project == "${params.project}"`);
- }
- if (params.state === State.DELETED) {
- filter.push(`state == "${State[params.state]}"`);
- }
-
- return filter.join(" && ");
-};
-
-export const useUserStore = defineStore("user", () => {
- const actuatorStore = useActuatorV1Store();
- const allUser = computed(() => allUsersUser());
-
- const userMapByName = ref<Map<string, User>>(
- new Map([[allUser.value.name, allUser.value]])
- );
-
- const setUser = (user: User) => {
- userMapByName.value.set(user.name, user);
- usePermissionStore().invalidCacheByUser(user);
- return user;
- };
-
- const fetchCurrentUser = async () => {
- const response = await userServiceClientConnect.getCurrentUser({});
- setUser(response);
- return response;
- };
-
- const fetchUserList = async (params: {
- pageSize: number;
- pageToken?: string;
- filter?: UserFilter;
- showDeleted?: boolean;
- }): Promise<{
- users: User[];
- nextPageToken: string;
- }> => {
- if (!hasWorkspacePermissionV2("bb.users.list")) {
- return {
- users: [],
- nextPageToken: "",
- };
- }
-
- const showDeleted =
- params.showDeleted ?? params.filter?.state === State.DELETED;
- const request = create(ListUsersRequestSchema, {
- pageSize: params.pageSize,
- pageToken: params.pageToken,
- filter: getListUserFilter(params.filter ?? {}),
- showDeleted,
- });
- const response = await userServiceClientConnect.listUsers(request);
- for (const user of response.users) {
- setUser(user);
- }
-
- return {
- users: response.users,
- nextPageToken: response.nextPageToken,
- };
- };
-
- const fetchUser = async (name: string, silent = false) => {
- const request = create(GetUserRequestSchema, {
- name,
- });
- return await userServiceClientConnect.getUser(request, {
- contextValues: createContextValues().set(silentContextKey, silent),
- });
- };
-
- const createUser = async (user: User) => {
- const request = create(CreateUserRequestSchema, {
- user: user,
- });
- const response = await userServiceClientConnect.createUser(request);
- actuatorStore.updateUserStat(1);
- return setUser(response);
- };
-
- const updateUser = async (updateUserRequest: UpdateUserRequest) => {
- const name = updateUserRequest.user?.name || "";
- const originData = await getOrFetchUserByIdentifier({
- identifier: name,
- fallback: false,
- });
- if (!isValidUserName(originData.name)) {
- throw new Error(`user with name ${name} not found`);
- }
-
- const request = create(UpdateUserRequestSchema, {
- user: updateUserRequest.user,
- updateMask: updateUserRequest.updateMask,
- otpCode: updateUserRequest.otpCode,
- regenerateTempMfaSecret: updateUserRequest.regenerateTempMfaSecret,
- regenerateRecoveryCodes: updateUserRequest.regenerateRecoveryCodes,
- });
- const response = await userServiceClientConnect.updateUser(request);
-
- return setUser(response);
- };
-
- const updateEmail = async (oldEmail: string, newEmail: string) => {
- const originData = await getOrFetchUserByIdentifier({
- identifier: oldEmail,
- fallback: false,
- });
- if (!isValidUserName(originData.name)) {
- throw new Error(`user with email ${oldEmail} not found`);
- }
- const oldName = originData.name;
- const response = await userServiceClientConnect.updateEmail({
- name: `users/${oldEmail}`,
- email: newEmail,
- });
- // Remove old cache entry since the user's name changes with email
- if (oldName !== response.name) {
- userMapByName.value.delete(oldName);
- }
- return setUser(response);
- };
-
- const archiveUser = async (name: string) => {
- const request = create(DeleteUserRequestSchema, {
- name,
- });
- await userServiceClientConnect.deleteUser(request);
- actuatorStore.updateUserStat(-1);
-
- const user = userMapByName.value.get(name);
- if (user) {
- user.state = State.DELETED;
- }
- };
-
- const restoreUser = async (name: string) => {
- const request = create(UndeleteUserRequestSchema, {
- name,
- });
- const response = await userServiceClientConnect.undeleteUser(request);
- actuatorStore.updateUserStat(1);
- return setUser(response);
- };
-
- const batchGetOrFetchUsers = async (userNameList: string[]) => {
- const validList = uniq(userNameList).filter(
- (name) =>
- Boolean(name) &&
- (name.startsWith(userNamePrefix) || name.startsWith(userBindingPrefix))
- );
- const pendingFetch = validList
- .filter((name) => {
- return getUserByIdentifier(name) === undefined;
- })
- .map((name) => ensureUserFullName(name));
-
- if (pendingFetch.length === 0) {
- return validList.map(
- (name) => getUserByIdentifier(name) ?? unknownUser(name)
- );
- }
-
- try {
- if (pendingFetch.length > 0) {
- const request = create(BatchGetUsersRequestSchema, {
- names: pendingFetch,
- });
- const response = await userServiceClientConnect.batchGetUsers(request, {
- contextValues: createContextValues().set(silentContextKey, true),
- });
- for (const user of response.users) {
- setUser(user);
- }
- }
- } finally {
- return validList.map(
- (name) => getUserByIdentifier(name) ?? unknownUser(name)
- );
- }
- };
-
- const getOrFetchUserByIdentifier = async ({
- identifier,
- silent = true,
- fallback = true,
- }: {
- identifier: string;
- silent?: boolean;
- fallback?: boolean;
- }) => {
- const user = getUserByIdentifier(identifier);
- if (user) {
- return user;
- }
-
- const fullname = ensureUserFullName(identifier);
- if (!isValidUserName(fullname)) {
- return unknownUser();
- }
- const request = fetchUser(fullname, silent)
- .then((user) => setUser(user))
- .catch(() => unknownUser(fallback ? fullname : ""));
- return request;
- };
-
- const getUserByIdentifier = (identifier: string) => {
- if (!identifier) {
- return;
- }
- const id = extractUserEmail(identifier);
- if (Number.isNaN(Number(id))) {
- return [...userMapByName.value.values()].find(
- (user) => user.email === id
- );
- }
- return userMapByName.value.get(`${userNamePrefix}${id}`);
- };
-
- return {
- allUser,
- fetchCurrentUser,
- fetchUserList,
- createUser,
- updateUser,
- updateEmail,
- batchGetOrFetchUsers,
- getOrFetchUserByIdentifier,
- getUserByIdentifier,
- archiveUser,
- restoreUser,
- };
-});
-
-export const getUpdateMaskFromUsers = (
- origin: User,
- update: User | Partial<User>
-): string[] => {
- const updateMask: string[] = [];
- if (!isUndefined(update.title) && !isEqual(origin.title, update.title)) {
- updateMask.push("title");
- }
- if (!isUndefined(update.email) && !isEqual(origin.email, update.email)) {
- updateMask.push("email");
- }
- if (!isUndefined(update.password) && update.password !== "") {
- updateMask.push("password");
- }
- if (!isUndefined(update.phone) && !isEqual(origin.phone, update.phone)) {
- updateMask.push("phone");
- }
- return updateMask;
-};
diff --git a/frontend/src/store/modules/v1/actuator.ts b/frontend/src/store/modules/v1/actuator.ts
deleted file mode 100644
index a7a33771d8..0000000000
--- a/frontend/src/store/modules/v1/actuator.ts
+++ /dev/null
@@ -1,176 +0,0 @@
-import { useLocalStorage } from "@vueuse/core";
-import { defineStore } from "pinia";
-import semver from "semver";
-import { computed, ref } from "vue";
-import { actuatorServiceClientConnect } from "@/connect";
-import { type AppFeatures, type AppProfile, defaultAppProfile } from "@/types";
-import type { ActuatorInfo } from "@/types/proto-es/v1/actuator_service_pb";
-import { STORAGE_KEY_ONBOARDING } from "@/utils";
-
-const EXTERNAL_URL_PLACEHOLDER =
- "https://docs.bytebase.com/get-started/self-host/external-url";
-
-export const useActuatorV1Store = defineStore("actuator_v1", () => {
- // State
- const initialized = ref(false);
- const serverInfo = ref<ActuatorInfo | undefined>(undefined);
- const serverInfoTs = ref(0);
- const appProfile = ref<AppProfile>(defaultAppProfile());
- const onboardingState = useLocalStorage<{
- consumed: string[];
- }>(STORAGE_KEY_ONBOARDING, {
- consumed: [],
- });
-
- // Getters
- const changelogURL = computed(() => {
- const version = semver.valid(serverInfo.value?.version);
- if (!version) {
- return "";
- }
- return `https://docs.bytebase.com/changelog/bytebase-${version.split(".").join("-")}/`;
- });
-
- const info = computed(() => serverInfo.value);
-
- const version = computed(() => serverInfo.value?.version || "");
-
- const gitCommitBE = computed(() => {
- const commit = serverInfo.value?.gitCommit ?? "";
- return commit === "" ? "unknown" : commit;
- });
-
- const gitCommitFE = computed(() => {
- const commit = import.meta.env.GIT_COMMIT ?? "";
- return commit === "" ? "unknown" : commit;
- });
-
- const isDocker = computed(() => serverInfo.value?.docker || false);
-
- const isSaaSMode = computed(() => serverInfo.value?.saas || false);
-
- const workspaceResourceName = computed(
- () => serverInfo.value?.workspace ?? ""
- );
-
- const needConfigureExternalUrl = computed(() => {
- if (!serverInfo.value) return false;
- const url = serverInfo.value?.externalUrl ?? "";
- return url === "" || url === EXTERNAL_URL_PLACEHOLDER;
- });
-
- const activatedInstanceCount = computed(
- () => serverInfo.value?.activatedInstanceCount ?? 0
- );
-
- const totalInstanceCount = computed(
- () => serverInfo.value?.totalInstanceCount ?? 0
- );
-
- const replicaCount = computed(() => serverInfo.value?.replicaCount ?? 1);
-
- const activeUserCount = computed(
- () => serverInfo.value?.activatedUserCount ?? 0
- );
-
- const userCountInIam = computed(() => serverInfo.value?.userCountInIam ?? 0);
-
- const enableOnboarding = computed(() => {
- return activeUserCount.value === 1 && !isSaaSMode.value;
- });
-
- const updateUserStat = (count: number) => {
- if (!serverInfo.value) {
- return;
- }
- serverInfo.value.activatedUserCount += count;
- serverInfo.value.activatedUserCount = Math.max(
- 0,
- serverInfo.value.activatedUserCount
- );
- };
-
- const quickStartEnabled = computed(() => {
- if (useAppFeature("bb.feature.hide-quick-start").value) {
- return false;
- }
- if (!serverInfo.value?.enableSample) {
- return false;
- }
-
- // Hide quickstart if there are more than 1 active users.
- return activeUserCount.value <= 1;
- });
-
- const setServerInfo = (info: ActuatorInfo) => {
- serverInfo.value = info;
- serverInfoTs.value = Date.now();
- };
-
- const fetchActuatorInfo = async (workspace?: string) => {
- return actuatorServiceClientConnect.getActuatorInfo({
- name: workspace ?? "",
- });
- };
-
- const fetchServerInfo = async (workspace?: string) => {
- const info = await fetchActuatorInfo(workspace);
- setServerInfo(info);
- return info;
- };
-
- const tryToRemindRefresh = async (): Promise<boolean> => {
- if (Date.now() - serverInfoTs.value >= 1000 * 60 * 30) {
- await fetchServerInfo(workspaceResourceName.value);
- }
- if (gitCommitBE.value === "unknown" || gitCommitFE.value === "unknown") {
- return false;
- }
- return gitCommitBE.value !== gitCommitFE.value;
- };
-
- const setupSample = async () => {
- await actuatorServiceClientConnect.setupSample({});
- };
-
- const overrideAppFeatures = (overrides: Partial<AppFeatures>) => {
- Object.assign(appProfile.value.features, overrides);
- };
-
- return {
- // State
- initialized,
- serverInfo,
- serverInfoTs,
- appProfile,
- onboardingState,
- // Getters
- changelogURL,
- info,
- version,
- gitCommitBE,
- gitCommitFE,
- isDocker,
- isSaaSMode,
- workspaceResourceName,
- needConfigureExternalUrl,
- activatedInstanceCount,
- totalInstanceCount,
- replicaCount,
- quickStartEnabled,
- enableOnboarding,
- activeUserCount,
- userCountInIam,
- // Actions
- updateUserStat,
- setServerInfo,
- fetchServerInfo,
- tryToRemindRefresh,
- setupSample,
- overrideAppFeatures,
- };
-});
-
-export const useAppFeature = <T extends keyof AppFeatures>(feature: T) => {
- return computed(() => useActuatorV1Store().appProfile.features[feature]);
-};
diff --git a/frontend/src/store/modules/v1/auth.ts b/frontend/src/store/modules/v1/auth.ts
deleted file mode 100644
index 978d848199..0000000000
--- a/frontend/src/store/modules/v1/auth.ts
+++ /dev/null
@@ -1,281 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { Code, createContextValues } from "@connectrpc/connect";
-import { useLocalStorage } from "@vueuse/core";
-import { uniqueId } from "lodash-es";
-import { defineStore } from "pinia";
-import { computed, ref } from "vue";
-import { authServiceClientConnect } from "@/connect";
-import { ignoredCodesContextKey } from "@/connect/context-key";
-import { router } from "@/router";
-import {
- AUTH_MFA_MODULE,
- AUTH_PASSWORD_RESET_MODULE,
- AUTH_PROFILE_SETUP_MODULE,
- AUTH_SIGNIN_MODULE,
-} from "@/router/auth";
-import { SETUP_MODULE } from "@/router/setup";
-import { SQL_EDITOR_HOME_MODULE } from "@/router/sqlEditor";
-import {
- useActuatorV1Store,
- useAppFeature,
- useUserStore,
- useWorkspaceV1Store,
-} from "@/store";
-import { UNKNOWN_USER_NAME, unknownUser } from "@/types";
-import {
- type LoginRequest,
- LoginRequestSchema,
- SendEmailLoginCodeRequestSchema,
- SignupRequestSchema,
-} from "@/types/proto-es/v1/auth_service_pb";
-import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";
-import type { User } from "@/types/proto-es/v1/user_service_pb";
-import { storageKeyResetPassword } from "@/utils";
-import { extractUserEmail } from "./common";
-
-export const useAuthStore = defineStore("auth_v1", () => {
- const userStore = useUserStore();
- const authSessionKey = ref<string>(uniqueId());
- const actuatorStore = useActuatorV1Store();
- const unauthenticatedOccurred = ref<boolean>(false);
- // Format: users/{email}. Changes when user email is updated.
- const currentUserName = ref<string | undefined>(undefined);
- // Flag to suppress "logged in as another user" notification during self email update
- const isSelfEmailUpdate = ref(false);
-
- const isLoggedIn = computed(() => {
- return (
- Boolean(currentUserName.value) &&
- currentUserName.value !== UNKNOWN_USER_NAME
- );
- });
-
- const currentUserEmail = computed(() =>
- extractUserEmail(currentUserName.value || "")
- );
-
- const requireResetPassword = computed(() => {
- if (!isLoggedIn.value) {
- return false;
- }
- return useLocalStorage<boolean>(
- storageKeyResetPassword(currentUserEmail.value),
- false
- ).value;
- });
-
- const setRequireResetPassword = (requireResetPassword: boolean) => {
- if (!isLoggedIn.value) {
- return false;
- }
- const needResetPasswordCache = useLocalStorage<boolean>(
- storageKeyResetPassword(currentUserEmail.value),
- false
- );
- needResetPasswordCache.value = requireResetPassword;
- };
-
- const getRedirectQuery = () => {
- const query = new URLSearchParams(window.location.search);
- return query.get("redirect");
- };
-
- // sometimes we have to redirect users even if we don't want to redirect them.
- // for example, the user is forced to reset their password,
- // or the user is using the LDAP to signin.
- const login = async ({
- request,
- redirect = true,
- redirectUrl,
- }: {
- request: LoginRequest;
- redirect?: boolean;
- redirectUrl?: string;
- }) => {
- const resp = await authServiceClientConnect.login(
- create(LoginRequestSchema, {
- ...request,
- web: true,
- }),
- {
- contextValues: createContextValues().set(ignoredCodesContextKey, [
- Code.NotFound,
- ]),
- }
- );
- let nextPage = redirectUrl ?? (getRedirectQuery() || "/");
- if (resp.mfaTempToken) {
- unauthenticatedOccurred.value = false;
- return router.push({
- name: AUTH_MFA_MODULE,
- query: {
- mfaTempToken: resp.mfaTempToken,
- redirect: nextPage,
- },
- });
- }
-
- const user = await fetchCurrentUser();
- unauthenticatedOccurred.value = !user;
-
- if (unauthenticatedOccurred.value) {
- return;
- }
-
- setRequireResetPassword(resp.requireResetPassword);
- await actuatorStore.fetchServerInfo(user?.workspace);
- // Re-fetch the current workspace now that we're authenticated — the
- // workspace store watcher may have tried (and failed) pre-login when
- // workspaceResourceName was already set from the signin page's actuator fetch.
- await useWorkspaceV1Store().fetchCurrentWorkspace();
-
- // After user login, we need to reset the auth session key.
- authSessionKey.value = uniqueId();
-
- const mode = useAppFeature("bb.feature.database-change-mode");
- if (mode.value === DatabaseChangeMode.EDITOR) {
- const route = router.resolve({
- name: SQL_EDITOR_HOME_MODULE,
- });
- nextPage = route.fullPath;
- }
- if (resp.requireResetPassword) {
- return router.push({
- name: AUTH_PASSWORD_RESET_MODULE,
- query: {
- redirect: nextPage,
- },
- });
- }
- if (actuatorStore.isSaaSMode && resp.user && needsProfileSetup(resp.user)) {
- return router.push({
- name: AUTH_PROFILE_SETUP_MODULE,
- query: {
- redirect: nextPage,
- },
- });
- }
- if (redirect) {
- router.replace(nextPage);
- }
- };
-
- const signup = async (request: Partial<User>) => {
- await authServiceClientConnect.signup(
- create(SignupRequestSchema, {
- email: request.email,
- title: request.name,
- password: request.password,
- })
- );
-
- // Signup sets HTTP-only cookies automatically.
- // Fetch the current user and proceed with post-login flow.
- const user = await fetchCurrentUser();
- unauthenticatedOccurred.value = !user;
- if (unauthenticatedOccurred.value) {
- return;
- }
-
- await actuatorStore.fetchServerInfo(user?.workspace);
- authSessionKey.value = uniqueId();
-
- if (actuatorStore.enableOnboarding) {
- return router.replace({ name: SETUP_MODULE });
- }
-
- const mode = useAppFeature("bb.feature.database-change-mode");
- let nextPage = getRedirectQuery() || "/";
- if (mode.value === DatabaseChangeMode.EDITOR) {
- nextPage = router.resolve({ name: SQL_EDITOR_HOME_MODULE }).fullPath;
- }
- router.replace(nextPage);
- };
-
- const logout = async () => {
- try {
- await authServiceClientConnect.logout({});
- } catch {
- // nothing
- } finally {
- unauthenticatedOccurred.value = false;
- const pathname = location.pathname;
- // Replace and reload the page to clear frontend state directly.
- window.location.href = router.resolve({
- name: AUTH_SIGNIN_MODULE,
- query: {
- redirect:
- getRedirectQuery() ||
- (pathname.startsWith("/auth") ? undefined : pathname),
- },
- }).fullPath;
- }
- };
-
- const fetchCurrentUser = async () => {
- try {
- const user = await userStore.fetchCurrentUser();
- currentUserName.value = user.name;
- return user;
- } catch {
- // do nothing.
- }
- };
-
- const sendEmailLoginCode = async (email: string, workspace?: string) => {
- await authServiceClientConnect.sendEmailLoginCode(
- create(SendEmailLoginCodeRequestSchema, { email, workspace })
- );
- };
-
- // Update currentUserName after self email change.
- // Sets flag to suppress "logged in as another user" notification.
- const updateCurrentUserNameForEmailChange = (newName: string) => {
- isSelfEmailUpdate.value = true;
- currentUserName.value = newName;
- };
-
- return {
- currentUserName,
- isLoggedIn,
- unauthenticatedOccurred,
- requireResetPassword,
- authSessionKey,
- isSelfEmailUpdate,
- login,
- signup,
- logout,
- fetchCurrentUser,
- setRequireResetPassword,
- sendEmailLoginCode,
- updateCurrentUserNameForEmailChange,
- };
-});
-
-export const getCurrentUserV1 = () => {
- const authStore = useAuthStore();
- const userStore = useUserStore();
- return (
- userStore.getUserByIdentifier(authStore.currentUserName || "") ||
- unknownUser()
- );
-};
-
-export const useCurrentUserV1 = () => computed(() => getCurrentUserV1());
-
-/**
- * Returns true if the user should be prompted to set up their profile.
- * First-time login with an auto-generated name (email local-part or full email).
- */
-function needsProfileSetup(user: User): boolean {
- // Only prompt on first login (lastLoginTime is not set yet).
- if (user.profile?.lastLoginTime) return false;
- const name = user.title;
- const email = user.email;
- if (!name || !email) return false;
- // Name matches full email or email local-part → auto-generated.
- if (name === email) return true;
- const atIndex = email.indexOf("@");
- if (atIndex > 0 && name === email.substring(0, atIndex)) return true;
- return false;
-}
diff --git a/frontend/src/store/modules/v1/common.ts b/frontend/src/store/modules/v1/common.ts
index fb69371c20..1af72399f2 100644
--- a/frontend/src/store/modules/v1/common.ts
+++ b/frontend/src/store/modules/v1/common.ts
@@ -304,3 +304,10 @@ export const isDatabaseName = (name: string): boolean => {
const regex = /^instances\/([^/]+)\/databases\/(.+)$/;
return regex.test(name);
};
+
+export const DEFAULT_MAX_RESULT_SIZE_IN_MB = 100;
+
+export const ensureGroupIdentifier = (id: string) => {
+ const email = extractGroupEmail(id);
+ return `${groupNamePrefix}${email}`;
+};
diff --git a/frontend/src/store/modules/v1/environment.ts b/frontend/src/store/modules/v1/environment.ts
deleted file mode 100644
index 22a8a4ae03..0000000000
--- a/frontend/src/store/modules/v1/environment.ts
+++ /dev/null
@@ -1,226 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { orderBy } from "lodash-es";
-import { defineStore } from "pinia";
-import type { ResourceId } from "@/types";
-import {
- isValidEnvironmentName,
- NULL_ENVIRONMENT_NAME,
- nullEnvironment,
- unknownEnvironment,
-} from "@/types";
-import type {
- EnvironmentSetting,
- EnvironmentSetting_Environment,
-} from "@/types/proto-es/v1/setting_service_pb";
-import {
- EnvironmentSetting_EnvironmentSchema,
- EnvironmentSettingSchema,
- Setting_SettingName,
- SettingValueSchema,
-} from "@/types/proto-es/v1/setting_service_pb";
-import type { Environment } from "@/types/v1/environment";
-import { hasWorkspacePermissionV2 } from "@/utils";
-import { environmentNamePrefix, getEnvironmentId } from "./common";
-import { useSettingV1Store } from "./setting";
-
-interface EnvironmentState {
- environmentMapById: Map<ResourceId, Environment>;
-}
-
-const getEnvironmentByIdMap = (
- environments: Environment[]
-): Map<ResourceId, Environment> => {
- return new Map(
- environments.map((environment) => [environment.id, environment])
- );
-};
-
-const convertToEnvironments = (
- environments: EnvironmentSetting_Environment[]
-): Environment[] => {
- return environments.map<Environment>((env, i) => {
- return {
- ...create(EnvironmentSetting_EnvironmentSchema, {
- name: `${environmentNamePrefix}${env.id}`,
- id: env.id,
- title: env.title,
- color: env.color,
- tags: env.tags,
- }),
- order: i,
- };
- });
-};
-
-const convertEnvironment = (
- env: Environment
-): EnvironmentSetting_Environment => {
- return create(EnvironmentSetting_EnvironmentSchema, {
- name: env.name,
- id: env.id,
- title: env.title,
- color: env.color,
- tags: env.tags,
- });
-};
-
-const convertEnvironments = (
- environments: Environment[]
-): EnvironmentSetting_Environment[] => {
- return environments.map(convertEnvironment);
-};
-
-const updateEnvironmentSetting = async (
- environment: EnvironmentSetting
-): Promise<Environment[]> => {
- const response = await useSettingV1Store().upsertSetting({
- name: Setting_SettingName.ENVIRONMENT,
- value: create(SettingValueSchema, {
- value: {
- case: "environment",
- value: environment,
- },
- }),
- });
-
- // Extract environments from proto-es response
- if (response.value?.value?.case === "environment") {
- const settingEnvironments = response.value.value.value.environments ?? [];
- return convertToEnvironments(settingEnvironments);
- }
- return [];
-};
-
-export const useEnvironmentV1Store = defineStore("environment_v1", {
- state: (): EnvironmentState => ({
- environmentMapById: new Map(),
- }),
- getters: {
- environmentList(state) {
- return orderBy(
- Array.from(state.environmentMapById.values()),
- (env) => env.order,
- "asc"
- );
- },
- },
- actions: {
- async fetchEnvironments(silent = false) {
- if (!hasWorkspacePermissionV2("bb.settings.getEnvironment")) {
- return;
- }
- const setting = await useSettingV1Store().getOrFetchSettingByName(
- Setting_SettingName.ENVIRONMENT,
- silent
- );
- if (setting?.value?.value?.case === "environment") {
- const settingEnvironments =
- setting.value.value.value.environments ?? [];
- const environments = convertToEnvironments(settingEnvironments);
- this.environmentMapById = getEnvironmentByIdMap(environments);
- }
- },
- async createEnvironment(
- environment: Partial<Environment>
- ): Promise<Environment> {
- const e = create(EnvironmentSetting_EnvironmentSchema, {
- name: "",
- id: environment.id ?? "",
- title: environment.title ?? "",
- color: environment.color ?? "",
- tags: environment.tags ?? {},
- });
- const newEnvironmentSettingValue = [
- ...convertEnvironments(this.environmentList),
- e,
- ];
-
- const newEnvironments = await updateEnvironmentSetting(
- create(EnvironmentSettingSchema, {
- environments: newEnvironmentSettingValue,
- })
- );
-
- const newEnvironmentMapById = getEnvironmentByIdMap(newEnvironments);
- this.environmentMapById = newEnvironmentMapById;
- const newEnvironment = newEnvironmentMapById.get(environment.id ?? "");
- if (!newEnvironment) {
- throw new Error(`environment with id ${environment.id} not found`);
- }
- return newEnvironment;
- },
- async updateEnvironment(
- update: Partial<Environment>
- ): Promise<Environment> {
- const originData = this.getEnvironmentByName(update.id || "");
- if (!originData) {
- throw new Error(`environment with id ${update.id} not found`);
- }
- const newEnvironments = await updateEnvironmentSetting(
- create(EnvironmentSettingSchema, {
- environments: convertEnvironments(
- this.environmentList.map((environment) => {
- if (environment.id === update.id) {
- environment.title = update.title ?? environment.title;
- environment.color = update.color ?? environment.color;
- environment.tags = update.tags ?? environment.tags;
- environment.order = update.order ?? environment.order;
- }
- return environment;
- })
- ),
- })
- );
-
- const newEnvironmentMapById = getEnvironmentByIdMap(newEnvironments);
- this.environmentMapById = newEnvironmentMapById;
- const newEnvironment = newEnvironmentMapById.get(update.id ?? "");
- if (!newEnvironment) {
- throw new Error(`environment with id ${update.id} not found`);
- }
- return newEnvironment;
- },
- async deleteEnvironment(name: string): Promise<void> {
- const id = getEnvironmentId(name);
- const newEnvironments = await updateEnvironmentSetting(
- create(EnvironmentSettingSchema, {
- environments: convertEnvironments(
- this.environmentList.filter((environment) => environment.id !== id)
- ),
- })
- );
- this.environmentMapById = getEnvironmentByIdMap(newEnvironments);
- },
- async reorderEnvironmentList(
- orderedEnvironmentList: Environment[]
- ): Promise<Environment[]> {
- const newEnvironments = await updateEnvironmentSetting(
- create(EnvironmentSettingSchema, {
- environments: convertEnvironments(orderedEnvironmentList),
- })
- );
- this.environmentMapById = getEnvironmentByIdMap(newEnvironments);
- return newEnvironments;
- },
- getEnvironmentByName(name: string, fallback: boolean = true) {
- if (name === NULL_ENVIRONMENT_NAME) {
- return nullEnvironment();
- }
- const id = getEnvironmentId(name);
- if (!id) {
- return unknownEnvironment();
- }
- const environment =
- this.environmentMapById.get(id) ?? unknownEnvironment();
- if (!isValidEnvironmentName(environment.name) && fallback) {
- return {
- ...environment,
- id,
- name,
- title: id,
- };
- }
- return environment;
- },
- },
-});
diff --git a/frontend/src/store/modules/v1/group.ts b/frontend/src/store/modules/v1/group.ts
deleted file mode 100644
index 980968c6df..0000000000
--- a/frontend/src/store/modules/v1/group.ts
+++ /dev/null
@@ -1,176 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { createContextValues } from "@connectrpc/connect";
-import { orderBy, uniq } from "lodash-es";
-import { defineStore } from "pinia";
-import { computed, reactive } from "vue";
-import { groupServiceClientConnect } from "@/connect";
-import { silentContextKey } from "@/connect/context-key";
-import { isValidProjectName } from "@/types";
-import type { Group } from "@/types/proto-es/v1/group_service_pb";
-import {
- BatchGetGroupsRequestSchema,
- CreateGroupRequestSchema,
- DeleteGroupRequestSchema,
- GetGroupRequestSchema,
- ListGroupsRequestSchema,
- UpdateGroupRequestSchema,
-} from "@/types/proto-es/v1/group_service_pb";
-import { hasWorkspacePermissionV2 } from "@/utils";
-import { extractGroupEmail, groupNamePrefix } from "./common";
-
-export interface GroupFilter {
- query?: string;
- project?: string;
-}
-
-const getListGroupFilter = (params: GroupFilter) => {
- const filter = [];
- const search = params.query?.trim()?.toLowerCase();
- if (search) {
- filter.push(`(title.contains("${search}") || email.contains("${search}"))`);
- }
- if (isValidProjectName(params.project)) {
- filter.push(`project == "${params.project}"`);
- }
-
- return filter.join(" && ");
-};
-
-export const ensureGroupIdentifier = (id: string) => {
- const email = extractGroupEmail(id);
- return `${groupNamePrefix}${email}`;
-};
-
-export const useGroupStore = defineStore("group", () => {
- const groupMapByName = reactive(new Map<string, Group>());
-
- // Getters
- const groupList = computed(() => {
- return orderBy(
- Array.from(groupMapByName.values()),
- (group) => group.name,
- "asc"
- );
- });
-
- const getGroupByIdentifier = (id: string) => {
- return groupMapByName.get(ensureGroupIdentifier(id));
- };
-
- const fetchGroupList = async (params: {
- pageSize: number;
- pageToken?: string;
- filter?: GroupFilter;
- }): Promise<{
- groups: Group[];
- nextPageToken: string;
- }> => {
- if (!hasWorkspacePermissionV2("bb.groups.list")) {
- return {
- groups: [],
- nextPageToken: "",
- };
- }
- const request = create(ListGroupsRequestSchema, {
- pageSize: params.pageSize,
- pageToken: params.pageToken,
- filter: getListGroupFilter(params.filter ?? {}),
- });
- // Ignore errors and silent the request.
- const { groups, nextPageToken } =
- await groupServiceClientConnect.listGroups(request, {
- contextValues: createContextValues().set(silentContextKey, true),
- });
- for (const group of groups) {
- groupMapByName.set(group.name, group);
- }
- return { groups, nextPageToken };
- };
-
- const batchFetchGroups = async (groupNameList: string[]) => {
- if (groupNameList.length === 0) {
- return [];
- }
- const request = create(BatchGetGroupsRequestSchema, {
- names: groupNameList.map(ensureGroupIdentifier),
- });
- const { groups } = await groupServiceClientConnect.batchGetGroups(request, {
- contextValues: createContextValues().set(silentContextKey, true),
- });
- for (const group of groups) {
- groupMapByName.set(group.name, group);
- }
- return groups;
- };
-
- const batchGetOrFetchGroups = async (groupNames: string[]) => {
- const validGroupList = uniq(groupNames).filter((groupName) => !!groupName);
- const pendingFetch = validGroupList.filter((groupName) => {
- const group = getGroupByIdentifier(groupName);
- if (group) {
- return false;
- }
- return true;
- });
- await batchFetchGroups(pendingFetch);
- return validGroupList.map(getGroupByIdentifier);
- };
-
- const getOrFetchGroupByIdentifier = async (id: string) => {
- if (!hasWorkspacePermissionV2("bb.groups.get")) {
- return;
- }
-
- const existed = getGroupByIdentifier(id);
- if (existed) {
- return existed;
- }
-
- const request = create(GetGroupRequestSchema, {
- name: ensureGroupIdentifier(id),
- });
- const group = await groupServiceClientConnect.getGroup(request, {
- contextValues: createContextValues().set(silentContextKey, true),
- });
- groupMapByName.set(group.name, group);
- return group;
- };
-
- const deleteGroup = async (name: string) => {
- const request = create(DeleteGroupRequestSchema, { name });
- await groupServiceClientConnect.deleteGroup(request);
- groupMapByName.delete(name);
- };
-
- const createGroup = async (group: Group) => {
- const request = create(CreateGroupRequestSchema, {
- group: group,
- groupEmail: extractGroupEmail(group.name),
- });
- const response = await groupServiceClientConnect.createGroup(request);
- groupMapByName.set(response.name, response);
- return response;
- };
-
- const updateGroup = async (group: Group) => {
- const request = create(UpdateGroupRequestSchema, {
- group: group,
- updateMask: { paths: ["title", "description", "members"] },
- allowMissing: false,
- });
- const response = await groupServiceClientConnect.updateGroup(request);
- groupMapByName.set(response.name, response);
- return response;
- };
-
- return {
- groupList,
- fetchGroupList,
- batchGetOrFetchGroups,
- getGroupByIdentifier,
- getOrFetchGroupByIdentifier,
- deleteGroup,
- updateGroup,
- createGroup,
- };
-});
diff --git a/frontend/src/store/modules/v1/index.ts b/frontend/src/store/modules/v1/index.ts
index 0dbcf8f237..92d05656a2 100644
--- a/frontend/src/store/modules/v1/index.ts
+++ b/frontend/src/store/modules/v1/index.ts
@@ -1,11 +1,4 @@
-export * from "./actuator";
-export * from "./auth";
+// The legacy Pinia v1 stores have been removed (migrated to the React app
+// store at `@/react/stores/app`). Only the pinia-free resource-name / helper
+// module remains.
export * from "./common";
-export * from "./environment";
-export * from "./group";
-export * from "./permission";
-export * from "./policy";
-export * from "./projectIamPolicy";
-export * from "./setting";
-export * from "./subscription";
-export * from "./workspace";
diff --git a/frontend/src/store/modules/v1/permission.ts b/frontend/src/store/modules/v1/permission.ts
deleted file mode 100644
index 5e7354b366..0000000000
--- a/frontend/src/store/modules/v1/permission.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-import { uniq } from "lodash-es";
-import { defineStore } from "pinia";
-import { computed, shallowReactive } from "vue";
-import { type Permission, PRESET_WORKSPACE_ROLES } from "@/types";
-import type { Project } from "@/types/proto-es/v1/project_service_pb";
-import { type User } from "@/types/proto-es/v1/user_service_pb";
-import { filterBindingsByUserName } from "@/utils";
-import { useRoleStore } from "../role";
-import { useCurrentUserV1 } from "./auth";
-import { useProjectIamPolicyStore } from "./projectIamPolicy";
-import { useWorkspaceV1Store } from "./workspace";
-
-export const usePermissionStore = defineStore("permission", () => {
- const projectRoleListCache = shallowReactive(new Map<string, string[]>());
- const roleStore = useRoleStore();
- const currentUser = useCurrentUserV1();
- const workspaceStore = useWorkspaceV1Store();
- const projectIamPolicyStore = useProjectIamPolicyStore();
-
- // currentRolesInWorkspace returns role for the current user in the workspace level
- // it also includes the role for the user group
- const currentRolesInWorkspace = computed(() => {
- return workspaceStore.getWorkspaceRolesByName(currentUser.value.name);
- });
-
- const currentPermissions = computed(() => {
- return new Set(
- [...currentRolesInWorkspace.value]
- .map((role) => roleStore.getRoleByName(role))
- .flatMap((role) => (role ? role.permissions : []) as Permission[])
- );
- });
-
- const currentRoleListInProjectV1 = (project: Project) => {
- const key = `${currentUser.value.name}@@${project.name}`;
- const cached = projectRoleListCache.get(key);
- if (cached) {
- return cached;
- }
-
- const workspaceLevelProjectRoles = [
- ...currentRolesInWorkspace.value,
- ].filter((role) => !PRESET_WORKSPACE_ROLES.includes(role));
-
- const iamPolicy = projectIamPolicyStore.getProjectIamPolicy(project.name);
- const projectBindings = filterBindingsByUserName({
- policy: iamPolicy,
- name: currentUser.value.name,
- ignoreGroup: false,
- });
-
- const result = uniq([
- ...projectBindings.map((binding) => binding.role),
- ...workspaceLevelProjectRoles,
- ]);
- if (projectBindings.length > 0) {
- // Note: do not set cache if no project IAM policy.
- // The project IAM policy may not initialized at this time.
- projectRoleListCache.set(key, result);
- }
- return result;
- };
-
- const currentPermissionsInProjectV1 = (project: Project): Set<Permission> => {
- const roles = currentRoleListInProjectV1(project);
- const permissions = new Set(
- roles
- .map((role) => roleStore.getRoleByName(role))
- .flatMap((role) => (role ? role.permissions : []) as Permission[])
- );
- return permissions;
- };
-
- const invalidCacheByProject = (project: string) => {
- const roleListKeys = Array.from(projectRoleListCache.keys()).filter((key) =>
- key.endsWith(`@@${project}`)
- );
- roleListKeys.forEach((key) => projectRoleListCache.delete(key));
- };
-
- const invalidCacheByUser = (user: User) => {
- const roleListKeys = Array.from(projectRoleListCache.keys()).filter((key) =>
- key.startsWith(`${user.name}@@`)
- );
- roleListKeys.forEach((key) => projectRoleListCache.delete(key));
- };
-
- return {
- currentPermissions,
- currentRolesInWorkspace,
- currentRoleListInProjectV1,
- currentPermissionsInProjectV1,
- invalidCacheByProject,
- invalidCacheByUser,
- };
-});
diff --git a/frontend/src/store/modules/v1/policy.ts b/frontend/src/store/modules/v1/policy.ts
deleted file mode 100644
index fee29e01e0..0000000000
--- a/frontend/src/store/modules/v1/policy.ts
+++ /dev/null
@@ -1,321 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { Code, ConnectError, createContextValues } from "@connectrpc/connect";
-import { defineStore } from "pinia";
-import { computed, reactive, ref, unref, watchEffect } from "vue";
-import { orgPolicyServiceClientConnect } from "@/connect";
-import { silentContextKey } from "@/connect/context-key";
-import { policyNamePrefix } from "@/store/modules/v1/common";
-import type { MaybeRef } from "@/types";
-import { UNKNOWN_USER_NAME } from "@/types";
-import type {
- Policy,
- QueryDataPolicy,
-} from "@/types/proto-es/v1/org_policy_service_pb";
-import {
- DeletePolicyRequestSchema,
- GetPolicyRequestSchema,
- PolicyResourceType,
- PolicySchema,
- PolicyType,
- QueryDataPolicySchema,
- RolloutPolicySchema,
- UpdatePolicyRequestSchema,
-} from "@/types/proto-es/v1/org_policy_service_pb";
-import { useActuatorV1Store } from "./actuator";
-import { useCurrentUserV1 } from "./auth";
-
-interface PolicyState {
- policyMapByName: Map<string, Policy>;
-}
-
-export const replacePolicyTypeNameToLowerCase = (name: string) => {
- const pattern = /(^|\/)policies\/([^/]+)($|\/)/;
- const replaced = name.replace(
- pattern,
- (_: string, left: string, policyType: string, right: string) => {
- return `${left}policies/${policyType.toLowerCase()}${right}`;
- }
- );
- if (replaced.startsWith("/")) {
- return replaced.slice(1);
- }
- return replaced;
-};
-
-// Shared default returned when no DATA_QUERY policy exists for a parent.
-// Must be a stable singleton so subscribers (e.g. React useVueState) don't
-// see a new reference on every call and thrash their effects.
-const EMPTY_QUERY_DATA_POLICY: QueryDataPolicy = create(QueryDataPolicySchema, {
- maximumResultRows: -1,
-});
-
-export const usePolicyV1Store = defineStore("policy_v1", () => {
- const state = reactive<PolicyState>({
- policyMapByName: new Map(),
- });
-
- const getQueryDataPolicyByParent = (parent: string): QueryDataPolicy => {
- const policy = getPolicyByParentAndType({
- parentPath: parent,
- policyType: PolicyType.DATA_QUERY,
- });
- return policy?.policy?.case === "queryDataPolicy"
- ? policy.policy.value
- : EMPTY_QUERY_DATA_POLICY;
- };
-
- const getOrFetchPolicyByParentAndType = async ({
- parentPath,
- policyType,
- refresh,
- }: {
- parentPath: string;
- policyType: PolicyType;
- refresh?: boolean;
- }) => {
- const name = replacePolicyTypeNameToLowerCase(
- `${parentPath}/${policyNamePrefix}${PolicyType[policyType]}`
- );
- return getOrFetchPolicyByName(name, refresh);
- };
-
- const getOrFetchPolicyByName = async (name: string, refresh = false) => {
- const cachedData = getPolicyByName(replacePolicyTypeNameToLowerCase(name));
- if (cachedData && !refresh) {
- return cachedData;
- }
- try {
- const request = create(GetPolicyRequestSchema, { name });
- const policy = await orgPolicyServiceClientConnect.getPolicy(request, {
- contextValues: createContextValues().set(silentContextKey, true),
- });
- state.policyMapByName.set(policy.name, policy);
- return policy;
- } catch (error) {
- if (error instanceof ConnectError && error.code === Code.NotFound) {
- // To prevent unnecessary requests, cache empty policies if not found.
- const emptyPolicy = create(PolicySchema, { name });
- state.policyMapByName.set(name, emptyPolicy);
- }
- }
- };
-
- const getPolicyByParentAndType = ({
- parentPath,
- policyType,
- }: {
- parentPath: string;
- policyType: PolicyType;
- }) => {
- const name = replacePolicyTypeNameToLowerCase(
- `${parentPath}/${policyNamePrefix}${PolicyType[policyType]}`
- );
- return getPolicyByName(name);
- };
-
- const getPolicyByName = (name: string) => {
- const policy = state.policyMapByName.get(
- replacePolicyTypeNameToLowerCase(name)
- );
- return policy;
- };
-
- const upsertPolicy = async ({
- parentPath,
- policy,
- }: {
- parentPath: string;
- policy: Partial<Policy>;
- }) => {
- if (!policy.type) {
- throw new Error("policy type is required");
- }
- const policyName = replacePolicyTypeNameToLowerCase(
- `${parentPath}/${policyNamePrefix}${PolicyType[policy.type]}`
- );
- const fullPolicy = create(PolicySchema, {
- name: policyName,
- inheritFromParent: policy.inheritFromParent ?? false,
- type: policy.type,
- resourceType:
- policy.resourceType ?? PolicyResourceType.RESOURCE_TYPE_UNSPECIFIED,
- enforce: policy.enforce ?? false,
- policy: policy.policy,
- });
- const request = create(UpdatePolicyRequestSchema, {
- policy: fullPolicy,
- updateMask: { paths: getUpdateMaskFromPolicyType(policy.type) },
- allowMissing: true,
- });
- const response = await orgPolicyServiceClientConnect.updatePolicy(request);
- state.policyMapByName.set(response.name, response);
- return response;
- };
-
- const deletePolicy = async (name: string) => {
- const request = create(DeletePolicyRequestSchema, { name });
- await orgPolicyServiceClientConnect.deletePolicy(request);
- state.policyMapByName.delete(name);
- };
-
- return {
- getOrFetchPolicyByParentAndType,
- getOrFetchPolicyByName,
- getPolicyByParentAndType,
- upsertPolicy,
- deletePolicy,
- getQueryDataPolicyByParent,
- };
-});
-
-const formatQueryDataPolicy = (policy: QueryDataPolicy) => {
- let maximumResultRows = policy.maximumResultRows;
- if (maximumResultRows <= 0) {
- maximumResultRows = Number.MAX_VALUE;
- }
-
- return {
- disableCopyData: policy.disableCopyData,
- disableExport: policy.disableExport,
- allowAdminDataSource: policy.allowAdminDataSource,
- maximumResultRows,
- };
-};
-
-const getUpdateMaskFromPolicyType = (policyType: PolicyType) => {
- switch (policyType) {
- case PolicyType.ROLLOUT_POLICY:
- return [PolicySchema.field.rolloutPolicy.name];
- case PolicyType.MASKING_EXEMPTION:
- return [PolicySchema.field.maskingExemptionPolicy.name];
- case PolicyType.MASKING_RULE:
- return [PolicySchema.field.maskingRulePolicy.name];
- case PolicyType.DATA_QUERY:
- return [PolicySchema.field.queryDataPolicy.name];
- case PolicyType.TAG:
- return [PolicySchema.field.tagPolicy.name];
- case PolicyType.POLICY_TYPE_UNSPECIFIED:
- throw new Error("unexpected POLICY_TYPE_UNSPECIFIED");
- default:
- throw new Error(`unknown policyType ${policyType satisfies never}`);
- }
-};
-
-export const usePolicyByParentAndType = (
- params: MaybeRef<{
- parentPath: string;
- policyType: PolicyType;
- }>
-) => {
- const store = usePolicyV1Store();
- const currentUserV1 = useCurrentUserV1();
- const ready = ref(false);
-
- watchEffect(() => {
- if (currentUserV1.value.name === UNKNOWN_USER_NAME) return;
- const { policyType, parentPath } = unref(params);
- store
- .getOrFetchPolicyByParentAndType({
- parentPath,
- policyType,
- })
- .finally(() => (ready.value = true));
- });
-
- const policy = computed(() => {
- const { parentPath, policyType } = unref(params);
- return store.getPolicyByParentAndType({
- parentPath,
- policyType,
- });
- });
- return {
- policy,
- ready,
- };
-};
-
-export const useQueryDataPolicy = (project: MaybeRef<string>) => {
- const store = usePolicyV1Store();
- const actuatorStore = useActuatorV1Store();
- const ready = ref(false);
-
- watchEffect(() => {
- Promise.all([
- // Fetch workspace-level DATA_QUERY policies
- store.getOrFetchPolicyByParentAndType({
- parentPath: actuatorStore.workspaceResourceName,
- policyType: PolicyType.DATA_QUERY,
- }),
- // Fetch project-level DATA_QUERY policies
- store.getOrFetchPolicyByParentAndType({
- parentPath: unref(project),
- policyType: PolicyType.DATA_QUERY,
- }),
- ]).finally(() => (ready.value = true));
- });
-
- const policy = computed(() => {
- const workspacePolicy = formatQueryDataPolicy(
- store.getQueryDataPolicyByParent(actuatorStore.workspaceResourceName)
- );
- const projectPolicy = formatQueryDataPolicy(
- store.getQueryDataPolicyByParent(unref(project))
- );
-
- return {
- ...workspacePolicy,
- maximumResultRows: Math.min(
- workspacePolicy.maximumResultRows,
- projectPolicy.maximumResultRows
- ),
- };
- });
-
- return {
- policy,
- ready,
- };
-};
-
-// getEmptyRolloutPolicy returns a default rollout policy for UI display purposes.
-//
-// IMPORTANT: These defaults MUST match the backend defaults defined in:
-// - backend/store/policy.go: GetDefaultRolloutPolicy()
-// - backend/api/v1/org_policy_service.go: getDefaultRolloutPolicy()
-//
-// This function is used for:
-// 1. Showing default policy in creation forms (so users see what they'll get)
-// 2. Allowing users to customize before creation
-// 3. Detecting if user customized from defaults (only persist if customized)
-//
-// The backend automatically returns these defaults via GetPolicy API when no
-// custom policy exists in the database, so we only persist customizations.
-//
-// Default values:
-// - automatic: false (manual rollout required)
-// - roles: [] (no role restrictions)
-// - requiredIssueApproval: true (issue must be approved before rollout)
-// - planCheckEnforcement: ERROR_ONLY (block rollout only on errors, not warnings)
-export const getEmptyRolloutPolicy = (
- parentPath: string,
- resourceType: PolicyResourceType
-): Policy => {
- const name = replacePolicyTypeNameToLowerCase(
- `${parentPath}/${policyNamePrefix}${PolicyType[PolicyType.ROLLOUT_POLICY]}`
- );
- return create(PolicySchema, {
- name,
- inheritFromParent: false,
- type: PolicyType.ROLLOUT_POLICY,
- resourceType,
- enforce: true,
- policy: {
- case: "rolloutPolicy",
- value: create(RolloutPolicySchema, {
- automatic: false,
- roles: [],
- }),
- },
- });
-};
diff --git a/frontend/src/store/modules/v1/projectIamPolicy.ts b/frontend/src/store/modules/v1/projectIamPolicy.ts
deleted file mode 100644
index fc32ace05a..0000000000
--- a/frontend/src/store/modules/v1/projectIamPolicy.ts
+++ /dev/null
@@ -1,238 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { isUndefined, uniq } from "lodash-es";
-import { defineStore } from "pinia";
-import { computed, ref, shallowReactive, unref, watch } from "vue";
-import { projectServiceClientConnect } from "@/connect";
-import {
- ALL_USERS_USER_EMAIL,
- groupBindingPrefix,
- type MaybeRef,
- type QueryPermission,
- QueryPermissionQueryAny,
-} from "@/types";
-import type { Expr } from "@/types/proto-es/google/api/expr/v1alpha1/syntax_pb";
-import type { Database } from "@/types/proto-es/v1/database_service_pb";
-import type { IamPolicy } from "@/types/proto-es/v1/iam_policy_pb";
-import {
- GetIamPolicyRequestSchema,
- IamPolicySchema,
- SetIamPolicyRequestSchema,
-} from "@/types/proto-es/v1/iam_policy_pb";
-import type { Project } from "@/types/proto-es/v1/project_service_pb";
-import type { User } from "@/types/proto-es/v1/user_service_pb";
-import { getDatabaseProject, getUserListInBinding } from "@/utils";
-import { convertFromExpr } from "@/utils/issue/cel";
-import { useRoleStore } from "../role";
-import { useUserStore } from "../user";
-import { useCurrentUserV1 } from "./auth";
-import { getUserFullNameByType, userNamePrefix } from "./common";
-import { useGroupStore } from "./group";
-import { usePermissionStore } from "./permission";
-
-export const composePolicyBindings = async (
- bindings: { members: string[] }[],
- skipFetchUsers = false
-) => {
- const users: string[] = [];
- const groups: string[] = [];
- for (const binding of bindings) {
- for (const member of binding.members) {
- if (member.startsWith(groupBindingPrefix)) {
- groups.push(member);
- } else {
- users.push(member);
- }
- }
- }
-
- const requests: Promise<unknown>[] = [
- useGroupStore().batchGetOrFetchGroups(groups),
- ];
- if (!skipFetchUsers) {
- requests.push(useUserStore().batchGetOrFetchUsers(users));
- }
- await Promise.allSettled(requests);
-};
-
-export const useProjectIamPolicyStore = defineStore(
- "project-iam-policy",
- () => {
- const policyMap = shallowReactive(new Map<string, IamPolicy>());
-
- const setIamPolicy = async (project: string, policy: IamPolicy) => {
- await composePolicyBindings(policy.bindings);
- policyMap.set(project, policy);
- return policy;
- };
-
- const fetchProjectIamPolicy = async (project: string) => {
- const request = create(GetIamPolicyRequestSchema, {
- resource: project,
- });
- const requestPromise = projectServiceClientConnect
- .getIamPolicy(request)
- .then((response) => {
- return setIamPolicy(project, response);
- });
- return requestPromise;
- };
-
- const updateProjectIamPolicy = async (
- project: string,
- policy: IamPolicy
- ) => {
- policy.bindings.forEach((binding) => {
- if (binding.members) {
- binding.members = uniq(binding.members);
- }
- });
- const request = create(SetIamPolicyRequestSchema, {
- resource: project,
- policy: policy,
- etag: policy.etag,
- });
- const response = await projectServiceClientConnect.setIamPolicy(request);
- policyMap.set(project, response);
-
- usePermissionStore().invalidCacheByProject(project);
- };
-
- const getProjectIamPolicy = (project: string) => {
- return policyMap.get(project) ?? create(IamPolicySchema, {});
- };
-
- const getOrFetchProjectIamPolicy = async (project: string) => {
- if (!policyMap.has(project)) {
- await fetchProjectIamPolicy(project);
- }
- return getProjectIamPolicy(project);
- };
-
- // Bridge entry-point so an external fetcher (e.g. the Zustand app
- // `iam` slice) can cache its result here and reuse the permission
- // chain without a second RPC. Also invalidates the role-list cache,
- // matching `fetchProjectIamPolicy`.
- const setProjectIamPolicy = (project: string, policy: IamPolicy) => {
- policyMap.set(project, policy);
- usePermissionStore().invalidCacheByProject(project);
- };
-
- return {
- getProjectIamPolicy,
- getOrFetchProjectIamPolicy,
- setProjectIamPolicy,
- updateProjectIamPolicy,
- };
- }
-);
-
-export const useProjectIamPolicy = (project: MaybeRef<string>) => {
- const store = useProjectIamPolicyStore();
- const ready = ref(false);
- watch(
- () => unref(project),
- (project) => {
- ready.value = false;
- store.getOrFetchProjectIamPolicy(project).finally(() => {
- ready.value = true;
- });
- },
- { immediate: true }
- );
- const policy = computed(() => {
- return store.getProjectIamPolicy(unref(project));
- });
- return { policy, ready };
-};
-
-const checkProjectIAMPolicyWithExpr = (
- user: User,
- project: Project,
- requiredPermissions: QueryPermission[],
- bindingExprCheck: (expr?: Expr) => boolean
-): boolean => {
- const roleStore = useRoleStore();
- const projectIamPolicyStore = useProjectIamPolicyStore();
- const policy = projectIamPolicyStore.getProjectIamPolicy(project.name);
- // Check if the user has the permission.
- for (const binding of policy.bindings) {
- // If the user is not in the binding, then skip.
- const nameList = getUserListInBinding({
- binding,
- ignoreGroup: false,
- });
- if (
- !nameList.includes(getUserFullNameByType(user)) &&
- !nameList.includes(`${userNamePrefix}${ALL_USERS_USER_EMAIL}`)
- ) {
- continue;
- }
- // If the role does not have the permission, then skip.
- const permissions =
- roleStore.getRoleByName(binding.role)?.permissions || [];
-
- for (const permission of permissions) {
- if (requiredPermissions.includes(permission as QueryPermission)) {
- // If binding expr check passes, then return true.
- if (bindingExprCheck(binding.parsedExpr)) {
- return true;
- }
- }
- }
- }
-
- return false;
-};
-
-export const checkQuerierPermission = (
- database: Database,
- permissions: QueryPermission[] = QueryPermissionQueryAny,
- schema?: string,
- table?: string
-) => {
- return checkProjectIAMPolicyWithExpr(
- useCurrentUserV1().value,
- getDatabaseProject(database),
- permissions,
- (expr?: Expr): boolean => {
- // If no condition is set, then return true.
- if (!expr) {
- return true;
- }
-
- const conditionExpr = convertFromExpr(expr);
- // Check if the condition is expired.
- if (
- conditionExpr.expiredTime &&
- new Date(conditionExpr.expiredTime).getTime() < Date.now()
- ) {
- return false;
- }
- // Check if the condition is valid for the database.
- if (
- conditionExpr.databaseResources &&
- conditionExpr.databaseResources.length > 0
- ) {
- for (const databaseResource of conditionExpr.databaseResources) {
- if (databaseResource.databaseFullName === database.name) {
- if (isUndefined(schema) && isUndefined(table)) {
- return true;
- } else {
- if (
- isUndefined(databaseResource.schema) ||
- (isUndefined(databaseResource.schema) &&
- isUndefined(databaseResource.table)) ||
- (databaseResource.schema === schema &&
- databaseResource.table === table)
- ) {
- return true;
- }
- }
- }
- }
- return false;
- }
- return true;
- }
- );
-};
diff --git a/frontend/src/store/modules/v1/setting.ts b/frontend/src/store/modules/v1/setting.ts
deleted file mode 100644
index b1cf30f458..0000000000
--- a/frontend/src/store/modules/v1/setting.ts
+++ /dev/null
@@ -1,175 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import type { FieldMask } from "@bufbuild/protobuf/wkt";
-import { createContextValues } from "@connectrpc/connect";
-import { defineStore } from "pinia";
-import { computed, reactive } from "vue";
-import { settingServiceClientConnect } from "@/connect";
-import { silentContextKey } from "@/connect/context-key";
-import { settingNamePrefix } from "@/store/modules/v1/common";
-import {
- type DataClassificationSetting_DataClassificationConfig,
- GetSettingRequestSchema,
- type Setting,
- Setting_SettingName,
- SettingSchema,
- type SettingValue,
- SettingValueSchema,
- UpdateSettingRequestSchema,
- type WorkspaceProfileSetting,
- WorkspaceProfileSettingSchema,
-} from "@/types/proto-es/v1/setting_service_pb";
-import { useActuatorV1Store } from "./actuator";
-
-export const DEFAULT_MAX_RESULT_SIZE_IN_MB = 100;
-
-export const useSettingV1Store = defineStore("setting_v1", () => {
- const settingMapByName = reactive(new Map<string, Setting>());
- const actuatorStore = useActuatorV1Store();
-
- const workspaceProfile = computed((): WorkspaceProfileSetting => {
- const setting = settingMapByName.get(
- `${settingNamePrefix}${Setting_SettingName[Setting_SettingName.WORKSPACE_PROFILE]}`
- );
- if (setting?.value?.value.case === "workspaceProfile") {
- return setting.value.value.value;
- }
- return create(WorkspaceProfileSettingSchema, {});
- });
-
- const classification = computed(
- (): DataClassificationSetting_DataClassificationConfig[] => {
- const setting = settingMapByName.get(
- `${settingNamePrefix}${Setting_SettingName[Setting_SettingName.DATA_CLASSIFICATION]}`
- );
- if (!setting?.value?.value) return [];
- const value = setting.value.value;
- if (value.case === "dataClassification") {
- return value.value.configs;
- }
- return [];
- }
- );
-
- const getProjectClassification = (
- classificationId: string
- ): DataClassificationSetting_DataClassificationConfig | undefined => {
- return classification.value.find(
- (config) => config.id === classificationId
- );
- };
-
- const fetchSettingByName = async (
- name: Setting_SettingName,
- silent = false
- ): Promise<Setting | undefined> => {
- try {
- const request = create(GetSettingRequestSchema, {
- name: `${settingNamePrefix}${Setting_SettingName[name]}`,
- });
- const response = await settingServiceClientConnect.getSetting(request, {
- contextValues: createContextValues().set(silentContextKey, silent),
- });
- return response;
- } catch {
- return;
- }
- };
-
- const getSettingByName = (name: Setting_SettingName): Setting | undefined => {
- return settingMapByName.get(
- `${settingNamePrefix}${Setting_SettingName[name]}`
- );
- };
-
- const getOrFetchSettingByName = async (
- name: Setting_SettingName,
- silent = false
- ): Promise<Setting | undefined> => {
- const setting = getSettingByName(name);
- if (setting) {
- return setting;
- }
- const response = await fetchSettingByName(name, silent);
- if (response) {
- settingMapByName.set(response.name, response);
- }
- return response;
- };
-
- const upsertSetting = async ({
- name,
- value,
- validateOnly = false,
- updateMask,
- }: {
- name: Setting_SettingName;
- value: SettingValue;
- validateOnly?: boolean;
- updateMask?: FieldMask | undefined;
- }): Promise<Setting> => {
- const setting = create(SettingSchema, {
- name: `${settingNamePrefix}${Setting_SettingName[name]}`,
- value,
- });
-
- const request = create(UpdateSettingRequestSchema, {
- setting,
- validateOnly,
- allowMissing: true,
- updateMask: updateMask,
- });
- const response = await settingServiceClientConnect.updateSetting(request);
- settingMapByName.set(response.name, response);
- // Bridge: keep the React app-store setting cache in sync so React
- // consumers (e.g. SQL editor's `OpenAIButton`) see the fresh value
- // without a page refresh. Dynamic-imported to avoid a static
- // module-load cycle (the app store transitively imports `@/store`).
- try {
- const { useAppStore } = await import("@/react/stores/app");
- useAppStore.getState().setSettingByName(response);
- } catch {
- // App store not available (some isolated test). Pinia cache is
- // already updated above.
- }
- return response;
- };
-
- const updateWorkspaceProfile = async ({
- payload,
- updateMask,
- }: {
- payload: Partial<WorkspaceProfileSetting>;
- updateMask: FieldMask;
- }): Promise<void> => {
- const profileSetting: WorkspaceProfileSetting = create(
- WorkspaceProfileSettingSchema,
- {
- ...workspaceProfile.value,
- ...payload,
- }
- );
- await upsertSetting({
- name: Setting_SettingName.WORKSPACE_PROFILE,
- value: create(SettingValueSchema, {
- value: {
- case: "workspaceProfile",
- value: profileSetting,
- },
- }),
- updateMask: updateMask,
- });
- // Refresh the latest server info.
- await actuatorStore.fetchServerInfo(actuatorStore.workspaceResourceName);
- };
-
- return {
- settingMapByName,
- workspaceProfile,
- classification,
- getProjectClassification,
- getSettingByName,
- getOrFetchSettingByName,
- upsertSetting,
- updateWorkspaceProfile,
- };
-});
diff --git a/frontend/src/store/modules/v1/subscription.test.ts b/frontend/src/store/modules/v1/subscription.test.ts
deleted file mode 100644
index 634e254f11..0000000000
--- a/frontend/src/store/modules/v1/subscription.test.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { createPinia, setActivePinia } from "pinia";
-import { beforeEach, describe, expect, test, vi } from "vitest";
-import { InstanceSchema } from "@/types/proto-es/v1/instance_service_pb";
-import {
- PlanFeature,
- PlanType,
- SubscriptionSchema,
-} from "@/types/proto-es/v1/subscription_service_pb";
-
-vi.mock("@/connect", () => ({
- subscriptionServiceClientConnect: {},
-}));
-
-vi.mock("@/types", () => ({
- hasFeature: vi.fn(() => true),
- hasInstanceFeature: vi.fn(
- (_plan: PlanType, _feature: PlanFeature, activated: boolean) => activated
- ),
- getDateForPbTimestampProtoEs: vi.fn(() => new Date()),
- getMinimumRequiredPlan: vi.fn(() => PlanType.TEAM),
- getTimeForPbTimestampProtoEs: vi.fn(() => Date.now()),
- instanceLimitFeature: new Set<PlanFeature>([
- PlanFeature.FEATURE_DATA_MASKING,
- ]),
- PLANS: [
- {
- type: PlanType.ENTERPRISE,
- maximumInstanceCount: -1,
- maximumSeatCount: -1,
- },
- ],
-}));
-
-vi.mock("@/utils/datetime", () => ({
- formatAbsoluteDateTime: vi.fn(() => ""),
-}));
-
-let useSubscriptionV1Store: typeof import("./subscription").useSubscriptionV1Store;
-
-describe("useSubscriptionV1Store unified instance license", () => {
- beforeEach(async () => {
- vi.clearAllMocks();
- setActivePinia(createPinia());
- ({ useSubscriptionV1Store } = await import("./subscription"));
- });
-
- test("computes unified mode from effective limits", () => {
- const store = useSubscriptionV1Store();
- store.setSubscription(
- create(SubscriptionSchema, {
- plan: PlanType.ENTERPRISE,
- instances: 10,
- activeInstances: 10,
- })
- );
-
- expect(store.hasUnifiedInstanceLicense).toBe(true);
-
- store.setSubscription(
- create(SubscriptionSchema, {
- plan: PlanType.ENTERPRISE,
- instances: 50,
- activeInstances: 20,
- })
- );
-
- expect(store.hasUnifiedInstanceLicense).toBe(false);
- });
-
- test("computes legacy split instance license mode", () => {
- const store = useSubscriptionV1Store();
- store.setSubscription(
- create(SubscriptionSchema, {
- plan: PlanType.ENTERPRISE,
- instances: 50,
- activeInstances: 20,
- })
- );
-
- expect(store.hasSplitInstanceLicense).toBe(true);
-
- store.setSubscription(
- create(SubscriptionSchema, {
- plan: PlanType.ENTERPRISE,
- instances: 10,
- activeInstances: 10,
- })
- );
-
- expect(store.hasSplitInstanceLicense).toBe(false);
-
- store.setSubscription(
- create(SubscriptionSchema, {
- plan: PlanType.FREE,
- instances: 0,
- activeInstances: 0,
- })
- );
-
- expect(store.hasSplitInstanceLicense).toBe(false);
- });
-
- test("does not report missing instance license in unified mode", () => {
- const store = useSubscriptionV1Store();
- store.setSubscription(
- create(SubscriptionSchema, {
- plan: PlanType.ENTERPRISE,
- instances: 10,
- activeInstances: 10,
- })
- );
-
- const inactiveInstance = create(InstanceSchema, {
- name: "instances/prod",
- title: "prod",
- activation: false,
- });
-
- expect(
- store.instanceMissingLicense(
- PlanFeature.FEATURE_DATA_MASKING,
- inactiveInstance
- )
- ).toBe(false);
- });
-});
diff --git a/frontend/src/store/modules/v1/subscription.ts b/frontend/src/store/modules/v1/subscription.ts
deleted file mode 100644
index 134bbfc149..0000000000
--- a/frontend/src/store/modules/v1/subscription.ts
+++ /dev/null
@@ -1,411 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import dayjs from "dayjs";
-import { defineStore } from "pinia";
-import type { Ref } from "vue";
-import { computed, ref } from "vue";
-import { subscriptionServiceClientConnect } from "@/connect";
-import {
- hasFeature as checkFeature,
- hasInstanceFeature as checkInstanceFeature,
- getDateForPbTimestampProtoEs,
- getMinimumRequiredPlan,
- getTimeForPbTimestampProtoEs,
- instanceLimitFeature,
- PLANS,
-} from "@/types";
-import type {
- Instance,
- InstanceResource,
-} from "@/types/proto-es/v1/instance_service_pb";
-import type {
- PaymentInfo,
- PurchasePlan,
- Subscription,
-} from "@/types/proto-es/v1/subscription_service_pb";
-import {
- BillingInterval,
- CancelPurchaseRequestSchema,
- CreatePurchaseRequestSchema,
- GetPaymentInfoRequestSchema,
- GetSubscriptionRequestSchema,
- ListPurchasePlansRequestSchema,
- PlanFeature,
- PlanType,
- UpdatePurchaseRequestSchema,
- UploadLicenseRequestSchema,
- VerifyCheckoutSessionRequestSchema,
-} from "@/types/proto-es/v1/subscription_service_pb";
-import { formatAbsoluteDateTime } from "@/utils/datetime";
-
-// The threshold of days before the license expiration date to show the warning.
-// Default is 7 days.
-export const LICENSE_EXPIRATION_THRESHOLD = 7;
-
-export const useSubscriptionV1Store = defineStore("subscription_v1", () => {
- // State
- const subscription = ref<Subscription | undefined>(undefined);
- const trialingDays = ref(14);
- const paymentInfo = ref<PaymentInfo | undefined>(undefined);
- const purchasePlans = ref<PurchasePlan[]>([]);
-
- // Getters
- const currentPlan = computed(() => {
- if (!subscription.value) {
- return PlanType.FREE;
- }
- return subscription.value.plan;
- });
-
- const isFreePlan = computed(() => currentPlan.value === PlanType.FREE);
-
- const instanceCountLimit = computed(() => {
- let limit = subscription.value?.instances ?? 0;
- if (limit > 0) {
- return limit;
- }
-
- limit =
- PLANS.find((plan) => plan.type === currentPlan.value)
- ?.maximumInstanceCount ?? 0;
- if (limit < 0) {
- const instanceLimitInLicense = subscription.value?.instances ?? 0;
- if (instanceLimitInLicense > 0) {
- return instanceLimitInLicense;
- }
- return Number.MAX_VALUE;
- }
- return limit;
- });
-
- const userCountLimit = computed(() => {
- let limit =
- PLANS.find((plan) => plan.type === currentPlan.value)?.maximumSeatCount ??
- 0;
- if (limit < 0) {
- limit = Number.MAX_VALUE;
- }
-
- const seatCount = subscription.value?.seats ?? 0;
- if (seatCount < 0) {
- return Number.MAX_VALUE;
- }
- if (seatCount === 0) {
- return limit;
- }
- return seatCount;
- });
-
- const instanceLicenseCount = computed(() => {
- const count = subscription.value?.activeInstances ?? 0;
- if (count < 0) {
- return Number.MAX_VALUE;
- }
- return count;
- });
-
- const hasUnifiedInstanceLicense = computed(() => {
- return instanceCountLimit.value <= instanceLicenseCount.value;
- });
-
- const hasSplitInstanceLicense = computed(() => {
- return !isFreePlan.value && !hasUnifiedInstanceLicense.value;
- });
-
- const expireAt = computed(() => {
- if (
- !subscription.value ||
- !subscription.value.expiresTime ||
- isFreePlan.value
- ) {
- return "";
- }
-
- return formatAbsoluteDateTime(
- getTimeForPbTimestampProtoEs(subscription.value.expiresTime)
- );
- });
-
- const isTrialing = computed(() => !!subscription.value?.trialing);
-
- const isExpired = computed(() => {
- if (
- !subscription.value ||
- !subscription.value.expiresTime ||
- isFreePlan.value
- ) {
- return false;
- }
- return dayjs(
- getDateForPbTimestampProtoEs(subscription.value.expiresTime)
- ).isBefore(new Date());
- });
-
- const daysBeforeExpire = computed(() => {
- if (
- !subscription.value ||
- !subscription.value.expiresTime ||
- isFreePlan.value
- ) {
- return -1;
- }
-
- const expiresTime = dayjs(
- getDateForPbTimestampProtoEs(subscription.value.expiresTime)
- );
- return Math.max(expiresTime.diff(new Date(), "day"), 0);
- });
-
- const isSelfHostLicense = computed(
- () => import.meta.env.MODE.toLowerCase() !== "release-aws"
- );
-
- const showTrial = computed(() => {
- if (!isSelfHostLicense.value) {
- return false;
- }
- if (!subscription.value || isFreePlan.value) {
- return true;
- }
- return false;
- });
-
- const isHAAllowed = computed(() => subscription.value?.ha ?? false);
-
- const purchaseLicenseUrl = computed(
- () => import.meta.env.BB_PURCHASE_LICENSE_URL as string
- );
-
- // Actions
- const setSubscription = (sub: Subscription) => {
- subscription.value = sub;
- };
-
- const hasFeature = (feature: PlanFeature) => {
- if (isExpired.value) {
- return false;
- }
- return checkFeature(currentPlan.value, feature);
- };
-
- const hasInstanceFeature = (
- feature: PlanFeature,
- instance: Instance | InstanceResource | undefined = undefined
- ) => {
- // For FREE plan, don't check instance activation
- if (currentPlan.value === PlanType.FREE) {
- return hasFeature(feature);
- }
-
- // If no instance provided or feature is not instance-limited
- if (!instance || !instanceLimitFeature.has(feature)) {
- return hasFeature(feature);
- }
-
- return checkInstanceFeature(
- currentPlan.value,
- feature,
- hasUnifiedInstanceLicense.value || instance.activation
- );
- };
-
- const instanceMissingLicense = (
- feature: PlanFeature,
- instance: Instance | InstanceResource | undefined = undefined
- ) => {
- // Only relevant for instance-limited features
- if (!instanceLimitFeature.has(feature)) {
- return false;
- }
- if (!instance) {
- return false;
- }
- if (hasUnifiedInstanceLicense.value) {
- return false;
- }
- // Feature is available in plan but instance is not activated
- return hasFeature(feature) && !instance.activation;
- };
-
- // Fetch subscription. When cache=false, returns the result without updating the store.
- // Useful for polling during plan changes to avoid UI flashing (PAID → FREE → PAID).
- const fetchSubscription = async (cache = true) => {
- try {
- const request = create(GetSubscriptionRequestSchema, {});
- const sub =
- await subscriptionServiceClientConnect.getSubscription(request);
- if (cache) {
- setSubscription(sub);
- }
- return sub;
- } catch (e) {
- console.error(e);
- }
- };
-
- // Poll GetSubscription until predicate returns true, timeout, or abort.
- // Used after webhook-driven state changes (purchase, update, cancel) to reflect
- // the new subscription in the store without requiring a manual page refresh.
- // On match, the store is updated and the subscription is returned. Returns
- // undefined on timeout or abort without mutating the store.
- const pollSubscriptionUntil = async (
- predicate: (sub: Subscription) => boolean,
- options: {
- timeoutMs?: number;
- intervalMs?: number;
- signal?: AbortSignal;
- } = {}
- ): Promise<Subscription | undefined> => {
- const { timeoutMs = 60_000, intervalMs = 2_000, signal } = options;
- const deadline = Date.now() + timeoutMs;
- while (Date.now() < deadline) {
- if (signal?.aborted) return undefined;
- const sub = await fetchSubscription(false);
- if (signal?.aborted) return undefined;
- if (sub && predicate(sub)) {
- setSubscription(sub);
- return sub;
- }
- await new Promise((r) => setTimeout(r, intervalMs));
- }
- return undefined;
- };
-
- const uploadLicense = async (license: string) => {
- const request = create(UploadLicenseRequestSchema, {
- license,
- });
- const sub = await subscriptionServiceClientConnect.uploadLicense(request);
- setSubscription(sub);
- return sub;
- };
-
- // Purchase actions (SaaS only)
- const createPurchase = async (
- plan: PlanType,
- interval: BillingInterval,
- seats: number
- ): Promise<string> => {
- const request = create(CreatePurchaseRequestSchema, {
- plan,
- interval,
- seats,
- });
- const response =
- await subscriptionServiceClientConnect.createPurchase(request);
- return response.paymentUrl;
- };
-
- const updatePurchase = async (
- plan: PlanType,
- interval: BillingInterval,
- seats: number,
- etag: string
- ): Promise<string> => {
- const request = create(UpdatePurchaseRequestSchema, {
- plan,
- interval,
- seats,
- etag,
- });
- const response =
- await subscriptionServiceClientConnect.updatePurchase(request);
- return response.paymentUrl;
- };
-
- const cancelPurchase = async (feedback: string, comment: string) => {
- const request = create(CancelPurchaseRequestSchema, { feedback, comment });
- await subscriptionServiceClientConnect.cancelPurchase(request);
- await fetchSubscription();
- };
-
- const fetchPaymentInfo = async () => {
- try {
- const request = create(GetPaymentInfoRequestSchema, {});
- const info =
- await subscriptionServiceClientConnect.getPaymentInfo(request);
- paymentInfo.value = info;
- return info;
- } catch (e) {
- console.error(e);
- }
- };
-
- const verifyCheckoutSession = async (sessionId: string): Promise<string> => {
- const request = create(VerifyCheckoutSessionRequestSchema, {
- sessionId,
- });
- const response =
- await subscriptionServiceClientConnect.verifyCheckoutSession(request);
- return response.status;
- };
-
- const fetchPurchasePlans = async () => {
- try {
- const request = create(ListPurchasePlansRequestSchema, {});
- const response =
- await subscriptionServiceClientConnect.listPurchasePlans(request);
- purchasePlans.value = response.plans;
- return response.plans;
- } catch (e) {
- console.error(e);
- }
- };
-
- return {
- // State
- subscription,
- trialingDays,
- paymentInfo,
- purchasePlans,
- // Getters
- currentPlan,
- isFreePlan,
- instanceCountLimit,
- userCountLimit,
- instanceLicenseCount,
- hasUnifiedInstanceLicense,
- hasSplitInstanceLicense,
- expireAt,
- isTrialing,
- isExpired,
- daysBeforeExpire,
- isSelfHostLicense,
- showTrial,
- isHAAllowed,
- purchaseLicenseUrl,
- // Actions
- hasFeature,
- hasInstanceFeature,
- instanceMissingLicense,
- getMinimumRequiredPlan,
- fetchSubscription,
- pollSubscriptionUntil,
- uploadLicense,
- setSubscription,
- // Purchase actions (SaaS)
- createPurchase,
- updatePurchase,
- cancelPurchase,
- verifyCheckoutSession,
- fetchPaymentInfo,
- fetchPurchasePlans,
- };
-});
-
-export const hasFeature = (feature: PlanFeature) => {
- const store = useSubscriptionV1Store();
- return store.hasFeature(feature);
-};
-
-export const featureToRef = (
- feature: PlanFeature,
- instance: Instance | InstanceResource | undefined = undefined
-): Ref<boolean> => {
- const store = useSubscriptionV1Store();
- return computed(() => store.hasInstanceFeature(feature, instance));
-};
-
-export const useCurrentPlan = () => {
- const store = useSubscriptionV1Store();
- return computed(() => store.currentPlan);
-};
diff --git a/frontend/src/store/modules/v1/workspace.ts b/frontend/src/store/modules/v1/workspace.ts
deleted file mode 100644
index 0c9ba08674..0000000000
--- a/frontend/src/store/modules/v1/workspace.ts
+++ /dev/null
@@ -1,286 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { FieldMaskSchema } from "@bufbuild/protobuf/wkt";
-import { cloneDeep } from "lodash-es";
-import { defineStore } from "pinia";
-import { computed, ref, watch } from "vue";
-import {
- authServiceClientConnect,
- workspaceServiceClientConnect,
-} from "@/connect";
-import { router } from "@/router";
-import { WORKSPACE_ROUTE_LANDING } from "@/router/dashboard/workspaceRoutes";
-import { userNamePrefix, workspaceNamePrefix } from "@/store/modules/v1/common";
-import {
- broadcastWorkspaceSwitch,
- workspaceSwitchChannel,
-} from "@/store/workspaceSwitchChannel";
-import { ALL_USERS_USER_EMAIL } from "@/types";
-import { SwitchWorkspaceRequestSchema } from "@/types/proto-es/v1/auth_service_pb";
-import type { IamPolicy } from "@/types/proto-es/v1/iam_policy_pb";
-import {
- BindingSchema,
- GetIamPolicyRequestSchema,
- IamPolicySchema,
- SetIamPolicyRequestSchema,
-} from "@/types/proto-es/v1/iam_policy_pb";
-import type { Workspace } from "@/types/proto-es/v1/workspace_service_pb";
-import { UpdateWorkspaceRequestSchema } from "@/types/proto-es/v1/workspace_service_pb";
-import { getUserListInBinding, isBindingPolicyExpired } from "@/utils";
-import { useActuatorV1Store } from "./actuator";
-import { composePolicyBindings } from "./projectIamPolicy";
-
-// Listen on the shared cross-tab channel. Using `addEventListener` instead of
-// `onmessage = ...` lets the React-side store register its own handler on the
-// same channel object — and crucially, posts made through that same object
-// (e.g. from the OAuth2 consent page via `switchWorkspaceWithoutRedirect`)
-// will NOT trigger either listener in the sending tab thanks to source-object
-// exclusion.
-workspaceSwitchChannel.addEventListener("message", () => {
- // Another tab switched workspace — full-reload to the landing page
- // to pick up the new cookie and reset all frontend state.
- const landingPath = router.resolve({ name: WORKSPACE_ROUTE_LANDING }).href;
- window.location.href = landingPath;
-});
-
-export const useWorkspaceV1Store = defineStore("workspace_v1", () => {
- const _workspaceIamPolicy = ref<IamPolicy>(create(IamPolicySchema, {}));
- const workspaceList = ref<Workspace[]>([]);
- const currentWorkspace = ref<Workspace | undefined>();
- const actuatorStore = useActuatorV1Store();
-
- const workspaceIamPolicy = computed(() => {
- return _workspaceIamPolicy.value;
- });
-
- watch(
- () => actuatorStore.workspaceResourceName,
- async (name) => {
- const requestName = name || `${workspaceNamePrefix}-`;
- const workspace = await workspaceServiceClientConnect.getWorkspace({
- name: requestName,
- });
- currentWorkspace.value = workspace;
- },
- { immediate: true }
- );
-
- const updateWorkspace = async (
- workspace: Workspace,
- updateMask: string[]
- ) => {
- const updated = await workspaceServiceClientConnect.updateWorkspace(
- create(UpdateWorkspaceRequestSchema, {
- workspace: workspace,
- updateMask: create(FieldMaskSchema, {
- paths: updateMask,
- }),
- })
- );
- const index = workspaceList.value.findIndex(
- (ws) => ws.name === updated.name
- );
- if (index >= 0) {
- workspaceList.value[index] = updated;
- }
- currentWorkspace.value = updated;
- };
-
- // roleMapToUsers returns Map<roles/{role}, Set<userfullname>>
- // the user fullname can be
- // - users/{email}, includes users/ALL_USERS_USER_EMAIL
- // - serviceAccounts/{email}
- // - workloadIdentities/{email}
- const roleMapToUsers = computed(() => {
- const map = new Map<string, Set<string>>();
- for (const binding of _workspaceIamPolicy.value.bindings) {
- if (!map.has(binding.role)) {
- map.set(binding.role, new Set());
- }
- for (const fullname of getUserListInBinding({
- binding,
- ignoreGroup: false,
- })) {
- map.get(binding.role)?.add(fullname);
- }
- }
- return map;
- });
-
- // userMapToRoles returns Map<userfullname, Set<roles/{role}>>
- // the user fullname can be
- // - users/{email}, includes users/ALL_USERS_USER_EMAIL
- // - serviceAccounts/{email}
- // - workloadIdentities/{email}
- const userMapToRoles = computed(() => {
- const map = new Map<string, Set<string>>();
- for (const binding of _workspaceIamPolicy.value.bindings) {
- for (const fullname of getUserListInBinding({
- binding,
- ignoreGroup: false,
- })) {
- if (!map.has(fullname)) {
- map.set(fullname, new Set());
- }
- map.get(fullname)?.add(binding.role);
- }
- }
- return map;
- });
-
- const fetchIamPolicy = async () => {
- const request = create(GetIamPolicyRequestSchema, {
- resource: actuatorStore.workspaceResourceName,
- });
- const policy = await workspaceServiceClientConnect.getIamPolicy(request);
- await composePolicyBindings(policy.bindings);
- _workspaceIamPolicy.value = policy;
- return policy;
- };
-
- const mergeBinding = ({
- member,
- roles,
- policy,
- }: {
- member: string;
- roles: string[];
- policy: IamPolicy;
- }) => {
- const newRolesSet = new Set(roles);
- const workspacePolicy = cloneDeep(policy);
-
- for (const binding of workspacePolicy.bindings) {
- const index = binding.members.findIndex((m) => m === member);
- if (!newRolesSet.has(binding.role)) {
- if (index >= 0) {
- binding.members.splice(index, 1);
- }
- } else {
- if (index < 0) {
- binding.members.push(member);
- }
- }
-
- newRolesSet.delete(binding.role);
- }
-
- for (const role of newRolesSet) {
- workspacePolicy.bindings.push(
- create(BindingSchema, {
- role,
- members: [member],
- })
- );
- }
-
- return workspacePolicy;
- };
-
- const patchIamPolicy = async (
- batchPatch: {
- member: string;
- roles: string[];
- }[]
- ) => {
- if (batchPatch.length === 0) {
- return;
- }
- let workspacePolicy = cloneDeep(_workspaceIamPolicy.value);
- for (const patch of batchPatch) {
- workspacePolicy = mergeBinding({
- ...patch,
- policy: workspacePolicy,
- });
- }
-
- const request = create(SetIamPolicyRequestSchema, {
- resource: actuatorStore.workspaceResourceName,
- policy: workspacePolicy,
- etag: workspacePolicy.etag,
- });
- const policy = await workspaceServiceClientConnect.setIamPolicy(request);
- _workspaceIamPolicy.value = policy;
- };
-
- const findRolesByMember = (member: string): string[] => {
- const roles = new Set<string>();
- for (const binding of _workspaceIamPolicy.value.bindings) {
- if (isBindingPolicyExpired(binding)) {
- continue;
- }
- if (binding.members.includes(member)) {
- roles.add(binding.role);
- }
- }
- return [...roles];
- };
-
- const getWorkspaceRolesByName = (name: string) => {
- const specificRoles = userMapToRoles.value.get(name) ?? new Set<string>([]);
- if (userMapToRoles.value.has(`${userNamePrefix}${ALL_USERS_USER_EMAIL}`)) {
- for (const role of userMapToRoles.value.get(
- `${userNamePrefix}${ALL_USERS_USER_EMAIL}`
- )!) {
- specificRoles.add(role);
- }
- }
- return specificRoles;
- };
-
- const fetchCurrentWorkspace = async () => {
- const name =
- actuatorStore.workspaceResourceName || `${workspaceNamePrefix}-`;
- const workspace = await workspaceServiceClientConnect.getWorkspace({
- name,
- });
- currentWorkspace.value = workspace;
- };
-
- const fetchWorkspaceList = async () => {
- const resp = await workspaceServiceClientConnect.listWorkspaces({});
- workspaceList.value = resp.workspaces;
- };
-
- // switchWorkspaceWithoutRedirect performs the server-side switch and
- // notifies other tabs, but leaves navigation to the caller. Posting via
- // the shared `broadcastWorkspaceSwitch` helper uses the single
- // workspaceSwitchChannel instance both the Vue and React stores listen
- // on, so source-object exclusion suppresses both in-tab listeners — the
- // caller (e.g. the OAuth2 consent page) is free to handle its own page
- // lifecycle via location.reload() without losing the consent URL.
- const switchWorkspaceWithoutRedirect = async (workspaceName: string) => {
- await authServiceClientConnect.switchWorkspace(
- create(SwitchWorkspaceRequestSchema, {
- workspace: workspaceName,
- web: true,
- })
- );
- broadcastWorkspaceSwitch(workspaceName);
- };
-
- const switchWorkspace = async (workspaceName: string) => {
- await switchWorkspaceWithoutRedirect(workspaceName);
- // Full-reload to the landing page to reset all frontend state.
- // Reloading the current URL would fail if the page is project-scoped
- // (the project likely doesn't exist in the target workspace).
- const landingPath = router.resolve({ name: WORKSPACE_ROUTE_LANDING }).href;
- window.location.href = landingPath;
- };
-
- return {
- userMapToRoles,
- workspaceIamPolicy,
- fetchIamPolicy,
- patchIamPolicy,
- findRolesByMember,
- roleMapToUsers,
- getWorkspaceRolesByName,
- workspaceList,
- currentWorkspace,
- updateWorkspace,
- fetchCurrentWorkspace,
- fetchWorkspaceList,
- switchWorkspace,
- switchWorkspaceWithoutRedirect,
- };
-});
diff --git a/frontend/src/types/v1/project.ts b/frontend/src/types/v1/project.ts
index ea2ac3b35f..05f78f2b94 100644
--- a/frontend/src/types/v1/project.ts
+++ b/frontend/src/types/v1/project.ts
@@ -1,5 +1,5 @@
import { create as createProto } from "@bufbuild/protobuf";
-import { useActuatorV1Store } from "@/store/modules/v1/actuator";
+import { appStoreUtilBridge } from "@/utils/app-store-bridge";
import { UNKNOWN_ID } from "../const";
import { State } from "../proto-es/v1/common_pb";
import type { Project } from "../proto-es/v1/project_service_pb";
@@ -10,7 +10,7 @@ export const UNKNOWN_PROJECT_NAME = `projects/${UNKNOWN_ID}`;
// Check if a project name is the default project.
// Reads the default project name from the actuator store.
export const isDefaultProject = (name: string): boolean => {
- const defaultProject = useActuatorV1Store().serverInfo?.defaultProject;
+ const defaultProject = appStoreUtilBridge()?.defaultProjectName();
return !!defaultProject && name === defaultProject;
};
diff --git a/frontend/src/utils/app-store-bridge.ts b/frontend/src/utils/app-store-bridge.ts
new file mode 100644
index 0000000000..d23fb3e06d
--- /dev/null
+++ b/frontend/src/utils/app-store-bridge.ts
@@ -0,0 +1,42 @@
+import type { Group } from "@/types/proto-es/v1/group_service_pb";
+import type { IamPolicy } from "@/types/proto-es/v1/iam_policy_pb";
+import type { Role } from "@/types/proto-es/v1/role_service_pb";
+import type {
+ PlanFeature,
+ PlanType,
+} from "@/types/proto-es/v1/subscription_service_pb";
+import type { User } from "@/types/proto-es/v1/user_service_pb";
+import type { Environment } from "@/types/v1/environment";
+
+// Narrow, synchronous accessors into the React app store for shared `@/utils`
+// code. The app store *registers* these at init (see `@/react/stores/app`)
+// rather than `@/utils` importing the store directly — a static import would
+// create an `@/utils` → app-store load-time cycle (the barrel-graph hazard
+// that also gates the permission checkers in `./iam/permission`).
+//
+// Callers must supply their own fallback for the pre-registration window
+// (`appStoreUtilBridge()` returns null until the app store module has loaded,
+// which happens at boot, before any render-time call).
+export interface AppStoreUtilBridge {
+ currentUser: () => User | undefined;
+ isLoggedIn: () => boolean;
+ setUnauthenticatedOccurred: (value: boolean) => void;
+ defaultProjectName: () => string;
+ currentPlan: () => PlanType;
+ hasFeature: (feature: PlanFeature) => boolean;
+ environmentList: () => Environment[];
+ getEnvironmentByName: (name: string, fallback?: boolean) => Environment;
+ roleList: () => Role[];
+ getRoleByName: (name: string) => Role | undefined;
+ getGroupByIdentifier: (identifier: string) => Group | undefined;
+ workspaceRoleMapToUsers: () => Map<string, Set<string>>;
+ getProjectIamPolicy: (project: string) => IamPolicy;
+}
+
+let bridge: AppStoreUtilBridge | null = null;
+
+export const registerAppStoreUtilBridge = (b: AppStoreUtilBridge): void => {
+ bridge = b;
+};
+
+export const appStoreUtilBridge = (): AppStoreUtilBridge | null => bridge;
diff --git a/frontend/src/utils/auth.ts b/frontend/src/utils/auth.ts
index fc4001d9a1..ba1b06a5a7 100644
--- a/frontend/src/utils/auth.ts
+++ b/frontend/src/utils/auth.ts
@@ -1,36 +1,19 @@
-import { router } from "@/router";
-import {
- AUTH_MFA_MODULE,
- AUTH_OAUTH_CALLBACK_MODULE,
- AUTH_OIDC_CALLBACK_MODULE,
- AUTH_PASSWORD_FORGOT_MODULE,
- AUTH_PASSWORD_RESET_MODULE,
- AUTH_SIGNIN_ADMIN_MODULE,
- AUTH_SIGNIN_MODULE,
- AUTH_SIGNUP_MODULE,
-} from "@/router/auth";
-import { useActuatorV1Store } from "@/store";
+// Auth/landing route-name literals. Inlined (no imports) on purpose: this
+// helper lives in the widely-imported `@/utils` barrel, so importing the route
+// constants from `@/react/router/handles` here would add that module to the
+// barrel's load graph and tip a fragile load-order cycle (app store ↔ @/utils
+// ↔ @/types). The values mirror `@/react/router/handles`.
+const AUTH_RELATED_ROUTES = [
+ "auth.signin",
+ "auth.signin.admin",
+ "auth.signup",
+ "auth.mfa",
+ "auth.password.reset",
+ "auth.password.forgot",
+ "auth.oauth.callback",
+ "auth.oidc.callback",
+];
export const isAuthRelatedRoute = (routeName: string) => {
- return [
- AUTH_SIGNIN_MODULE,
- AUTH_SIGNIN_ADMIN_MODULE,
- AUTH_SIGNUP_MODULE,
- AUTH_MFA_MODULE,
- AUTH_PASSWORD_RESET_MODULE,
- AUTH_PASSWORD_FORGOT_MODULE,
- AUTH_OAUTH_CALLBACK_MODULE,
- AUTH_OIDC_CALLBACK_MODULE,
- ].includes(routeName);
-};
-
-export const resolveWorkspaceName = (): string | undefined => {
- const actuatorStore = useActuatorV1Store();
- const route = router.currentRoute.value;
-
- const workspaceID = route.query["workspace"] as string | undefined;
- const workspaceNameFromQuery = workspaceID
- ? `workspaces/${workspaceID}`
- : undefined;
- return actuatorStore.workspaceResourceName || workspaceNameFromQuery;
+ return AUTH_RELATED_ROUTES.includes(routeName);
};
diff --git a/frontend/src/utils/auto-route.ts b/frontend/src/utils/auto-route.ts
index 5b93936f1b..27b3309853 100644
--- a/frontend/src/utils/auto-route.ts
+++ b/frontend/src/utils/auto-route.ts
@@ -1,17 +1,12 @@
-import { type Router } from "vue-router";
import {
PROJECT_V1_ROUTE_DATABASE_DETAIL,
PROJECT_V1_ROUTE_DATABASES,
-} from "@/router/dashboard/projectV1";
-import { SETTING_ROUTE_WORKSPACE_SUBSCRIPTION } from "@/router/dashboard/workspaceSetting";
+ SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,
+} from "@/react/router/handles";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
import { extractDatabaseResourceName, extractProjectResourceName } from "./v1";
-export const isSQLEditorRoute = (router: Router) => {
- return router.currentRoute.value.name?.toString().startsWith("sql-editor");
-};
-
export const autoDatabaseRoute = (database: Database) => {
const name = PROJECT_V1_ROUTE_DATABASE_DETAIL;
diff --git a/frontend/src/utils/expr.ts b/frontend/src/utils/expr.ts
index 3ceb3228ae..9386aec02a 100644
--- a/frontend/src/utils/expr.ts
+++ b/frontend/src/utils/expr.ts
@@ -6,11 +6,7 @@ import {
batchGetOrFetchProjects,
fetchProjectList,
} from "@/react/stores/app/projectAccess";
-import {
- instanceNamePrefix,
- projectNamePrefix,
- useEnvironmentV1Store,
-} from "@/store";
+import { instanceNamePrefix, projectNamePrefix } from "@/store";
import { isValidInstanceName } from "@/types";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import type { Instance } from "@/types/proto-es/v1/instance_service_pb";
@@ -20,6 +16,7 @@ import {
extractInstanceResourceName,
extractProjectResourceName,
} from "@/utils";
+import { appStoreUtilBridge } from "@/utils/app-store-bridge";
type LabeledOption = { value: string; label: string };
@@ -39,7 +36,7 @@ export type OptionConfig = {
};
export const getEnvironmentIdOptions = (): LabeledOption[] => {
- const environmentList = useEnvironmentV1Store().environmentList;
+ const environmentList = appStoreUtilBridge()?.environmentList() ?? [];
return environmentList.map((env) => ({
label: `${env.title} (${env.id})`,
value: env.id,
diff --git a/frontend/src/utils/iam/permission.ts b/frontend/src/utils/iam/permission.ts
index 173aa8bb3b..c0ac4c337a 100644
--- a/frontend/src/utils/iam/permission.ts
+++ b/frontend/src/utils/iam/permission.ts
@@ -1,24 +1,38 @@
-import { usePermissionStore } from "@/store";
import type { Permission } from "@/types";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
-export const hasWorkspacePermissionV2 = (permission: Permission): boolean => {
- return usePermissionStore().currentPermissions.has(permission);
+// Permission checks resolve against the React app store (the single source of
+// truth for the current user, workspace IAM policy, and roles). The legacy
+// Pinia `usePermissionStore` is no longer populated and must not be used.
+//
+// The app store *registers* its checkers here at init rather than this module
+// importing the store directly: `@/utils` sits in the early barrel-import
+// graph (`@/types` → `@/utils` → this file), so a static import of the store
+// would force `createAppStore()` to run before `@/types` finishes
+// initializing, crashing on partially-initialized exports.
+type WorkspaceChecker = (permission: Permission) => boolean;
+type ProjectChecker = (project: Project, permission: Permission) => boolean;
+
+// Default to "deny" until the app store registers (it does so at module init,
+// well before any render-time permission check).
+let workspaceChecker: WorkspaceChecker = () => false;
+let projectChecker: ProjectChecker = () => false;
+
+export const registerPermissionCheckers = (checkers: {
+ hasWorkspacePermission: WorkspaceChecker;
+ hasProjectPermission: ProjectChecker;
+}): void => {
+ workspaceChecker = checkers.hasWorkspacePermission;
+ projectChecker = checkers.hasProjectPermission;
};
-// hasProjectPermissionV2 checks if the user has the given permission on the project.
+export const hasWorkspacePermissionV2 = (permission: Permission): boolean =>
+ workspaceChecker(permission);
+
+// hasProjectPermissionV2 checks if the user has the given permission on the
+// project. The app store's hasProjectPermission already falls back to
+// workspace-level permissions first.
export const hasProjectPermissionV2 = (
project: Project,
permission: Permission
-): boolean => {
- // Check workspace-level permissions first.
- // For those users who have workspace-level project roles, they should have all project-level permissions.
- if (hasWorkspacePermissionV2(permission)) {
- return true;
- }
-
- // Check project-level permissions.
- const permissions =
- usePermissionStore().currentPermissionsInProjectV1(project);
- return permissions.has(permission);
-};
+): boolean => projectChecker(project, permission);
diff --git a/frontend/src/utils/role.ts b/frontend/src/utils/role.ts
index d37b9cc758..8cd3be1d78 100644
--- a/frontend/src/utils/role.ts
+++ b/frontend/src/utils/role.ts
@@ -1,13 +1,13 @@
import { t } from "@/plugins/i18n";
-import { useRoleStore } from "@/store";
import type { Permission } from "@/types/iam";
import { PresetRoleType } from "@/types/iam";
+import { appStoreUtilBridge } from "@/utils/app-store-bridge";
export const checkRoleContainsAnyPermission = (
roleName: string,
...permissions: Permission[]
): boolean => {
- const role = useRoleStore().getRoleByName(roleName);
+ const role = appStoreUtilBridge()?.getRoleByName(roleName);
if (!role) {
return false;
}
@@ -44,7 +44,7 @@ export const displayRoleTitle = (role: string): string => {
return t("role.project-viewer.self");
}
// Use role.title if possible
- const item = useRoleStore().roleList.find((r) => r.name === role);
+ const item = appStoreUtilBridge()?.getRoleByName(role);
// Fallback to extracted resource name otherwise
return item?.title || extractRoleResourceName(role);
};
@@ -73,7 +73,7 @@ export const displayRoleDescription = (role: string): string => {
return t("role.project-viewer.description");
}
// Use role.description if possible
- const item = useRoleStore().roleList.find((r) => r.name === role);
+ const item = appStoreUtilBridge()?.getRoleByName(role);
// Fallback to extracted resource name otherwise
return item?.description || extractRoleResourceName(role);
};
diff --git a/frontend/src/utils/sqlEditor.ts b/frontend/src/utils/sqlEditor.ts
index 7a6e89a5cb..5bd75a21ce 100644
--- a/frontend/src/utils/sqlEditor.ts
+++ b/frontend/src/utils/sqlEditor.ts
@@ -1,20 +1,10 @@
-import { head } from "lodash-es";
import { v1 as uuidv1 } from "uuid";
-import { useQueryDataPolicy } from "@/store";
-import type {
- QueryDataSourceType,
- SQLEditorConnection,
- SQLEditorTab,
-} from "@/types";
+import type { SQLEditorConnection, SQLEditorTab } from "@/types";
import {
DEFAULT_SQL_EDITOR_TAB_MODE,
defaultViewState,
UNKNOWN_DATABASE_NAME,
} from "@/types";
-import type { Database } from "@/types/proto-es/v1/database_service_pb";
-import { DataSourceType } from "@/types/proto-es/v1/instance_service_pb";
-import { wrapRefAsPromise } from "@/utils";
-import { getInstanceResource } from "./v1/database";
export const defaultSQLEditorTab = (): SQLEditorTab => {
return {
@@ -57,35 +47,7 @@ export const isSameSQLEditorConnection = (
return a.instance === b.instance && a.database === b.database;
};
-// `getConnectionForSQLEditorTab` and `isConnectedSQLEditorTab` moved to
-// `@/react/lib/sqlEditorConnection` so the database lookup can go through
-// the React app store without dragging `@/react/stores/app` into the
-// `@/utils` import graph (which would create a static ESM cycle).
-
-export const getValidDataSourceByPolicy = async (
- database: Database,
- type?: QueryDataSourceType
-) => {
- const instanceResource = getInstanceResource(database);
- const adminDataSource = instanceResource.dataSources.find(
- (ds) => ds.type === DataSourceType.ADMIN
- )!;
- const readonlyDataSources = instanceResource.dataSources.filter(
- (ds) => ds.type === DataSourceType.READ_ONLY
- );
-
- const { ready, policy } = useQueryDataPolicy(database.project);
- await wrapRefAsPromise(ready, /* expected */ true);
-
- if (policy.value.allowAdminDataSource) {
- switch (type) {
- case DataSourceType.ADMIN:
- return adminDataSource.id;
- default:
- // try to use read-only data source first.
- return head(readonlyDataSources)?.id ?? adminDataSource.id;
- }
- }
-
- return head(readonlyDataSources)?.id ?? adminDataSource.id;
-};
+// `getConnectionForSQLEditorTab` / `isConnectedSQLEditorTab` and
+// `getValidDataSourceByPolicy` moved to `@/react/lib/*` so the database and
+// policy lookups read the React app store directly without dragging
+// `@/react/stores/app` into the `@/utils` import graph (a static ESM cycle).
diff --git a/frontend/src/utils/v1/database.ts b/frontend/src/utils/v1/database.ts
index 58277e350b..85572fa96d 100644
--- a/frontend/src/utils/v1/database.ts
+++ b/frontend/src/utils/v1/database.ts
@@ -1,5 +1,4 @@
import { getProjectByName } from "@/react/stores/app/projectAccess";
-import { checkQuerierPermission, useEnvironmentV1Store } from "@/store";
import {
databaseNamePrefix,
instanceNamePrefix,
@@ -15,8 +14,10 @@ import { Engine } from "@/types/proto-es/v1/common_pb";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import type { InstanceResource } from "@/types/proto-es/v1/instance_service_pb";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
-import type { Environment } from "@/types/v1/environment";
+import { type Environment, unknownEnvironment } from "@/types/v1/environment";
+import { appStoreUtilBridge } from "@/utils/app-store-bridge";
import { hasWorkspacePermissionV2 } from "../iam";
+import { checkQuerierPermission } from "./iam";
import { extractProjectResourceName } from "./project";
export const databaseV1Url = (db: Database) => {
@@ -103,7 +104,9 @@ export const getDatabaseProject = (database: Database): Project => {
// Get effective environment entity
export const getDatabaseEnvironment = (database: Database): Environment => {
- return useEnvironmentV1Store().getEnvironmentByName(
- database.effectiveEnvironment ?? ""
+ return (
+ appStoreUtilBridge()?.getEnvironmentByName(
+ database.effectiveEnvironment ?? ""
+ ) ?? unknownEnvironment()
);
};
diff --git a/frontend/src/utils/v1/iam.ts b/frontend/src/utils/v1/iam.ts
index dd6100ad99..41e4163f46 100644
--- a/frontend/src/utils/v1/iam.ts
+++ b/frontend/src/utils/v1/iam.ts
@@ -1,13 +1,13 @@
-import { uniq } from "lodash-es";
+import { isUndefined, uniq } from "lodash-es";
+import { getProjectByName } from "@/react/stores/app/projectAccess";
import {
ensureGroupIdentifier,
extractServiceAccountId,
extractWorkloadIdentityId,
groupNamePrefix,
- useGroupStore,
- useWorkspaceV1Store,
} from "@/store";
import {
+ getUserFullNameByType,
serviceAccountNamePrefix,
userNamePrefix,
workloadIdentityNamePrefix,
@@ -15,11 +15,19 @@ import {
import {
ALL_USERS_USER_EMAIL,
groupBindingPrefix,
+ type QueryPermission,
+ QueryPermissionQueryAny,
serviceAccountBindingPrefix,
+ unknownUser,
workloadIdentityBindingPrefix,
} from "@/types";
+import type { Expr } from "@/types/proto-es/google/api/expr/v1alpha1/syntax_pb";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
import type { Group } from "@/types/proto-es/v1/group_service_pb";
import type { Binding, IamPolicy } from "@/types/proto-es/v1/iam_policy_pb";
+import type { Project } from "@/types/proto-es/v1/project_service_pb";
+import type { User } from "@/types/proto-es/v1/user_service_pb";
+import { appStoreUtilBridge } from "@/utils/app-store-bridge";
import { convertFromExpr } from "@/utils/issue/cel";
import { ensureUserFullName } from "@/utils/v1/user";
@@ -75,7 +83,8 @@ export const getUserListInBinding = ({
const resolveGroup =
getGroupByIdentifier ??
- ((identifier: string) => useGroupStore().getGroupByIdentifier(identifier));
+ ((identifier: string) =>
+ appStoreUtilBridge()?.getGroupByIdentifier(identifier));
const fullnameList = [];
for (const member of binding.members) {
@@ -106,7 +115,6 @@ export const memberMapToRolesInProjectIAM = (
targetRole?: string,
getGroupByIdentifier?: (identifier: string) => Group | undefined
): Map<string, Set<string>> => {
- const workspaceStore = useWorkspaceV1Store();
// Map<userfullname, Set<roles/{role}>>
const rolesMapByName = new Map<string, Set<string>>();
@@ -133,7 +141,10 @@ export const memberMapToRolesInProjectIAM = (
}
// Handle workspace level project roles.
- for (const [role, userSet] of workspaceStore.roleMapToUsers.entries()) {
+ const roleMapToUsers =
+ appStoreUtilBridge()?.workspaceRoleMapToUsers() ??
+ new Map<string, Set<string>>();
+ for (const [role, userSet] of roleMapToUsers.entries()) {
if (targetRole && role !== targetRole) {
continue;
}
@@ -168,3 +179,85 @@ export const filterBindingsByUserName = ({
);
});
};
+
+// Project-level IAM permission check. Reads the React app store (project IAM
+// policy + roles) via the util bridge — relocated from the deleted Pinia
+// `projectIamPolicy` store, whose data was never populated in the React shell.
+const checkProjectIAMPolicyWithExpr = (
+ user: User,
+ project: Project,
+ requiredPermissions: QueryPermission[],
+ bindingExprCheck: (expr?: Expr) => boolean
+): boolean => {
+ const policy = appStoreUtilBridge()?.getProjectIamPolicy(project.name);
+ if (!policy) {
+ return false;
+ }
+ for (const binding of policy.bindings) {
+ const nameList = getUserListInBinding({ binding, ignoreGroup: false });
+ if (
+ !nameList.includes(getUserFullNameByType(user)) &&
+ !nameList.includes(`${userNamePrefix}${ALL_USERS_USER_EMAIL}`)
+ ) {
+ continue;
+ }
+ const permissions =
+ appStoreUtilBridge()?.getRoleByName(binding.role)?.permissions || [];
+ for (const permission of permissions) {
+ if (requiredPermissions.includes(permission as QueryPermission)) {
+ if (bindingExprCheck(binding.parsedExpr)) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+};
+
+export const checkQuerierPermission = (
+ database: Database,
+ permissions: QueryPermission[] = QueryPermissionQueryAny,
+ schema?: string,
+ table?: string
+): boolean => {
+ return checkProjectIAMPolicyWithExpr(
+ appStoreUtilBridge()?.currentUser() ?? unknownUser(),
+ getProjectByName(database.project),
+ permissions,
+ (expr?: Expr): boolean => {
+ if (!expr) {
+ return true;
+ }
+ const conditionExpr = convertFromExpr(expr);
+ if (
+ conditionExpr.expiredTime &&
+ new Date(conditionExpr.expiredTime).getTime() < Date.now()
+ ) {
+ return false;
+ }
+ if (
+ conditionExpr.databaseResources &&
+ conditionExpr.databaseResources.length > 0
+ ) {
+ for (const databaseResource of conditionExpr.databaseResources) {
+ if (databaseResource.databaseFullName === database.name) {
+ if (isUndefined(schema) && isUndefined(table)) {
+ return true;
+ }
+ if (
+ isUndefined(databaseResource.schema) ||
+ (isUndefined(databaseResource.schema) &&
+ isUndefined(databaseResource.table)) ||
+ (databaseResource.schema === schema &&
+ databaseResource.table === table)
+ ) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ return true;
+ }
+ );
+};
diff --git a/frontend/src/utils/v1/instance.ts b/frontend/src/utils/v1/instance.ts
index 1253d98d52..1b543a5a89 100644
--- a/frontend/src/utils/v1/instance.ts
+++ b/frontend/src/utils/v1/instance.ts
@@ -1,6 +1,5 @@
import { computed, unref } from "vue";
import { t } from "@/plugins/i18n";
-import { useSubscriptionV1Store } from "@/store";
import type { MaybeRef } from "@/types";
import {
isValidInstanceName,
@@ -18,9 +17,10 @@ import {
DataSourceType,
} from "@/types/proto-es/v1/instance_service_pb";
import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";
+import { appStoreUtilBridge } from "@/utils/app-store-bridge";
export function instanceV1Name(instance: Instance | InstanceResource) {
- const store = useSubscriptionV1Store();
+ const currentPlan = appStoreUtilBridge()?.currentPlan() ?? PlanType.FREE;
let name = instance.title;
// For unknown instance, we will use the name as the title.
if (instance.title === unknownInstance().title) {
@@ -29,7 +29,7 @@ export function instanceV1Name(instance: Instance | InstanceResource) {
if (
isValidInstanceName(instance.name) &&
!instance.activation &&
- store.currentPlan !== PlanType.FREE
+ currentPlan !== PlanType.FREE
) {
name += ` (${t("common.no-license")})`;
}
diff --git a/frontend/src/utils/v1/issue/issue.ts b/frontend/src/utils/v1/issue/issue.ts
index a9cf33e7fc..ef614e634b 100644
--- a/frontend/src/utils/v1/issue/issue.ts
+++ b/frontend/src/utils/v1/issue/issue.ts
@@ -1,12 +1,12 @@
import { create } from "@bufbuild/protobuf";
import dayjs from "dayjs";
import { t } from "@/plugins/i18n";
+import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/react/router/handles";
import {
getDatabaseByName,
getDatabaseList,
} from "@/react/stores/app/databaseAccess";
import { getProjectByName } from "@/react/stores/app/projectAccess";
-import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
import { projectNamePrefix } from "@/store";
import { isValidDatabaseName, UNKNOWN_ID, unknownDatabase } from "@/types";
import { State } from "@/types/proto-es/v1/common_pb";
diff --git a/frontend/vitest.setup.ts b/frontend/vitest.setup.ts
index 3ec0674eac..a284c833fe 100644
--- a/frontend/vitest.setup.ts
+++ b/frontend/vitest.setup.ts
@@ -1,5 +1,39 @@
import "@testing-library/jest-dom/vitest";
-import { vi } from "vitest";
+import { afterEach, vi } from "vitest";
+
+// App-wide guardrail against React infinite-render-loop bugs. Both signatures
+// below are ALWAYS real bugs, never benign:
+// - "getSnapshot should be cached" — a `useSyncExternalStore` whose
+// getSnapshot returns a fresh value every call (this crashed the SQL
+// Editor: GutterBar → useVueRoute → "Maximum update depth"). It is only a
+// console warning, so a looping component would otherwise pass its tests.
+// - "Maximum update depth exceeded" — setState/store-write on every render.
+// Any test that renders a component triggering these now fails, so the whole
+// existing render-test suite doubles as loop detection across the app.
+const RENDER_LOOP_SIGNATURES = [
+ "getSnapshot should be cached",
+ "Maximum update depth exceeded",
+];
+let renderLoopWarnings: string[] = [];
+const realConsoleError = console.error.bind(console);
+console.error = (...args: unknown[]) => {
+ const message = args.map((arg) => String(arg)).join(" ");
+ if (RENDER_LOOP_SIGNATURES.some((sig) => message.includes(sig))) {
+ renderLoopWarnings.push(message);
+ }
+ realConsoleError(...args);
+};
+afterEach(() => {
+ if (renderLoopWarnings.length > 0) {
+ const captured = renderLoopWarnings;
+ renderLoopWarnings = [];
+ throw new Error(
+ `React infinite-render-loop detected during this test. A useSyncExternalStore ` +
+ `getSnapshot must return a cached/stable value, and effects must not ` +
+ `setState unconditionally every render:\n${captured.join("\n")}`
+ );
+ }
+});
// jsdom does not implement ResizeObserver. Components that subscribe to size
// changes (e.g. EllipsisText) blow up on mount without this shim.