Skip to content

fix(studio): DOM-nesting hydration errors, ghost deleted-snippet nav, and migrations query 400s - #47667

Merged
alaister merged 15 commits into
masterfrom
alaister/studio-dom-nesting-and-query-fixes
Jul 8, 2026
Merged

alaister merged 15 commits into
masterfrom
alaister/studio-dom-nesting-and-query-fixes

Conversation

@alaister

@alaister alaister commented Jul 7, 2026 •

Copy link
Copy Markdown
Member

App-level fixes that reproduce on BOTH the Next and TanStack builds — split out of #47657 (which stays TanStack-only) for reviewability. All were found by a full-site click-through of the dashboard.

Invalid HTML nesting (React 19 "will cause a hydration error" console errors)

  • FormLayout description rendered in a <p> (packages/ui-patterns): consumers pass arbitrary JSX (the RowEditor's created_at timezone note passes a <div> with <p>s) → <p>-in-<p> / <div>-in-<p>. Container is now a <div> with identical classes (Tailwind preflight makes them render the same).
  • Switch toggles nested inside Tooltip trigger buttons (button-in-button) in ColumnEditor ("Allow Nullable" + "Is Unique"), ExtensionRow, and PublicationsTableItem → repo-standard TooltipTrigger asChild + <div> wrapper.
  • Saved log queries rendered a <div> directly inside <tbody> (/logs/explorer/saved) → rows are now proper <tr><td colSpan> wrappers; the component itself is untouched (it's valid in its sidebar usage).
  • Nested anchors in observability metric cards: a card-level <Link> wrapped MetricCard's "More information" <Link> (identical URLs) → the chevron affordance renders as a <span> when no href is passed; clicks bubble to the card link, tooltips preserved. Design-system standalone usage unaffected.
  • objectFit="cover" passed to modern next/image on the featured integration card (unknown-prop warning) — the className already had object-cover; prop dropped.

Ghost dead-snippet after deletion

Deleting the active SQL snippet left its id in useDashboardHistory (history.sql), so the "SQL Editor" nav item navigated to /sql/<deleted-id> — content fetch 404s, no editor pane renders, and a phantom tab reappears. Fixed both ends: delete flows now purge dashboard history (and the tabs store clears a stale previewTabId), and /sql/[id] treats a snippet 404 as "clean up + router.replace to /sql/new + toast" instead of rendering the dead state. Unit tests for the store/history cleanup.

pg-meta migrations query 400s on every project load

ActivityStats on project home runs the migrations list query, whose SQL was a bare select * from supabase_migrations.schema_migrations — that table only exists once a migration has run, so every other project logged a failed ?key=migrations request on every load (visible in production consoles too). The SQL is now guarded with to_regclass + query_to_xml (same pattern as the advisor lints' storage.buckets guard), returning zero rows instead of erroring; legacy version-only tables still work. Tested against real dockerized Postgres (absent table, populated ordering, special chars, legacy schema) + MSW hook tests.

Found and verified via /test-supabase-local (browser click-through + console audit on both builds).

To test

Console must stay free of React DOM-nesting errors ("cannot be a descendant of" / "cannot contain a nested") on each surface:

  1. Table editor → Insert row panel (created_at field renders its timezone note) and Edit column panel ("Allow Nullable"/"Is Unique" tooltips still hover).
  2. /database/extensions and /database/publications → toggle switches render, tooltips hover.
  3. /logs/explorer/saved (with ≥1 saved query) → rows render full-width inside the table, hover shows Actions.
  4. /observability → no nested-anchor error on load; card body click and the chevron both navigate; label help-icons still show tooltips.
  5. /integrations → no objectFit unknown-prop warning; featured card images still cover.
  6. Ghost snippet: open a SQL snippet → delete it via the sidebar → click the "SQL Editor" nav item → lands on /sql/new (no phantom tab, no 404 content fetch). Direct-load /sql/<random-uuid> → toast + redirect to /sql/new.
  7. Migrations 400: load project home with a project that has never run a migration → the pg-meta/<ref>/query?key=migrations request returns 200 with [] (previously a 400 on every load). Database → Migrations still lists real migrations when they exist.

Summary by CodeRabbit

Summary by CodeRabbit

  • Bug Fixes

    • Deleted SQL snippets are fully removed from dashboard history and stale editor/tab state; users are redirected with a toast.
    • Closing preview tabs no longer leaves stale references.
    • Improved toggle/tooltip/dialog interactions to avoid broken UI, including metric headers showing tooltips even without direct links.
    • Migrations display safely when migration tables/relations are missing.
  • UI Improvements

    • Refreshed layout for saved queries, form descriptions, and integration imagery.
  • Tests

    • Added coverage for snippet history cleanup, tab removal, migrations SQL behavior, and query edge cases.

Review feedback: query_to_xml breaks on Multigres (Ivan)

The defensive migrations query (added here to stop the ?key=migrations 400 when the table doesn't exist yet) originally guarded with query_to_xml, which is forbidden through Multigres's pooler (MUL-736 / PSQL-1318). Rewritten without query_to_xml/xmltable using the splinter#170 pattern: a PL/pgSQL do block guarded by to_regclass (PL/pgSQL defers planning, so a missing table never errors) stashes the rows into a transaction-local GUC via set_config, and a trailing select reads them back with jsonb_array_elements. Verified that postgres-meta sends the whole SQL as one simple-query string → single implicit transaction → the local GUC survives to the select and doesn't leak into the pooled connection. 6/6 dockerized-Postgres tests (absent table → [], populated/ordered/special-chars, legacy version-only table, full pg-meta-shaped multi-statement string, GUC non-leakage).

Note (out of scope, pre-existing): packages/pg-meta/src/sql/studio/advisor/lints.ts still uses query_to_xml — a separate pre-existing Multigres risk that should get its own splinter-pattern sync.

alaister added 8 commits July 7, 2026 09:37
The non-react-form description container was a <p>, but descriptions are
typed as ReactNode and call sites pass block-level JSX (e.g. the row
editor's DateTimeInput passes a <div> containing a <p>), producing
'<p> cannot be a descendant of <p>' / '<div> cannot be a descendant of
<p>' React DOM-nesting console errors and a hydration risk. Same
classNames, so rendering is unchanged.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
Radix TooltipTrigger renders a <button> by default, and both the column
editor's Allow Nullable / Is Unique fields and the extensions table's
toggle wrapped a Switch (also a <button>) in it, logging '<button>
cannot be a descendant of <button>' React DOM-nesting errors and
risking hydration issues. Use the established asChild + div wrapper
pattern instead; tooltip hover behavior and layout are unchanged.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…s page

The saved queries page passed SavedQueriesItem (which renders a <div>
via LogsSidebarItem) directly as the table body, logging '<div> cannot
be a child of <tbody>' React DOM-nesting errors and risking hydration
mismatches (parsers foster-parent divs out of tbody). Wrap each item in
a full-width tr/td with zero padding so the item keeps governing its
own layout.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
Each card on the observability overview is wrapped in a Link, and
MetricCardHeader rendered its own 'More information' chevron Link
inside it — to the exact same URL — logging '<a> cannot be a descendant
of <a>' React DOM-nesting errors and risking hydration issues.
MetricCardHeader now renders the chevron affordance (with its tooltip)
as a span when no href is passed, and the overview cards omit the
redundant header href: clicks on the chevron fall through to the
wrapping card link, so both click behaviors and the visuals are
unchanged. Standalone MetricCardHeader usage with href still renders a
link.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…image

Modern next/image no longer supports objectFit and forwards it to the
DOM, logging 'React does not recognize the objectFit prop' console
warnings. The className already applies object-cover, so the prop was
redundant.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
…oltip trigger

Same invalid button-in-button nesting as the ColumnEditor/ExtensionRow
toggles — React flags it as a hydration risk. Same asChild + div fix.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
After deleting the currently open SQL snippet, clicking the SQL Editor nav
item navigated to /sql/<deleted-id>: the content fetch 404ed, the page
rendered a dead state with no editor pane, and a phantom tab for the
deleted snippet reappeared (the /sql/[id] route effect re-adds a tab for
whatever id it lands on). It only healed on a hard reload.

Root cause is two-sided:
- The delete flows (DeleteSnippetsModal + SQLEditorNav) removed the
  snippet's tabs but never purged history.sql in useDashboardHistory, and
  /sql (index) redirects to history.sql first, resurrecting the deleted id.
- /sql/[id] had no fallback when the snippet content query 404s: it
  rendered a dead state and left the stale tab/history entries in place.

Fix both ends:
- Add clearSnippetsFromHistory to useDashboardHistory and call it from both
  delete flows so dashboard history can't point at a deleted snippet.
- On a 404 from the snippet content query, /sql/[id] now removes the stale
  tab, clears history, drops the local snippet state, and replaces the
  route with /sql/new (toast included) instead of rendering the dead state.
  The invalid-uuid admonition is preserved.
- removeTab now also clears previewTabId when the removed tab was the
  preview tab, so persisted tab state can't point at a closed tab.

Adds unit tests for the history purge and tab removal cleanup.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
The project home ActivityStats mounts useMigrationsQuery, whose SQL selects
directly from supabase_migrations.schema_migrations. That table only exists
once a migration has been applied, so for every other project the query
failed with 42P01 and surfaced as a visible
POST /platform/pg-meta/<ref>/query?key=migrations -> 400 in the console on
every project page load (Studio swallowed the error client-side, but the
failed request still fired each time).

Guard the SQL with to_regclass + query_to_xml (same pattern as the
storage.buckets guard in the advisor lints) so it returns zero rows instead
of erroring when the table is absent, while still returning real migrations
when it exists. Rows are serialized via to_jsonb so legacy tables that only
have a version column keep working too.

Adds pg-meta DB tests for the absent-table, populated, null-column, and
legacy-schema cases, plus msw tests for the studio hook's error fallback.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
@alaister
alaister requested review from a team as code owners July 7, 2026 01:38
@vercel

vercel Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
design-system Ready Ready Preview, Comment Jul 8, 2026 4:21am
docs Ready Ready Preview, Comment, Open in v0 Jul 8, 2026 4:21am
studio-self-hosted Ready Ready Preview, Comment Jul 8, 2026 4:21am
studio-staging Ready Ready Preview, Comment Jul 8, 2026 4:21am
ui-library Ready Ready Preview, Comment Jul 8, 2026 4:21am
zone-www-dot-com Ready Ready Preview, Comment, Open in v0 Jul 8, 2026 4:21am
1 Skipped Deployment
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Jul 8, 2026 4:21am

Request Review

@supabase

supabase Bot commented Jul 7, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project xguihxuzqibwxjnimxev because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR updates Studio UI wrappers and card headers, hardens migrations queries and tests, adds deleted-snippet history cleanup and redirect handling, and clears preview-tab state when tabs are removed.

Changes

Tooltip and header nesting fixes

Layer / File(s) Summary
Tooltip-triggered switch wrappers
apps/studio/components/interfaces/Database/Extensions/ExtensionRow.tsx, apps/studio/components/interfaces/Database/Publications/PublicationsTableItem.tsx, apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx, apps/studio/components/interfaces/Integrations/CronJobs/CronJobTableCell.tsx
TooltipTrigger and DialogTrigger now use asChild with wrapper div elements around switch controls, preserving the existing toggle and disabled behavior.
Metric card link rendering
packages/ui-patterns/src/MetricCard/index.tsx, apps/studio/components/interfaces/Observability/DatabaseInfrastructureSection.tsx
MetricCardHeader now renders its chevron wrapper when linkTooltip is present, and database infrastructure cards drop href in favor of linkTooltip while remaining inside an outer Link.
Independent markup tweaks
apps/studio/components/interfaces/Integrations/Landing/IntegrationCard.tsx, packages/ui-patterns/src/form/Layout/FormLayout.tsx, apps/studio/pages/project/[ref]/logs/explorer/saved.tsx, apps/studio/components/interfaces/Auth/Users/UsersV2.tsx, apps/studio/components/interfaces/Database/Roles/CreateRolePanel.tsx
Image cover behavior moves to CSS, form descriptions render in a div, saved-query rows use a spanning table cell, row rendering gets an explicit key, and the role form sets initial default values.

Migrations query resilience

Layer / File(s) Summary
Guarded migrations SQL query
packages/pg-meta/src/sql/studio/database/migrations.ts
getMigrationsSql() now checks for schema_migrations with to_regclass, reads rows through JSON conversion when present, and returns an empty result when the table is absent.
pg-meta migrations tests
packages/pg-meta/test/sql/studio/migrations.test.ts
Integration tests cover missing-table handling, row ordering, parsing of name and statements, multi-statement execution, session cleanup, and legacy schemas with reduced columns.
getMigrations API tests
apps/studio/data/database/migrations-query.test.ts
getMigrations tests mock the query endpoint for successful rows, missing-table 400 responses, and other 400 errors.

SQL snippet deletion cleanup

Layer / File(s) Summary
Dashboard history snippet clearing
apps/studio/hooks/misc/useDashboardHistory.ts, apps/studio/hooks/misc/useDashboardHistory.test.tsx
useDashboardHistory adds clearSnippetsFromHistory(ids), and tests cover snippet history updates, removal behavior, and editor-history isolation.
Snippet deletion cleanup wiring
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/DeleteSnippetsModal.tsx, apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx
Deletion cleanup now clears dashboard history before existing redirect and editor-state updates.
Missing snippet redirect flow
apps/studio/pages/project/[ref]/sql/[id].tsx
The SQL page detects deleted snippets, clears related state, shows a toast, and redirects to the new-query route.

Preview tab removal

Layer / File(s) Summary
Preview tab removal
apps/studio/state/tabs.tsx, apps/studio/state/tabs.test.ts
Removing a tab now clears previewTabId when needed, with tests covering tab-removal cases.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

  • supabase/supabase#43592: Both PRs touch apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx and adjust component wiring in the same UI area.
    Suggested labels: autofix
    Suggested reviewers: awaseem, joshenlim
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is informative but does not follow the required template and omits the current/new behavior, issue links, and context sections. Rewrite it using the repository template: acknowledge CONTRIBUTING.md, state the change type, current behavior, new behavior, and add issue/context links.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly covers the main Studio fixes: DOM nesting, deleted-snippet navigation, and migrations query errors.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch alaister/studio-dom-nesting-and-query-fixes

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results

passed  230 passed
flaky  2 flaky
skipped  5 skipped

Details

stats  237 tests across 27 suites
duration  4 minutes, 12 seconds
commit  1002029

Flaky tests

Features › realtime-inspector.spec.ts › Realtime Inspector › Broadcast Messages › clicking broadcast message shows detail panel
Features › realtime-inspector.spec.ts › Realtime Inspector › Message Display › messages counter shows correct count

Skipped tests

Features › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled
Features › sql-editor.spec.ts › SQL Editor › snippet favourite works as expected
Features › sql-editor.spec.ts › SQL Editor › share with team works as expected
Features › sql-editor.spec.ts › SQL Editor › folders works as expected
Features › sql-editor.spec.ts › SQL Editor › other SQL snippets actions work as expected

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/studio/pages/project/[ref]/sql/[id].tsx (1)

35-35: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use clearSnippetsFromHistory([id]) in the 404 redirect path.
setLastVisitedSnippet(undefined) clears whatever snippet was last visited, even when the missing id is unrelated. The helper already removes only matching ids, so this keeps the user's real resume point intact.

Proposed fix
-  const { history, setLastVisitedSnippet } = useDashboardHistory()
+  const { history, setLastVisitedSnippet, clearSnippetsFromHistory } = useDashboardHistory()
     const staleTabId = createTabId('sql', { id })
     if (tabs.hasTab(staleTabId)) tabs.removeTab(staleTabId)
     if (snippet !== undefined) snapV2.removeSnippet(id)
-    setLastVisitedSnippet(undefined)
+    clearSnippetsFromHistory([id])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/studio/pages/project/`[ref]/sql/[id].tsx at line 35, The 404 redirect
path is clearing the wrong dashboard snippet state by calling
setLastVisitedSnippet(undefined), which can wipe an unrelated resume point.
Update the missing-project handling in the sql page component to use
clearSnippetsFromHistory([id]) instead, so only the failed snippet id is removed
while the rest of useDashboardHistory() remains intact.
🧹 Nitpick comments (1)
apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx (1)

448-502: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Correctly fixes nested-button DOM issue.

TooltipTrigger asChild + div wrapper properly resolves the Switch-in-button nesting for both toggles here.

Minor note: this exact Tooltip > TooltipTrigger asChild > div > Switch (or FormItemLayout wrapping Switch) pattern now appears 4 times across this PR (twice here, once in ExtensionRow.tsx, once in PublicationsTableItem.tsx). Consider extracting a small shared wrapper (e.g. a TooltipSwitch/DisabledTooltipTrigger helper) to avoid re-implementing the same fix if similar nesting issues surface elsewhere.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx`
around lines 448 - 502, The nested-button fix is repeated in multiple places, so
factor the `TooltipTrigger asChild` + wrapped `Switch` pattern into a shared
helper/component to keep the DOM-safe behavior consistent. Create a small
reusable wrapper (for example around the `FormItemLayout`/`Switch` combination
used in `ColumnEditor`, `ExtensionRow`, and `PublicationsTableItem`) and update
those call sites to use it instead of duplicating the same `Tooltip >
TooltipTrigger asChild > div > Switch` structure.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@apps/studio/pages/project/`[ref]/sql/[id].tsx:
- Line 35: The 404 redirect path is clearing the wrong dashboard snippet state
by calling setLastVisitedSnippet(undefined), which can wipe an unrelated resume
point. Update the missing-project handling in the sql page component to use
clearSnippetsFromHistory([id]) instead, so only the failed snippet id is removed
while the rest of useDashboardHistory() remains intact.

---

Nitpick comments:
In
`@apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx`:
- Around line 448-502: The nested-button fix is repeated in multiple places, so
factor the `TooltipTrigger asChild` + wrapped `Switch` pattern into a shared
helper/component to keep the DOM-safe behavior consistent. Create a small
reusable wrapper (for example around the `FormItemLayout`/`Switch` combination
used in `ColumnEditor`, `ExtensionRow`, and `PublicationsTableItem`) and update
those call sites to use it instead of duplicating the same `Tooltip >
TooltipTrigger asChild > div > Switch` structure.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 374f86a8-c25a-44b4-af64-c99480d851e0

📥 Commits

Reviewing files that changed from the base of the PR and between 0ed4e6f and 8ea4ec3.

📒 Files selected for processing (18)
  • apps/studio/components/interfaces/Database/Extensions/ExtensionRow.tsx
  • apps/studio/components/interfaces/Database/Publications/PublicationsTableItem.tsx
  • apps/studio/components/interfaces/Integrations/Landing/IntegrationCard.tsx
  • apps/studio/components/interfaces/Observability/DatabaseInfrastructureSection.tsx
  • apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/DeleteSnippetsModal.tsx
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx
  • apps/studio/data/database/migrations-query.test.ts
  • apps/studio/hooks/misc/useDashboardHistory.test.tsx
  • apps/studio/hooks/misc/useDashboardHistory.ts
  • apps/studio/pages/project/[ref]/logs/explorer/saved.tsx
  • apps/studio/pages/project/[ref]/sql/[id].tsx
  • apps/studio/state/tabs.test.ts
  • apps/studio/state/tabs.tsx
  • packages/pg-meta/src/sql/studio/database/migrations.ts
  • packages/pg-meta/test/sql/studio/migrations.test.ts
  • packages/ui-patterns/src/MetricCard/index.tsx
  • packages/ui-patterns/src/form/Layout/FormLayout.tsx
💤 Files with no reviewable changes (1)
  • apps/studio/components/interfaces/Integrations/Landing/IntegrationCard.tsx

alaister added 2 commits July 7, 2026 09:59
- Run prettier on migrations-query.test.ts (CI format job failure)
- Only clear the deleted snippet id from dashboard history in the SQL
  editor 404 fallback, instead of wiping whatever snippet was last
  visited (CodeRabbit review feedback)
- Extract the repeated deleted-snippet condition into a named
  isSnippetDeleted boolean

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
href={`/project/${projectRef}/observability/query-performance?totalTimeFilter=${encodeURIComponent(JSON.stringify({ operator: '>', value: 1000 }))}`}
linkTooltip="Go to query performance"
>
<MetricCardHeader linkTooltip="Go to query performance">

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dropped the href on this header (and the ones below) since each card is already wrapped in a Link — a nested anchor is invalid HTML and was causing the DOM-nesting hydration error. Clicks on the chevron just bubble up to the card link; keeping linkTooltip preserves the tooltip + chevron affordance.

export const getMigrationsSql = (): SafeSqlFragment => {
// The migrations table only exists once a migration has been applied (e.g. via
// the CLI or the dashboard). Guard with to_regclass + query_to_xml so this query
// returns zero rows instead of erroring with 42P01 (undefined_table).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Context on this change: the previous bare select threw 42P01 (undefined_table) when supabase_migrations.schema_migrations did not exist yet, which surfaced as a 400 (with retries) on every dashboard load for projects without migrations. The to_regclass + query_to_xml guard is the same pattern we already use for the storage.buckets check in src/sql/studio/advisor/lints.ts.

alaister and others added 3 commits July 7, 2026 12:54
…g trigger

Same invalid button-in-button nesting as the other toggle switches —
React flags it as a hydration risk. Same asChild + div fix.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
- CreateRolePanel called useForm without defaultValues, so the name
  field went uncontrolled -> controlled on first keystroke. Wire up the
  existing initialValues const as defaultValues.
- UsersV2's custom renderRow didn't forward the row key to <Row>, firing
  a missing-key warning after the list re-renders (e.g. creating a user).
  Pass key={id} to match the pattern used in the other data grids.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo

@joshenlim joshenlim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixes all look good! Verified changes locally

…gres

query_to_xml is forbidden through Multigres's connection pooler
(MUL-736, dup of PSQL-1318), so the to_regclass + query_to_xml guard
added for the missing supabase_migrations.schema_migrations table would
fail on Multigres-pooled connections.

Replace it with the pattern splinter used to fix PSQL-1318: a PL/pgSQL
do-block guarded by to_regclass (PL/pgSQL defers planning, so the table
reference is never planned when the table is absent -> no 42P01) that
stashes the rows as jsonb in a transaction-local GUC via
set_config(..., true), followed by a select that reads the GUC back.
pg-meta sends the whole string as a single simple-protocol query, which
Postgres runs in one implicit transaction, so the GUC survives to the
select and reverts afterwards without leaking into pooled sessions.

The test harness now mirrors postgres-meta's multi-statement result
handling (rows of the last statement that produced any), and new tests
cover the exact string pg-meta sends (statement_timeout prefix
included) plus GUC non-leakage on a reused connection.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@apps/studio/components/interfaces/Integrations/CronJobs/CronJobTableCell.tsx`:
- Around line 96-109: The `CronJobTableCell` formatting logic has a typo in the
`col.id` check, so the `dayjs(value).valueOf()` branch never runs for the
latest-run column. Update the conditional in `CronJobTableCell` to use the
actual `latest_run` identifier used by the table and `CronJob` fields, so the
formatting path for that column is reached and `formattedValue` is computed
correctly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d2fd1b6c-dbaa-47f0-b759-b1e4a026ba41

📥 Commits

Reviewing files that changed from the base of the PR and between e40668b and c24822f.

📒 Files selected for processing (11)
  • apps/studio/components/interfaces/Auth/Users/UsersV2.tsx
  • apps/studio/components/interfaces/Database/Extensions/ExtensionRow.tsx
  • apps/studio/components/interfaces/Database/Publications/PublicationsTableItem.tsx
  • apps/studio/components/interfaces/Database/Roles/CreateRolePanel.tsx
  • apps/studio/components/interfaces/Integrations/CronJobs/CronJobTableCell.tsx
  • apps/studio/components/interfaces/Integrations/CronJobs/CronJobs.constants.tsx
  • apps/studio/components/interfaces/Organization/BillingSettings/Subscription/ExitSurveyModal.tsx
  • apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx
  • packages/pg-meta/src/sql/studio/database/migrations.ts
  • packages/pg-meta/test/db/utils.ts
  • packages/pg-meta/test/sql/studio/migrations.test.ts
✅ Files skipped from review due to trivial changes (1)
  • apps/studio/components/interfaces/Organization/BillingSettings/Subscription/ExitSurveyModal.tsx
🚧 Files skipped from review as they are similar to previous changes (5)
  • apps/studio/components/interfaces/Auth/Users/UsersV2.tsx
  • apps/studio/components/interfaces/Database/Extensions/ExtensionRow.tsx
  • apps/studio/components/interfaces/Database/Roles/CreateRolePanel.tsx
  • packages/pg-meta/src/sql/studio/database/migrations.ts
  • apps/studio/components/interfaces/TableGridEditor/SidePanelEditor/ColumnEditor/ColumnEditor.tsx

@alaister
alaister merged commit 9af6e65 into master Jul 8, 2026
35 checks passed
@alaister
alaister deleted the alaister/studio-dom-nesting-and-query-fixes branch July 8, 2026 04:32
@github-actions

github-actions Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (master-1783485305)

Score Average Improvements Regressions
Knowledge Usage 92.3% (+0pp) 2 🟢 1 🔴
Tool Usage 70.6% (-2pp) 2 🟢 1 🔴
SQL Identifier Quoting 100% (+0pp) - -
SQL Validity 100% (+0pp) - -
Time_to_first_token 3.1tok (-0.44tok) 19 🟢 10 🔴
Llm_calls 2.89 (+0.05) 12 🟢 12 🔴
Tool_calls 2.92 (+0.01) 12 🟢 11 🔴
Errors 5.23 (+0.01) 3 🟢 5 🔴
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 21236.14tok (-73.77tok) 11 🟢 14 🔴
Prompt_cached_tokens 6726.62tok (-976.92tok) 10 🟢 14 🔴
Prompt_cache_creation_tokens 0tok (+0tok) - -
Prompt_cache_creation_5m_tokens 0tok (+0tok) - -
Prompt_cache_creation_1h_tokens 0tok (+0tok) - -
Completion_tokens 590.79tok (-28.76tok) 15 🟢 14 🔴
Completion_reasoning_tokens 95.91tok (-5.31tok) 14 🟢 12 🔴
Total_tokens 21826.93tok (-102.53tok) 13 🟢 16 🔴
Estimated_cost 0$ (+0$) 13 🟢 14 🔴
Duration 17.29s (-2.25s) 21 🟢 8 🔴
Llm_duration 11.66s (-0.81s) 18 🟢 11 🔴

alaister added a commit that referenced this pull request Jul 8, 2026
…rom #46424) (#47657)

Post-merge fixes for the TanStack Start migration (#46424) — things that
broke on the TanStack build as master evolved under the migration
branches. Kept on their own branch off master rather than piling onto
the E2E-matrix PR (#47119); all land on master and cascade up to S6 +
the big PR.

Common theme: a master PR changed something the Next pipeline handles
via `next/font` / `pages/_app.tsx` / `next.config.ts`, but the
hand-rolled TanStack equivalent (`routes/__root.tsx`,
`styles/fonts.css`, `vercel.ts`) wasn't updated to match — invisible on
the Next deploy, broken only on TanStack.

---

## 1. Monaco loader path (#47182)

#47182 re-nested the served Monaco assets from a flat
`public/monaco-editor/` layout into `public/monaco-editor/vs/` and
updated `pages/_app.tsx`, but `routes/__root.tsx` still pointed
`loader.config` at the old path, so `loader.js` 404'd and **no Monaco
editor mounted anywhere in the TanStack build**. Now mirrors the Next
config (`${origin}${BASE_PATH}/monaco-editor/vs`, window-guarded for
SSR). Was failing the whole `tanstack` E2E shard on #47119.

## 2. Inter + Manrope fonts (#47306)

#47306 renamed Tailwind's sans var `--font-custom` → `--font-sans` and
added `--font-heading` (Manrope), set via `next/font` on Next.
`fonts.css` still only set the now-ignored `--font-custom`, so the body
fell back to the theme's system chain (`Circular, custom-font,
Helvetica…`) at weight 450 — that's the "Inter weights look wrong".
Manrope was missing entirely.

- Wire `--font-sans` (Inter) + `--font-heading` (Manrope) to match
`next/font`.
- **Vendor all three families** (Inter, Manrope, Source Code Pro) via
`@font-face` so nothing depends on the Google Fonts CDN — matches
`next/font` self-hosting, and (see below) `font-src` doesn't allow
`fonts.gstatic.com` anyway.

Verified in-browser: computed `body` → `Inter`, headings → `Manrope`,
all loading from local `/assets/*.woff2`.

## 3. Security headers / CSP (next.config.ts `headers()`)

The Next build sets X-Frame-Options / X-Content-Type-Options / HSTS /
**Content-Security-Policy** / Referrer-Policy via `next.config.ts`. The
TanStack build never carried these over — `vercel.ts` only set
cache-control, so **the deployed TanStack dashboard shipped with no CSP
at all**.

The TanStack deploy serves a static shell (no server to attach headers),
so they go in the Vercel config:
- `security-headers.ts` — shared source of truth, reuses `getCSP()`,
env-gated exactly like next.config.
- `vercel.ts` — apply to every response (all base-path prefixes): full
`getCSP()` + HSTS on platform.
- `scripts/serve.js` — the non-platform set (`frame-ancestors 'none'`)
for the self-hosted server.

**Tested the policy in a real browser** (temporarily enforced it on the
TanStack build via /test-supabase-local): everything passed except one
real gap — `font-src` was missing `data:`, so GraphiQL's bundled Monaco
codicon font and Stripe's payment-element fonts (both data: URIs) were
blocked (37 violations on a cold load). Added `data:` to `font-src` in
`csp.ts` → violations drop to zero, SQL editor Monaco renders clean.
That gap affects the Next build too.

---

## 4. `node:path` import crashing `/project/[ref]/merge`

Found by a full-site click-through of the TanStack build (all product
areas, ongoing — see below). `useEdgeFunctionsDiff.ts` +
`EdgeFunctionsDiffPanel.tsx` did `import { basename } from 'path'` in
client code. Webpack (Next) polyfills `path` in the browser; Vite
externalizes it, so the whole `/merge` route crashed with "Module
\"path\" has been externalized for browser compatibility". Replaced the
two `basename` call sites with a string helper. Verified in-browser:
`/merge` renders.

## 5. URL shape — Next-style search-param semantics + shim fixes

The dashboard produced malformed URLs vs the Next build (strange query
params, trailing slashes, `##` hashes). Root cause + audit verified
empirically against `@tanstack/[email protected]`; all fixed with
unit tests and browser-verified:

- **`createRouter` used TanStack's default JSON search codec** —
`?flag=true` became `?flag=%22true%22` via links, repeated
`?filter=…&filter=…` collapsed into a JSON array (breaking
multi-filter/sort table-editor URLs and the account-page round-trip,
which double-encoded), and search values arrived as numbers/booleans
where the app expects strings. New `lib/router-search-params.ts`
(Next-style: strings in, strings out, repeated keys → string[]) wired
into the router.
- **Link shim** (`compat/next/link.tsx`): `URL.hash` includes the
leading `#` while TanStack's `hash` prop adds its own → every
`href="…#section"` navigated to `##section` (hash-scroll broke);
`Object.fromEntries(searchParams)` dropped repeated query params. Both
fixed.
- **Trailing slash injected before the query** on every `?`-only
relative navigation (`/auth/providers/?provider=…`): fixed in the compat
router (prefix current pathname) and via a custom nuqs adapter
(`lib/nuqs-tanstack-adapter.tsx`) replacing the stock tanstack-router
adapter, whose `navigate({ to: '?…' })` writes hit the same TanStack
behavior (123 files use nuqs).
- **Pathname-less `router.push({ query })` leaked path params** — Next
re-consumes `ref`/`id` from `query` into the path pattern; the shim
didn't, yielding
`/editor/17597?schema=public&ref=<ref>&id=17597&filter=…` from
table-editor filter/sort, linter panels, and advisor shortcuts. The shim
now defaults the pathname to the current route pattern and backfills
omitted params.
- **Redirects dropped query + hash** (Next's `redirects()` preserves
them): `__root.tsx` `matchRedirect` and `routes/index.tsx` now carry
incoming params/hash through (consumed rule params excluded,
destination's own params win). `/?next=new-project&projectName=zzz` →
`/new/new-project?projectName=zzz`; `/sql/quickstarts?template=x#frag` →
`/sql/examples?template=x#frag`.

Browser-verified post-fix: advisors `?preset=WARN`, providers
`?provider=Google`, `?schema=auth` — all clean (no `/?`, no leaks);
repeated `filter` params survive hydration; `=true` unquoted; single
`#`.

## 6. TanStack `navigate` corrupting query values (Logs Explorer SQL
newline loss)

TanStack router-core treats a query string embedded in `navigate({ to
})` as part of the *path*: `decodePath` percent-decodes it and
`sanitizePathSegment` strips control characters, silently deleting every
`%0A`. Logs Explorer's SQL (`s` param) lost its newlines on Run/reload —
`order by timestamp desc` / `limit 5` glued into `desclimit 5`, which
then failed the LIMIT lint. Pre-existing on the TanStack build (the
stock nuqs adapter had the same shape); Next unaffected.

Fixed by never embedding query strings in `to`: the nuqs adapter and the
compat `router.push`/`replace`/`prefetch` (plus the `next/navigation`
shim) now pass search as an object through the app codec
(`splitInternalUrl` hoisted to `lib/internal-url.ts`). Guard test drives
a real `createRouter` with multi-line SQL through both producers.
Browser-verified: newlines survive the full Run → reload → re-Run cycle.

## 7. Integration overview markdown never loaded (all integrations)

`MarkdownContent` used a template-literal dynamic import
(``import(`@/static-data/integrations/${id}/overview.md`)``) — webpack
builds a context module for that, Vite can't analyze it, so every
integration detail page threw `Failed to resolve module specifier` and
rendered no overview text. Fixed with an explicit lazy registry of
literal imports (`static-data/integrations/overviews.ts`, drift-guarded
by a test) plus an `mdRawLoader()` Vite plugin mirroring next.config's
turbopack raw-loader rule. Both runtimes keep working; md stays out of
the main bundle.

## 8. GraphiQL editor never mounted (`exports is not defined`)

Our `umdAmdShortCircuit()` Vite plugin (which disarms Monaco's global
AMD loader for deps like papaparse) rewrote `typeof define ===
'function' && define.amd` to `false` inside `monaco-editor`'s bundled
copy of marked — whose UMD relies on its own *local* `define` shim — so
the whole optimized monaco chunk failed to evaluate and GraphiQL's
editor pane stayed blank. The check now only short-circuits when
`define` is the global AMD loader. Browser-verified: all four GraphiQL
Monaco panes mount, queries execute. (Known follow-up: GraphiQL's Monaco
workers fall back to the main thread under Vite — functional, worker
wiring is Next-specific `setup-workers/webpack`.)

## 9. `@sentry/nextjs` bundling Next internals — built TanStack bundle
crashed (caught by E2E)

The E2E suite against the **built** TanStack bundle (not the dev server)
found lazy chunks like `table-editor-*.js` dead on arrival:
`@sentry/nextjs` (imported by ~25 client files) drags in
`next/dist/shared/lib/constants`, whose module scope evaluates
`process?.features?.typescript` — optional chaining doesn't guard an
undeclared `process` in the browser, so the whole chunk failed at load
with `ReferenceError: process is not defined`. Dev shims `process`,
which is why weeks of dev-server testing never saw it.

Fixed by aliasing `@sentry/nextjs` → `compat/sentry-nextjs.ts`
(re-exports `@sentry/react`, same deduped 10.59.0, plus explicit
stand-ins for the three Next-only APIs) in the Vite build only.
Verified: fresh build has zero Next-internals markers in any chunk;
table editor loads clean; full E2E suite run against the built bundle.

Note for the stack: `alaister/tanstack-start` / the E2E-matrix branch
already carried a different fix for the same crash (a `next/constants`
shim) that never made it to master — the cherry-pick onto those branches
keeps **both** (the shim covers any other transitive importer; the alias
keeps Next internals out of the client bundle entirely).

**Follow-up found while fixing:** Sentry is never *initialized* in the
TanStack runtime — `instrumentation-client.ts` /
`sentry.server.config.ts` are Next-convention files nothing imports
under TanStack, so `captureException` calls are silent no-ops. Needs an
`@sentry/react` init (+ `tanstackRouterBrowserTracingIntegration`) wired
into the TanStack client entry as its own PR.

## 10. GraphiQL Monaco workers + edge-function Deno typings (Vite-only
gaps)

- **GraphiQL's Monaco workers ran on the main thread** under Vite
("Could not create web worker(s)…" — `setup-workers/webpack`'s `new
URL(...)` form isn't rewritten by Vite). A `graphiqlViteWorkers()`
plugin resolves the import to graphiql's own `setup-workers/vite`
variant for client builds (SSR untouched, Next untouched); the
setup-workers chain is `optimizeDeps.exclude`d because the Rolldown
optimizer can't load `?worker` ids.
- **Edge-function editors silently lost their Deno typings** —
`AIEditor` loaded `public/deno/*.d.ts` via `/* @vite-ignore */` imports
that always failed at runtime under Vite. The `.md` raw loader is
generalized into `rawTextLoader` (exact-path allowlist for the two
typings files, served as virtual string modules so the dep scanner never
parses `.d.ts` syntax), and the imports are now static-analyzable
literals that both bundlers handle (turbopack's raw-loader rules match
them on the Next side).

## Split out for reviewability

App-level fixes that reproduce on the Next build too (DOM-nesting
hydration errors, the ghost deleted-snippet nav, the recurring pg-meta
`migrations` 400) moved to their own PR: #47667. Sentry initialization
for the TanStack runtime (captures were silent no-ops) is #47666,
stacked on this PR.

## Full-site test campaign

Drove every dashboard product area on the local TanStack build
(Playwright, human-style) hunting migration regressions:
redirects/404/catch-alls, org, account, project home/branches/merge,
table editor CRUD, SQL editor (Monaco/run/save/templates/AI), all
database pages, all auth pages, storage CRUD, edge functions + realtime,
logs/observability, advisors, settings, integrations hub incl. nested
routes, global UI (palette/connect/switchers/theme/fonts), and a
cross-cutting sweep (document titles, back/forward chain, hard-refresh
hydration on deep URLs, trailing-slash active state). Every failure
found is fixed above and re-verified in-browser; remaining console
quirks were cross-checked against the deployed Next build and are
pre-existing (tracked separately).

## To test

Most fixes are already browser-verified + covered by unit tests and the
self-hosted E2E suite; the last two landed after the final browser pass
and still need an in-browser check:

1. **GraphiQL Monaco workers** — restart the dev server (clear
`apps/studio/node_modules/.vite` once first — the optimizer cache may
hold a stale prebundle of the worker chain). Open
`/project/<ref>/integrations/graphiql/graphiql` with the console open:
the `Could not create web worker(s). Falling back to loading web worker
code in main thread` warning must be gone, and DevTools → Sources →
Threads shows the three workers (json, editor, graphql). Autocomplete in
the query editor stays responsive.
2. **Edge-function Deno typings** — `/project/<ref>/functions/new`: no
"Failed to load … typings" console error, and typing `Deno.` in the
editor offers typed completions (e.g. `Deno.env`).

Spot-checks for the rest (all previously verified):
- `/project/<ref>/merge` renders (no "Module path" crash).
- Multi-line SQL in Logs Explorer survives Run → reload (no `desclimit`
gluing, no LIMIT-lint false failure); `s` param keeps `%0A`.
- `/auth/providers` → open a provider → `?provider=…` with no trailing
slash before `?`; table-editor filter/sort URLs carry no leaked
`ref`/`id` params; `/?next=new-project&projectName=x` lands on
`/new/new-project?projectName=x`.
- Integration detail pages (cron/queues/vault/data_api) show their
overview prose; GraphiQL query editor mounts.
- Built bundle (`MODE=test vite build` + `start:tanstack`): table editor
loads with no `process is not defined`.
- `curl -sI` any page on a platform deploy: `X-Content-Type-Options:
nosniff` (was the invalid `no-sniff`).


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Centralized integration overview markdown loading with registry-based
lookup.
* Improved Monaco loading/asset path handling for smoother editor
startup.
* **Bug Fixes**
* Next-style navigation/search handling now preserves pathname, hash,
repeated query keys, and special characters (including newlines).
* Redirects now reliably carry over query and hash with correct
precedence.
* **Security/Configuration**
* Updated CSP font sourcing and unified security headers delivery across
environments; conditional HSTS behavior.
* Refreshed font CSS variables and font-face definitions to match the
theme.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->


---

### Review feedback: non-prod favicon (Joshen)

The TanStack `__root.tsx` hardcoded the prod favicon; local + hosted
staging now use the white staging favicon (`/favicon/staging`), matching
what `pages/_app.tsx` passes to `MetaFaviconsPagesRouter` for non-prod.
Rather than pull the pages-router component into the TanStack head, it
reuses the same synchronous `NEXT_PUBLIC_ENVIRONMENT` signal the file
already uses for `IS_DEV_TOOLBAR_ENABLED` (the `head()` route option
isn't a React component, so it can't run `_app`'s async CLI check — but
the env signal covers the reported local/staging case).

---------

Co-authored-by: Alaister Young <[email protected]>
Co-authored-by: Joshen Lim <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants