Skip to content

fix(studio): TanStack post-merge fixes — Monaco loader, fonts, CSP (from #46424) - #47657

Merged
alaister merged 26 commits into
masterfrom
alaister/tanstack-migration-fixes
Jul 8, 2026
Merged

alaister merged 26 commits into
masterfrom
alaister/tanstack-migration-fixes

Conversation

@alaister

@alaister alaister commented Jul 6, 2026 •

Copy link
Copy Markdown
Member

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.excluded 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).

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.

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).

…path

#47182 dropped CDN loading for Monaco in every environment and moved the
locally-served assets from a flat public/monaco-editor/ layout into
public/monaco-editor/vs/. The Next entry (pages/_app.tsx) was updated to
match, but the TanStack root (routes/__root.tsx) still pointed loader.config
at ${BASE_PATH}/monaco-editor, so after that landed the loader looked for
loader.js at /monaco-editor/loader.js (404) and no Monaco editor mounted.

Mirror the Next config: serve from ${origin}${BASE_PATH}/monaco-editor/vs
for all environments, window-guarded since __root.tsx is also evaluated
during SSR. Fixes the app-wide Monaco breakage that was failing the TanStack
E2E shard (RLS policy editor, cron SQL, realtime JSON payload, database
functions, GraphiQL coexistence).
@alaister
alaister requested a review from a team as a code owner July 6, 2026 15:35
@supabase

supabase Bot commented Jul 6, 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 ↗︎.

@vercel

vercel Bot commented Jul 6, 2026 •

Copy link
Copy Markdown

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

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

Request Review

@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8c6bf886-06e0-4b96-a517-1469763362dc

📥 Commits

Reviewing files that changed from the base of the PR and between a8f7842 and fa66d18.

📒 Files selected for processing (3)
  • apps/studio/lib/internal-url.test.ts
  • apps/studio/lib/internal-url.ts
  • apps/studio/routes/__root.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/studio/lib/internal-url.ts
  • apps/studio/routes/__root.tsx

📝 Walkthrough

Walkthrough

Studio now standardizes Monaco/font setup, security headers, URL/search/redirect behavior, edge diff file keys, integration overview loading, and Vite compatibility shims.

Changes

Studio asset loading and security headers

Layer / File(s) Summary
Browser-guarded Monaco loader
apps/studio/lib/configure-monaco-loader.ts, apps/studio/pages/_app.tsx, apps/studio/routes/__root.tsx, apps/studio/components/ui/AIEditor/index.tsx, e2e/studio/features/monaco-graphiql-coexistence.spec.ts
Monaco loader setup is centralized, Deno typings loading is consolidated, and the e2e router fallback now uses history state when the Next router is absent.
Font links and CSS variables
apps/studio/routes/__root.tsx, apps/studio/styles/fonts.css
Google Fonts links are removed, local font-face rules are added, and the Studio font CSS variables are renamed and expanded.
Security header policy
apps/studio/csp.ts, apps/studio/next.config.ts, apps/studio/security-headers.ts
CSP font sources include data:, the content-type header spelling is corrected, and shared security headers are assembled from environment checks.
Header injection on served routes
apps/studio/scripts/serve.js, apps/studio/vercel.ts
The same security headers are applied in the local server and Vercel route handling.

Studio URL compatibility and redirect handling

Layer / File(s) Summary
Search param codec
apps/studio/router.tsx, apps/studio/lib/router-search-params.ts, apps/studio/lib/internal-url.ts, apps/studio/lib/router-search-params.test.ts, apps/studio/lib/internal-url.test.ts
The router now uses Next-style search parsing and stringifying, with shared URL-splitting and tests covering repeated keys, hashes, base paths, and round trips.
Nuqs adapter and router URL shaping
apps/studio/lib/nuqs-tanstack-adapter.tsx, apps/studio/compat/next/router.ts, apps/studio/compat/next/navigation.ts, apps/studio/lib/nuqs-tanstack-adapter.test.ts, apps/studio/compat/next/router.test.ts, apps/studio/lib/router-url-shape.test.tsx
Custom nuqs and Next-compat navigation helpers now split pathname, search, and hash explicitly and are covered by URL-shape regression tests.
Redirect query and hash preservation
apps/studio/redirects.shared.ts, apps/studio/routes/__root.tsx, apps/studio/routes/index.tsx, apps/studio/redirects.shared.test.ts
Redirect matching now preserves carried query and hash values, including maintenance-mode branches and root-route redirects.
Next link URL splitting
apps/studio/compat/next/link.tsx
The link compat shim now relies on the shared internal URL splitter.

Studio edge diff file key normalization

Layer / File(s) Summary
Browser-safe file keys
apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx, apps/studio/hooks/branches/useEdgeFunctionsDiff.ts
File-key matching now uses a shared browser-safe helper instead of Node basename.

Studio Vite bundling shims and integration overviews

Layer / File(s) Summary
Vite plugins for Sentry, GraphiQL, and raw text
apps/studio/vite.config.ts, apps/studio/compat/sentry-nextjs.ts, apps/studio/types/markdown.d.ts, apps/studio/TANSTACK_MIGRATION.md
Vite adds raw-text loading, GraphiQL worker swapping, AMD short-circuit changes, and a Sentry alias/shim, with matching migration notes and markdown typing.
Integration overview markdown registry
apps/studio/static-data/integrations/overviews.ts, apps/studio/static-data/integrations/overviews.test.ts, apps/studio/components/interfaces/Integrations/Integration/MarkdownContent.tsx, apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/MarkdownContent.tsx
Integration overview markdown is loaded through a central registry instead of per-component dynamic imports.

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

Sequence Diagram(s)

sequenceDiagram
  participant RootRoute as routes/__root.tsx
  participant IndexRoute as routes/index.tsx
  participant Redirects as redirects.shared.ts

  RootRoute->>Redirects: matchRedirect({ pathname, search, hash })
  IndexRoute->>Redirects: redirect({ href }) with carried search/hash
  Redirects-->>RootRoute: matched destination with preserved query/hash
Loading
sequenceDiagram
  participant NuqsAdapter as nuqs-tanstack-adapter.tsx
  participant NextRouter as compat/next/router.ts
  participant Navigation as compat/next/navigation.ts
  participant TanStackRouter as TanStack Router

  NuqsAdapter->>TanStackRouter: buildSearchUpdateArgs(pathname, search)
  NextRouter->>TanStackRouter: withDefaultPathname() / resolveSearchOrHashOnlyTarget()
  Navigation->>TanStackRouter: splitInternalUrl(href) -> to/search/hash
  TanStackRouter-->>NuqsAdapter: navigate() with normalized href
Loading

Possibly related PRs

Suggested labels: autofix

Suggested reviewers: ivasilov, awaseem

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the change broadly, but it does not follow the repository's required template sections. Rewrite it using the required headings and fill in CONTRIBUTING.md, change type, current behavior, new behavior, and additional context.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is specific and matches the main TanStack post-merge fixes, especially Monaco loader, fonts, and CSP.
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/tanstack-migration-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 6, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results

passed  232 passed
skipped  5 skipped

Details

stats  237 tests across 27 suites
duration  3 minutes, 57 seconds
commit  fa66d18

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

alaister added 2 commits July 6, 2026 23:50
#47306 renamed Tailwind's sans var from --font-custom to --font-sans and added
--font-heading (Manrope), setting both via next/font on the Next build. The
TanStack fonts.css was never updated — it still only set the now-ignored
--font-custom, so --font-sans was unset and resolved to theme.css's fallback
chain (Circular, custom-font, Helvetica Neue, ...) i.e. system fonts, and
--font-heading/Manrope was missing entirely. Body text rendered as Helvetica at
weight 450, which is why the Inter weights looked wrong.

- fonts.css: set --font-sans (vendored Inter) and --font-heading (Manrope) to
  match what next/font provides on Next; drop the dead --font-custom.
- __root.tsx: load Manrope over the same Google Fonts <link> already used for
  Source Code Pro (Inter stays vendored via @font-face).

Verified against the built CSS bundle in a browser: computed body font-family is
now Inter (was the Circular/system fallback) and headings resolve to Manrope.
The unlayered :root wins over theme.css's @layer theme self-referential
--font-sans, same as the Next inline-style approach.
@alaister alaister changed the title fix(studio): point TanStack Monaco loader at re-nested vs/ asset path (from #46424) fix(studio): TanStack post-merge fixes — Monaco loader path + Inter/Manrope fonts (from #46424) Jul 6, 2026
Follow-up to the font fix: drop the Google Fonts <link> and self-host all three
families via @font-face in fonts.css, matching next/font (which self-hosts them
on the Next build). Keeps self-hosted / offline studio working — no runtime CDN
dependency.

- Inter + Source Code Pro reuse the woff2 fonts/index.ts already ships.
- Manrope: vendored latin + latin-ext subset variable woff2 (fonts/manrope/,
  from @fontsource-variable/manrope) with the standard Google unicode-ranges;
  no italic axis. Weight ranges mirror fonts/index.ts.
- __root.tsx: remove the googleapis/gstatic preconnects + stylesheet link.

Verified in a browser against the built bundle: Inter (body), Manrope (headings)
and Source Code Pro (mono) all load from local /assets/*.woff2, and no
fonts.googleapis/gstatic references remain in the client output.

@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/styles/fonts.css`:
- Around line 42-51: Remove the unnecessary quotes around the Manrope font
family in both `@font-face` blocks in fonts.css. Update the font-family
declarations for the Manrope entries to use the unquoted name, while leaving
quoted families like Source Code Pro unchanged; use the `@font-face` rules as the
location reference.
🪄 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: f0b2c783-c389-49ff-8df6-b30817785d2b

📥 Commits

Reviewing files that changed from the base of the PR and between bbdee87 and 358be92.

⛔ Files ignored due to path filters (2)
  • apps/studio/fonts/manrope/manrope-latin-ext-wght-normal.woff2 is excluded by !**/*.woff2
  • apps/studio/fonts/manrope/manrope-latin-wght-normal.woff2 is excluded by !**/*.woff2
📒 Files selected for processing (2)
  • apps/studio/routes/__root.tsx
  • apps/studio/styles/fonts.css

Comment thread apps/studio/styles/fonts.css Resolved
alaister added 2 commits July 7, 2026 00:20
The Next build sets X-Frame-Options / X-Content-Type-Options / HSTS /
Content-Security-Policy / Referrer-Policy via next.config.ts `headers()`. The
TanStack build never carried these over — vercel.ts only set cache-control, so
the deployed dashboard shipped with no CSP.

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

Note: font-src in the CSP is 'self' + cloudflare + supabase-assets (no
fonts.gstatic.com), so vendoring the fonts locally in the previous commit is what
keeps them CSP-compliant. X-Content-Type-Options keeps next.config's 'no-sniff'
value verbatim for parity.
GraphiQL's bundled Monaco ships the codicon icon font as a data: URI, and
Stripe's payment element inlines its fonts the same way, but font-src didn't
allow data: — so those fonts were blocked once the CSP is enforced (surfaced
while testing the CSP on the TanStack build; would affect the Next build too).

Verified in a browser: with the CSP applied, the data: font violations
(37 of them on a cold load) drop to zero, and the SQL editor Monaco renders.
@alaister
alaister requested a review from a team as a code owner July 6, 2026 16:27
@alaister alaister changed the title fix(studio): TanStack post-merge fixes — Monaco loader path + Inter/Manrope fonts (from #46424) fix(studio): TanStack post-merge fixes — Monaco loader, fonts, CSP (from #46424) Jul 6, 2026

@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/security-headers.ts`:
- Around line 19-21: The X-Content-Type-Options header is using an invalid value
in the shared security headers setup, so update the value to nosniff in
security-headers.ts and keep the mirrored copies in next.config.ts and
scripts/serve.js consistent. Make the change in the shared header definition and
the matching header arrays/config paths so all Studio deployment paths use the
same valid setting.
🪄 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: 971f6fbf-f052-4856-8604-ddbc578cca2d

📥 Commits

Reviewing files that changed from the base of the PR and between 358be92 and 2184360.

📒 Files selected for processing (4)
  • apps/studio/csp.ts
  • apps/studio/scripts/serve.js
  • apps/studio/security-headers.ts
  • apps/studio/vercel.ts
✅ Files skipped from review due to trivial changes (1)
  • apps/studio/csp.ts

Comment thread apps/studio/security-headers.ts Outdated
Comment on lines +19 to +21
// Mirrors next.config.ts (note: the effective value browsers honour is
// `nosniff`; kept identical to the Next build to avoid a behaviour split).
{ key: 'X-Content-Type-Options', value: 'no-sniff' },

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm the broken value's blast radius across the studio header paths.
rg -n "no-sniff|X-Content-Type-Options" apps/studio

Repository: supabase/supabase

Length of output: 459


🏁 Script executed:

#!/bin/bash
sed -n '1,120p' apps/studio/security-headers.ts
printf '\n--- next.config.ts ---\n'
sed -n '80,130p' apps/studio/next.config.ts
printf '\n--- serve.js ---\n'
sed -n '160,190p' apps/studio/scripts/serve.js

Repository: supabase/supabase

Length of output: 4295


🌐 Web query:

X-Content-Type-Options valid value nosniff MDN

💡 Result:

The only valid value for the X-Content-Type-Options HTTP response header is nosniff [1]. According to MDN Web Docs, this header is used to signal that the MIME type advertised in the Content-Type header should be respected and not changed [2][3]. By setting X-Content-Type-Options: nosniff, you prevent the browser from performing MIME type sniffing [3]. This is a security measure that ensures browsers do not execute or render content as a type different from what is explicitly declared, helping to mitigate attacks such as cross-site scripting (XSS) where malicious content might otherwise be interpreted as a script or stylesheet [4][3].

Citations:


X-Content-Type-Options should be nosniff everywhere
no-sniff is not a valid value, so MIME-sniffing protection is effectively off here and in the mirrored copies in apps/studio/next.config.ts and apps/studio/scripts/serve.js. Update all three to nosniff so the Next, Vercel, and self-hosted paths stay aligned.

🤖 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/security-headers.ts` around lines 19 - 21, The
X-Content-Type-Options header is using an invalid value in the shared security
headers setup, so update the value to nosniff in security-headers.ts and keep
the mirrored copies in next.config.ts and scripts/serve.js consistent. Make the
change in the shared header definition and the matching header arrays/config
paths so all Studio deployment paths use the same valid setting.

alaister added 7 commits July 7, 2026 01:22
Vite doesn't polyfill Node's path module in the browser bundle (webpack on
Next did), so `import { basename } from 'path'` crashed the whole
/project/[ref]/merge route on the TanStack build with 'Module "path" has
been externalized for browser compatibility'. Replace the two basename
call sites with a string helper.

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

TanStack's default JSON search-param codec coerced ?page=2 to a number and
?flag=true to a boolean, JSON-quoted any string that parses as JSON
(?flag=%22true%22 in the address bar), and collapsed repeated keys — so
multi-value filters like ?filter=a:eq:1&filter=b:eq:2 could never survive a
round trip. The whole app (compat shims, nuqs, useUrlState consumers) was
written against Next pages-router semantics where every search value is a
plain string and repeated keys become arrays.

Provide custom parseSearch/stringifySearch implementing the Next semantics:
URLSearchParams-based, no JSON parsing or type coercion, repeated keys ↔
string arrays, byte-stable round trips. SSR-safe (no window access).

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

Two URL-shape bugs in the next/link compat shim's splitInternalUrl:

- URL.hash includes the leading '#' but TanStack's hash prop expects the
  bare fragment and prepends its own — every <Link href="...#section">
  navigated to '...##section' and hash-scroll never fired.
- Object.fromEntries(parsed.searchParams) kept only the last occurrence of
  a repeated query key, silently dropping multi-value params like
  ?filter=a&filter=b. Collapse to string | string[] per key instead,
  matching the router's Next-style parseSearch shape.

basePath stripping is unchanged; splitInternalUrl is now exported for the
new unit tests.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
TanStack resolves a `?`-only relative `to` by appending it to the current
path, so any navigation that only changes the query string landed on
`<path>/?<query>` — e.g. picking a preset on the advisors page produced
`/advisors/security/?preset=...` and changing an auth provider produced
`/auth/providers/?provider=...`. Two producers fixed:

- The next/router compat shim's push/replace: a resolved `?`/`#`-only
  target is now prefixed with the current (basepath-stripped) pathname.
- nuqs writes (useQueryState/useQueryStates across ~123 files): the stock
  `nuqs/adapters/tanstack-router` adapter navigates with
  `to: renderQueryString(search) || '.'`. Replaced with a custom adapter
  (via nuqs's unstable_createAdapterProvider) that navigates to
  `pathname + renderQueryString(search)`, preserving replace/push, scroll,
  and hash behavior of the stock adapter.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
Next's redirects() carries the incoming query string and hash through to
the redirect destination; the TanStack beforeLoad redirects dropped them —
deep links like /project/x/sql/quickstarts?template=... lost the template
on the rewrite to /sql/examples, and /?next=new-project&projectName=foo
lost projectName.

matchRedirect (redirects.shared.ts) now merges the incoming query and hash
onto the destination via a new pure preserveQueryAndHash helper: params
already set on the destination win, keys the rule matched on (`has`) are
consumed, and a destination hash (e.g. billing#invoices) wins over the
incoming one. The `/` index route redirect does the same, consuming `next`
only when it matched. The shared module stays runtime-agnostic; the config
consumers (next.config.ts / vercel.ts) only import the tables and are
unaffected.

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

Drives an actual TanStack router configured with the app's custom search
codec through the navigation shapes the compat shims and the custom nuqs
adapter produce, asserting Next-shaped hrefs: no JSON coercion or quoting,
repeated keys preserved, no trailing slash injected on ?-only navigations,
single '#' on hash links.

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

Next resolves `push({ query })` (no pathname) against the current route
pattern and re-consumes dynamic params from query into the path. The shim
navigated to a ?-only target instead, so `ref`/`id` — merged into
`router.query` per Next's shape — leaked into the query string on every
query-only push (table editor filter/sort, linter panels, advisor
shortcuts): `/editor/17597?schema=public&ref=<ref>&id=17597&filter=...`.
Default the pathname to the current route pattern and backfill omitted
params (minus TanStack's _splat) so interpolation consumes them.

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.

🧹 Nitpick comments (4)
apps/studio/routes/__root.tsx (1)

136-145: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Monaco loader guard and absolute path look correct, but duplicated with pages/_app.tsx.

This logic — window guard, ${window.location.origin}${BASE_PATH}/monaco-editor/vs — is byte-for-byte duplicated in apps/studio/pages/_app.tsx:121-128. Since both files intentionally exist to support the dual Next/TanStack pipelines (per the fonts.css import comment above), consider extracting the loader config into a small shared helper (e.g. lib/monaco-loader-config.ts) imported by both entry points, so future path changes don't need to be kept in sync manually across two files.

♻️ Proposed extraction
// apps/studio/lib/configure-monaco-loader.ts
import { loader } from '`@monaco-editor/react`'
import { BASE_PATH } from '`@/lib/constants`'

export function configureMonacoLoader() {
  if (typeof window !== 'undefined') {
    loader.config({ paths: { vs: `${window.location.origin}${BASE_PATH}/monaco-editor/vs` } })
  }
}
-if (typeof window !== 'undefined') {
-  loader.config({ paths: { vs: `${window.location.origin}${BASE_PATH}/monaco-editor/vs` } })
-}
+configureMonacoLoader()
🤖 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/routes/__root.tsx` around lines 136 - 145, The Monaco loader
setup is duplicated between __root.tsx and pages/_app.tsx, so future path
changes will drift. Extract the window-guarded loader.config logic that builds
`${window.location.origin}${BASE_PATH}/monaco-editor/vs` into a shared helper
(for example, a configureMonacoLoader function in a small lib module) and import
it from both entry points. Keep the SSR window check inside the shared helper so
both pipelines still behave identically.
apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx (1)

1-1: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Browser-safe rewrite looks correct; consider deduplicating fileKey.

Removing the node:path import and inlining the last-slash slice is a reasonable way to avoid crashing under Vite's browser bundle. However, the identical fileKey implementation is duplicated verbatim in apps/studio/hooks/branches/useEdgeFunctionsDiff.ts. Since both copies must stay behaviorally identical for file matching to work correctly (per the downstream fileKey(f.name) calls in that hook), consider extracting this into a shared utility to avoid drift.

♻️ Suggested consolidation
-const fileKey = (fullPath: string) => fullPath.slice(fullPath.lastIndexOf('/') + 1)
+import { fileKey } from './fileKey.utils'

Also applies to: 33-36

🤖 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/BranchManagement/EdgeFunctionsDiffPanel.tsx`
at line 1, The browser-safe `fileKey` logic is duplicated in
`EdgeFunctionsDiffPanel` and `useEdgeFunctionsDiff`, so keep the behavior in
sync by extracting the shared implementation into a common utility and updating
both call sites to use it. Use the existing `fileKey` helper and the downstream
`fileKey(f.name)` matching in `useEdgeFunctionsDiff` as the anchor points when
consolidating, so file matching continues to behave identically everywhere.
apps/studio/lib/nuqs-tanstack-adapter.tsx (1)

29-48: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Enable structural sharing on the filtered location selector

select returns a fresh object on every location change, so this hook will still re-render on unrelated updates unless the selected value is structurally shared. Pass structuralSharing: true here (or enable it at the router level) so unchanged watched search values keep the same reference.

Possible fix
  const search = useLocation({
+   structuralSharing: true,
    select: (state) =>
      Object.fromEntries(Object.entries(state.search).filter(([key]) => watchKeys.includes(key))),
  })
🤖 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/lib/nuqs-tanstack-adapter.tsx` around lines 29 - 48, Enable
structural sharing for the filtered location selector in
useNuqsTanStackRouterAdapter so unrelated location updates do not force
re-renders. Update the useLocation call that computes search to pass
structuralSharing: true, or apply the same setting at the router level, and keep
the filtering logic based on watchKeys unchanged.
apps/studio/routes/index.tsx (1)

14-34: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider extracting the redirect-suffix logic into a tested utility.

The suffix closure implements non-trivial, easy-to-regress logic (carrying query + hash, conditionally dropping next) inline in the route's beforeLoad. Per Studio testing conventions, pure transformation logic like this should live in a .utils.ts file next to the route and be unit tested directly, rather than only being exercised indirectly through this route.

As per coding guidelines: "PR adds business logic inline in a component that could be extracted to a ComponentName.utils.ts file next to the component and unit tested... PR adds a utility function without test coverage."

♻️ Proposed extraction
-import { stringifySearch } from '`@/lib/router-search-params`'
+import { stringifySearch } from '`@/lib/router-search-params`'
+import { buildRedirectSuffix } from './index.utils'
 
 export const Route = createFileRoute('/')({
   validateSearch: (search: Record<string, unknown>) => ({
     next: typeof search.next === 'string' ? search.next : undefined,
   }),
   beforeLoad: ({ search, location }) => {
-    const suffix = (consumeNext: boolean) => {
-      const carried = { ...location.search } as Record<string, unknown>
-      if (consumeNext) delete carried.next
-      return `${stringifySearch(carried)}${location.hash ? `#${location.hash}` : ''}`
-    }
+    const suffix = (consumeNext: boolean) =>
+      buildRedirectSuffix(location.search, location.hash, consumeNext)
     if (IS_PLATFORM) {
🤖 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/routes/index.tsx` around lines 14 - 34, The redirect suffix logic
in the route’s beforeLoad is non-trivial and should be extracted into a tested
utility. Move the suffix/redirect-query-hash transformation out of the inline
beforeLoad closure in index.tsx into a nearby .utils.ts helper (for example, a
function that accepts location.search, location.hash, and whether next should be
consumed), then update beforeLoad to call that helper and keep only the redirect
decisions there. Add unit tests for the helper to cover preserving arbitrary
query params and hash, and dropping next only when the redirect consumes it.

Source: Coding guidelines

🤖 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.

Nitpick comments:
In
`@apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx`:
- Line 1: The browser-safe `fileKey` logic is duplicated in
`EdgeFunctionsDiffPanel` and `useEdgeFunctionsDiff`, so keep the behavior in
sync by extracting the shared implementation into a common utility and updating
both call sites to use it. Use the existing `fileKey` helper and the downstream
`fileKey(f.name)` matching in `useEdgeFunctionsDiff` as the anchor points when
consolidating, so file matching continues to behave identically everywhere.

In `@apps/studio/lib/nuqs-tanstack-adapter.tsx`:
- Around line 29-48: Enable structural sharing for the filtered location
selector in useNuqsTanStackRouterAdapter so unrelated location updates do not
force re-renders. Update the useLocation call that computes search to pass
structuralSharing: true, or apply the same setting at the router level, and keep
the filtering logic based on watchKeys unchanged.

In `@apps/studio/routes/__root.tsx`:
- Around line 136-145: The Monaco loader setup is duplicated between __root.tsx
and pages/_app.tsx, so future path changes will drift. Extract the
window-guarded loader.config logic that builds
`${window.location.origin}${BASE_PATH}/monaco-editor/vs` into a shared helper
(for example, a configureMonacoLoader function in a small lib module) and import
it from both entry points. Keep the SSR window check inside the shared helper so
both pipelines still behave identically.

In `@apps/studio/routes/index.tsx`:
- Around line 14-34: The redirect suffix logic in the route’s beforeLoad is
non-trivial and should be extracted into a tested utility. Move the
suffix/redirect-query-hash transformation out of the inline beforeLoad closure
in index.tsx into a nearby .utils.ts helper (for example, a function that
accepts location.search, location.hash, and whether next should be consumed),
then update beforeLoad to call that helper and keep only the redirect decisions
there. Add unit tests for the helper to cover preserving arbitrary query params
and hash, and dropping next only when the redirect consumes it.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2b6c8543-ecff-4747-b22d-6f8ae003d160

📥 Commits

Reviewing files that changed from the base of the PR and between 2184360 and 1b87617.

📒 Files selected for processing (16)
  • apps/studio/compat/next/link.test.tsx
  • apps/studio/compat/next/link.tsx
  • apps/studio/compat/next/router.test.ts
  • apps/studio/compat/next/router.ts
  • apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx
  • apps/studio/hooks/branches/useEdgeFunctionsDiff.ts
  • apps/studio/lib/nuqs-tanstack-adapter.test.ts
  • apps/studio/lib/nuqs-tanstack-adapter.tsx
  • apps/studio/lib/router-search-params.test.ts
  • apps/studio/lib/router-search-params.ts
  • apps/studio/lib/router-url-shape.test.tsx
  • apps/studio/redirects.shared.test.ts
  • apps/studio/redirects.shared.ts
  • apps/studio/router.tsx
  • apps/studio/routes/__root.tsx
  • apps/studio/routes/index.tsx
✅ Files skipped from review due to trivial changes (3)
  • apps/studio/lib/nuqs-tanstack-adapter.test.ts
  • apps/studio/lib/router-search-params.ts
  • apps/studio/hooks/branches/useEdgeFunctionsDiff.ts

alaister added 5 commits July 7, 2026 03:32
… in navigations

Under the TanStack build, three navigation producers embedded the query
string inside the router's `to` (`navigate({ to: '/path?s=...' })`): the
custom nuqs adapter's updateUrl, the next/router compat shim's
push/replace, and the next/navigation compat shim's push/replace.
TanStack router-core treats the whole `to` string as a path —
buildLocation → interpolatePath → decodePath percent-DECODES it, then
sanitizePathSegment strips control characters (/[\x00-\x1f\x7f]/). Every
%0A newline in a query value was silently deleted.

User-visible symptom: Logs Explorer SQL (the `s` param) lost its
newlines on Run/reload, gluing `order by timestamp desc` and `limit 5`
into `order by timestamp desclimit 5`, which then failed the LIMIT lint.
Any query value with control characters was affected on client-side
navigations. The Next build was unaffected.

Fix: never embed `?query`/`#hash` in `to`.
- Hoist the next/link shim's splitInternalUrl into lib/internal-url.ts
  (shared; behavior unchanged for Link) and use it in the next/router
  and next/navigation shims to pass { to, search, hash } separately —
  `search: {}` / `hash: ''` keep Next's push-without-query semantics.
  Prefetch/preloadRoute paths are split the same way so they preload
  the real target.
- The nuqs adapter now navigates with `to` = current pathname and the
  full search state as a record (buildSearchUpdateArgs, replacing
  buildSearchUpdateTarget), letting the app's Next-style search codec
  serialize values losslessly. Side effect: nuqs-written URLs now
  percent-encode reserved chars like `:` (URLSearchParams semantics),
  consistent with every other producer; values round-trip identically.
- Also fix the pre-existing tsc error on the navigate pipeline
  (`useParams({ strict: false })` can type as undefined).

Tests: lib/router-url-shape.test.tsx now drives a real router through
both producer shapes with multi-line SQL fixtures asserting lossless
round-trips ("limit 5" intact); splitInternalUrl tests moved to
lib/internal-url.test.ts with %0A and already-basepath-relative cases;
nuqs adapter tests updated for buildSearchUpdateArgs.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
Every integration detail page's overview text was blank under the Vite
dev/TanStack build: the two MarkdownContent components loaded their copy
via a template-literal dynamic import
(import(`@/static-data/integrations/${id}/overview.md`)), which webpack
turns into a context module but Vite/Rolldown leaves untouched, so the
browser threw "TypeError: Failed to resolve module specifier" for every
integration (data_api, cron, queues, vault, graphiql, ...).

Replace the template-literal import with an explicit registry of literal
dynamic imports (static-data/integrations/overviews.ts) that both
bundlers can statically analyze and code-split, and add an mdRawLoader
Vite plugin mirroring next.config.ts's raw-loader rule so .md files
resolve to their text content under Vite without query-suffixed
specifiers (which would break the turbopack rule). A unit test keeps the
registry in sync with the overview.md files on disk, and types/markdown.d.ts
types the literal .md imports.

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

On /project/<ref>/integrations/graphiql/graphiql under the Vite build,
the editor pane never mounted and the console showed
"ReferenceError: exports is not defined" inside the optimized
monaco-editor dep chunk (twice).

Root cause: monaco-editor/esm/vs/base/common/marked/marked.js (pulled in
by @graphiql/react's bundled Monaco — the only place studio bundles
Monaco instead of using the CDN loader) wraps marked's UMD bundle in a
*local* define shim (function define(deps, factory) {
factory(__marked_exports) }; define.amd = true) and its ESM tail reads
__marked_exports.X || exports.X. The umdAmdShortCircuit() plugin
rewrote the UMD check 'typeof define === "function" && define.amd' to a
bare 'false', diverting the factory to the global-object branch,
leaving __marked_exports empty, so the tail's exports.X fallback threw
at module evaluation and the whole graphiql chunk failed to load.

Fix: replace the check with
'(typeof define === "function" && define !== globalThis.define && define.amd)'
instead of 'false' — it still disarms UMD wrappers that would register
against Monaco's global CDN loader (papaparse on
/functions/[slug]/invocations, the original bug), but leaves local AMD
shims like marked's working. Also drop 'define.amd': 'false' from the
config-level define, which would have broken the same file in the
production Rolldown build; the transform plugin now owns this
substitution for both pipelines.

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

The built TanStack bundle (vite build) crashed at module load on the
table editor route (and any other lazy route whose chunk pulled in
Sentry) with "ReferenceError: process is not defined". The chain:
studio code does `import * as Sentry from '@sentry/nextjs'` in ~25
client files -> @sentry/nextjs's client entry imports
next/dist/shared/lib/constants -> its module scope evaluates
`...(process?.features?.typescript ? ['next.config.mts'] : [])`, and
optional chaining does not guard an undeclared `process` identifier in
the browser, so the whole chunk throws before any component runs. The
Vite dev server shims `process`, which is why this only surfaced in the
production/test build (caught by E2E).

Fix: alias the bare `@sentry/nextjs` id to compat/sentry-nextjs.ts in
vite.config.ts (TanStack build only -- the Next build doesn't read this
config). The shim re-exports @sentry/react (the same-version package
@sentry/nextjs wraps on the client; every API studio uses at runtime --
captureException, captureMessage, startSpan, withScope, setTag, setUser,
init, and the Event/Breadcrumb/StackFrame types -- exists there) and adds
explicit stand-ins for the Next-only APIs (captureRouterTransitionStart,
captureRequestError, withSentryConfig) so the alias can never surface an
"undefined is not a function".

The alias also obsoletes the previous @sentry/nextjs SSR workarounds
(ssr.noExternal entry + ssr.optimizeDeps.include) -- the id is rewritten
before SSR resolution ever sees it, and @sentry/react ships real ESM.

No dependency changes: @sentry/react is already a direct studio dep
resolving to 10.59.0, exactly matching @sentry/[email protected]'s own
dependency.

Verified: test-mode TanStack build passes (prerender + smoke), no built
client chunk contains process?.features / middleware-manifest.json /
PHASE_PRODUCTION_BUILD / next/dist / __NEXT_DATA__, and tsc is clean
apart from the known pre-existing ui-patterns InstructionBlocks error.

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

The routerPush helper reached for window.next.router, which only exists
under the Next runtime — on the TanStack build both coexistence tests
failed with 'Next router not available'. Fall back to History-API
pushState + popstate, which TanStack Router subscribes to, keeping the
client-side (chunk-preserving) navigation these tests depend on.

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
* --font-sans -> body (Inter) [theme.css: --font-sans]
* --font-heading -> headings (Manrope) [globals.css @theme inline]
* --font-source-code-pro -> mono (Source Code Pro)
* If a var is renamed on the Next side (fonts/index.ts / theme.css), rename it

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.

Review context for the sentence I trimmed from this header: #47306 renamed the sans var from --font-custom to --font-sans and added --font-heading (Manrope), but this file was never updated — so on the TanStack build the body fell through to the theme fallback chain (Circular/system) and headings never got Manrope. That is the regression the renames + Manrope @font-face below fix.

optimizeDeps: {
include: ['@sentry/nextjs'],
},
// `@sentry/nextjs` deliberately has no entry here: the resolve.alias

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.

Change context: @sentry/nextjs previously needed CJS workarounds here — a noExternal entry plus ssr.optimizeDeps.include (Vite 8.0.13's SSR module runner evaluated its CJS without the compat wrapper and crashed with "exports is not defined"). I dropped both in this PR: the resolve.alias above rewrites the id to the @sentry/react-backed shim before SSR resolution ever sees it, so the workarounds became unreachable.

// transform above — a blanket `'define.amd': 'false'` define would also
// rewrite the *read* in vendored bundles that install their own local
// `define` shim (monaco-editor's `esm/vs/base/common/marked/marked.js`)
// and break them — see the plugin's comment for the failure mode.

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.

For the record, the "failure mode" referenced here was hit on this branch: the previous blanket 'define.amd': 'false' define (and an earlier unguarded transform) also rewrote the read inside monaco's vendored marked.js, whose local define shim relies on the AMD branch — the GraphiQL editor pane died with ReferenceError: exports is not defined. Hence the substitution now lives only in the guarded umdAmdShortCircuit() transform.

// `navigate({ to: renderQueryString(search) || '.', from })`. That shape is
// doubly broken for us:
// - TanStack resolves a `?`-only relative `to` by *appending* it to the
// current path, injecting a trailing slash — every nuqs write turns

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.

Both failure modes listed here were live regressions on this branch, not theoretical: every nuqs write on /auth/providers picked up a trailing slash, and Logs Explorer SQL in s lost its newlines (desc\nlimit 5 → desclimit 5). The unit tests alongside (nuqs-tanstack-adapter.test.ts, router-url-shape.test.tsx) pin both.

@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

🧹 Nitpick comments (2)
apps/studio/lib/internal-url.test.ts (1)

63-68: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Add an SSR-mode test case for cross-origin URLs.

All current tests run with window defined, so they don't exercise the typeof window === 'undefined' branch in splitInternalUrl — which is the exact branch with the cross-origin detection gap flagged in internal-url.ts. Once that's fixed, add a case simulating SSR (e.g. vi.stubGlobal('window', undefined)) asserting splitInternalUrl('https://supabase.com/docs') still returns the full URL unchanged.

🤖 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/lib/internal-url.test.ts` around lines 63 - 68, The existing
cross-origin URL test only covers the browser path, so add an SSR-specific case
in the splitInternalUrl test suite that simulates typeof window === 'undefined'
(for example by stubbing global window to undefined) and asserts
splitInternalUrl keeps a cross-origin URL like https://supabase.com/docs
unchanged. Place it alongside the current splitInternalUrl assertions so the new
test explicitly covers the SSR branch and the cross-origin handling gap.
apps/studio/static-data/integrations/overviews.ts (1)

58-63: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider unit-testing loadIntegrationOverview's branch behavior.

overviews.test.ts only asserts INTEGRATION_OVERVIEW_IDS stays in sync with disk; the null-for-unknown-id and stringified-markdown-for-known-id branches of loadIntegrationOverview itself aren't directly exercised. Since both MarkdownContent components branch on markdown !== null, a regression here (e.g., accidentally returning undefined or throwing instead of null) wouldn't be caught by the existing test.

As per path instructions for apps/studio/** (Studio Testing Review Rules): "PR adds a utility function without test coverage" should be flagged.

🤖 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/static-data/integrations/overviews.ts` around lines 58 - 63, Add
unit tests for loadIntegrationOverview to cover both branches: verify it returns
null for an unknown integrationId and returns the stringified default markdown
for a known integration. Mock the dynamic loader in INTEGRATION_OVERVIEWS so the
test exercises loadIntegrationOverview directly, and assert the return
type/value rather than only the disk sync behavior currently covered in
overviews.test.ts. This should also indirectly protect the MarkdownContent
null-check path by ensuring the utility keeps returning null instead of
undefined or throwing for missing ids.

Source: Path instructions

🤖 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/lib/internal-url.ts`:
- Around line 62-80: The cross-origin check in splitInternalUrl() is still gated
on window, which makes SSR treat absolute external URLs as internal links.
Update the origin comparison to use the parsed URL against the computed base
origin unconditionally, so compat/next/link.tsx gets the same href-to result on
server and client. Keep the fix localized to splitInternalUrl() and preserve the
existing fallback behavior when URL parsing fails.

---

Nitpick comments:
In `@apps/studio/lib/internal-url.test.ts`:
- Around line 63-68: The existing cross-origin URL test only covers the browser
path, so add an SSR-specific case in the splitInternalUrl test suite that
simulates typeof window === 'undefined' (for example by stubbing global window
to undefined) and asserts splitInternalUrl keeps a cross-origin URL like
https://supabase.com/docs unchanged. Place it alongside the current
splitInternalUrl assertions so the new test explicitly covers the SSR branch and
the cross-origin handling gap.

In `@apps/studio/static-data/integrations/overviews.ts`:
- Around line 58-63: Add unit tests for loadIntegrationOverview to cover both
branches: verify it returns null for an unknown integrationId and returns the
stringified default markdown for a known integration. Mock the dynamic loader in
INTEGRATION_OVERVIEWS so the test exercises loadIntegrationOverview directly,
and assert the return type/value rather than only the disk sync behavior
currently covered in overviews.test.ts. This should also indirectly protect the
MarkdownContent null-check path by ensuring the utility keeps returning null
instead of undefined or throwing for missing ids.
🪄 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: 5e7910e6-510f-4f0b-92fc-a40a2e7a5212

📥 Commits

Reviewing files that changed from the base of the PR and between 2184360 and 14cd885.

📒 Files selected for processing (34)
  • apps/studio/TANSTACK_MIGRATION.md
  • apps/studio/compat/next/link.tsx
  • apps/studio/compat/next/navigation.ts
  • apps/studio/compat/next/router.test.ts
  • apps/studio/compat/next/router.ts
  • apps/studio/compat/sentry-nextjs.ts
  • apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx
  • apps/studio/components/interfaces/Integrations/Integration/IntegrationOverviewTabV2/MarkdownContent.tsx
  • apps/studio/components/interfaces/Integrations/Integration/MarkdownContent.tsx
  • apps/studio/components/ui/AIEditor/index.tsx
  • apps/studio/hooks/branches/useEdgeFunctionsDiff.ts
  • apps/studio/lib/configure-monaco-loader.ts
  • apps/studio/lib/internal-url.test.ts
  • apps/studio/lib/internal-url.ts
  • apps/studio/lib/nuqs-tanstack-adapter.test.ts
  • apps/studio/lib/nuqs-tanstack-adapter.tsx
  • apps/studio/lib/router-search-params.test.ts
  • apps/studio/lib/router-search-params.ts
  • apps/studio/lib/router-url-shape.test.tsx
  • apps/studio/next.config.ts
  • apps/studio/pages/_app.tsx
  • apps/studio/redirects.shared.test.ts
  • apps/studio/redirects.shared.ts
  • apps/studio/router.tsx
  • apps/studio/routes/__root.tsx
  • apps/studio/routes/index.tsx
  • apps/studio/scripts/serve.js
  • apps/studio/security-headers.ts
  • apps/studio/static-data/integrations/overviews.test.ts
  • apps/studio/static-data/integrations/overviews.ts
  • apps/studio/styles/fonts.css
  • apps/studio/types/markdown.d.ts
  • apps/studio/vite.config.ts
  • e2e/studio/features/monaco-graphiql-coexistence.spec.ts
✅ Files skipped from review due to trivial changes (2)
  • apps/studio/types/markdown.d.ts
  • apps/studio/TANSTACK_MIGRATION.md
🚧 Files skipped from review as they are similar to previous changes (14)
  • apps/studio/router.tsx
  • apps/studio/security-headers.ts
  • apps/studio/routes/index.tsx
  • apps/studio/hooks/branches/useEdgeFunctionsDiff.ts
  • apps/studio/styles/fonts.css
  • apps/studio/lib/router-search-params.ts
  • apps/studio/redirects.shared.test.ts
  • apps/studio/compat/next/router.test.ts
  • apps/studio/scripts/serve.js
  • apps/studio/routes/__root.tsx
  • apps/studio/redirects.shared.ts
  • apps/studio/lib/router-search-params.test.ts
  • apps/studio/compat/next/router.ts
  • apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx

Comment thread apps/studio/lib/internal-url.ts Resolved

@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.

Tested changes locally, verified manually

  • Fonts loading
  • Monaco loading
  • GraphiQL loading + typings
  • Integrations markdown
  • Edge Function typings
  • Branching merge page crash

The other fixes, just checked through the code changes which generally look alright to me

Issues found

  • SQL editor content query param -> doesn’t populate the editor content
    • e.g Navigating to /project/_/sql/new?skip=true&content=select (Might be from the router stuff?)

Approving nonetheless 🙂 🙏

The TanStack __root.tsx hardcoded the prod favicon route, so local and
hosted staging showed the prod icon. pages/_app.tsx passes /favicon/staging
to MetaFaviconsPagesRouter for non-prod (per Joshen's review) — mirror that
with the same synchronous NEXT_PUBLIC_ENVIRONMENT signal already used by
IS_DEV_TOOLBAR_ENABLED (the head() route option can't run _app's async CLI
check, but the env signal covers the reported local/staging case).

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.

🧹 Nitpick comments (1)
apps/studio/routes/__root.tsx (1)

138-147: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Duplicate non-prod condition with IS_DEV_TOOLBAR_ENABLED.

FAVICON_ROUTE's ternary repeats the exact same NEXT_PUBLIC_ENVIRONMENT === 'local' || 'staging' check already computed for IS_DEV_TOOLBAR_ENABLED (Lines 110-112). Consider extracting a shared IS_NON_PROD_ENV constant to avoid the two checks drifting independently later.

♻️ Proposed refactor
+const IS_NON_PROD_ENV =
+  process.env.NEXT_PUBLIC_ENVIRONMENT === 'local' ||
+  process.env.NEXT_PUBLIC_ENVIRONMENT === 'staging'
+
 // Keep dev-only components out of the production bundle.
-const IS_DEV_TOOLBAR_ENABLED =
-  process.env.NEXT_PUBLIC_ENVIRONMENT === 'local' ||
-  process.env.NEXT_PUBLIC_ENVIRONMENT === 'staging'
+const IS_DEV_TOOLBAR_ENABLED = IS_NON_PROD_ENV
...
-const FAVICON_ROUTE =
-  process.env.NEXT_PUBLIC_ENVIRONMENT === 'local' ||
-  process.env.NEXT_PUBLIC_ENVIRONMENT === 'staging'
-    ? '/favicon/staging'
-    : '/favicon'
+const FAVICON_ROUTE = IS_NON_PROD_ENV ? '/favicon/staging' : '/favicon'
🤖 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/routes/__root.tsx` around lines 138 - 147, `FAVICON_ROUTE`
repeats the same non-prod environment check already used for
`IS_DEV_TOOLBAR_ENABLED`, so extract a shared `IS_NON_PROD_ENV` constant and use
it in both places. Update the root route module so the environment logic is
defined once near the existing `NEXT_PUBLIC_ENVIRONMENT` checks, then reference
that constant in the `FAVICON_ROUTE` ternary to keep the non-prod behavior
consistent and avoid future drift.
🤖 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.

Nitpick comments:
In `@apps/studio/routes/__root.tsx`:
- Around line 138-147: `FAVICON_ROUTE` repeats the same non-prod environment
check already used for `IS_DEV_TOOLBAR_ENABLED`, so extract a shared
`IS_NON_PROD_ENV` constant and use it in both places. Update the root route
module so the environment logic is defined once near the existing
`NEXT_PUBLIC_ENVIRONMENT` checks, then reference that constant in the
`FAVICON_ROUTE` ternary to keep the non-prod behavior consistent and avoid
future drift.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c22a768f-f1fc-4c46-8c24-66ef0f3392ad

📥 Commits

Reviewing files that changed from the base of the PR and between 120f2c3 and a8f7842.

📒 Files selected for processing (1)
  • apps/studio/routes/__root.tsx

- splitInternalUrl: compare against the parse base's origin unconditionally
  (not gated on window) so SSR no longer treats external absolute URLs like
  https://supabase.com/docs as internal paths; client behavior unchanged.
- internal-url.test.ts: add SSR-mode cases (window stubbed undefined) —
  external absolute URL passes through untouched, relative path still splits.
- __root.tsx: extract shared IS_NON_PROD_ENV const used by both
  IS_DEV_TOOLBAR_ENABLED and FAVICON_ROUTE (behavior identical).

Claude-Session: https://claude.ai/code/session_01MLH8WVg8zBJnmZTYTV3ooo
alaister added a commit that referenced this pull request Jul 8, 2026
… and migrations query 400s (#47667)

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.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## 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.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->


---

### 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.

---------

Co-authored-by: Alaister Young <[email protected]>
Co-authored-by: Joshen Lim <[email protected]>
Co-authored-by: Saxon Fletcher <[email protected]>
@alaister
alaister merged commit 18431ef into master Jul 8, 2026
34 checks passed
@alaister
alaister deleted the alaister/tanstack-migration-fixes branch July 8, 2026 06:53
@github-actions

github-actions Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (master-1783493738)

Score Average Improvements Regressions
Knowledge Usage 100% (+3pp) 1 🟢 -
SQL Identifier Quoting 100% (+0pp) - -
SQL Validity 100% (+0pp) - -
Tool Usage 74.5% (-2pp) - 1 🔴
Time_to_first_token 2.83tok (-0.18tok) 15 🟢 14 🔴
Llm_calls 3.05 (+0.26) 15 🟢 7 🔴
Tool_calls 3.03 (-0.05) 11 🟢 11 🔴
Errors 5.23 (-0.05) 5 🟢 3 🔴
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 22106.26tok (-970.23tok) 14 🟢 11 🔴
Prompt_cached_tokens 7444.6tok (+547.31tok) 14 🟢 10 🔴
Prompt_cache_creation_tokens 0tok (+0tok) - -
Prompt_cache_creation_5m_tokens 0tok (+0tok) - -
Prompt_cache_creation_1h_tokens 0tok (+0tok) - -
Completion_tokens 625.99tok (-26.41tok) 12 🟢 17 🔴
Completion_reasoning_tokens 103.71tok (-1.97tok) 11 🟢 14 🔴
Total_tokens 22732.25tok (-996.64tok) 16 🟢 13 🔴
Estimated_cost 0$ (0$) 17 🟢 8 🔴
Duration 16.14s (-0.59s) 11 🟢 18 🔴
Llm_duration 11.53s (+0.98s) 10 🟢 19 🔴

alaister added a commit that referenced this pull request Jul 9, 2026
…ilent no-ops) (#47666)

Stacked on #47657 (base is `alaister/tanstack-migration-fixes`; retarget
to `master` once that merges).

The TanStack runtime never ran `Sentry.init` —
`instrumentation-client.ts` is a Next-convention file nothing imports
under TanStack Start, so every `Sentry.captureException` on that build
(including the `routes/__root.tsx` error-boundary /
`routerErrorComponent` reports) was a silent no-op.

- **Shared config source**: the entire client config moves verbatim from
`instrumentation-client.ts` into `lib/sentry-client-options.ts`
(`buildSentryClientOptions`). Both runtimes build from it, so Next and
TanStack can't drift — the builds differ only in two explicit knobs.
- **TanStack init**: `sentry.tanstack.ts` initializes `@sentry/react`
from `getRouter()` (TanStack Start's real client bootstrap — the
earliest point with the router instance), wiring
`tanstackRouterBrowserTracingIntegration(router)`. Window-guarded +
idempotent; `router.tsx` is TanStack-only so the Next build is
untouched. (Named without `.client.` — Start's import-protection fails
the build for `*.client.*` in the server graph.)
- **Third-party error filter is intentionally Next-only**: without the
bundler-injected `applicationKey` metadata (only `withSentryConfig`
provides it), the SDK tags *every* event `third_party_code: true` and
`beforeSend` would drop them all — recreating the silent no-op with a
DSN set. Follow-up: add `@sentry/vite-plugin` moduleMetadata, then
enable.
- **DSN-less builds stay crash-free**: `vite.config.ts` inlines
`undefined` for unset
`NEXT_PUBLIC_SENTRY_DSN`/`NEXT_PUBLIC_SENTRY_ENVIRONMENT` (a literal
`process.env.*` in the bundle is the exact `process is not defined`
class #47657 fixed). No-DSN → disabled client, plus the existing
`IS_PLATFORM`/consent gates.
- Tests: `instrumentation-client.test.ts` moved to
`lib/sentry-client-options.test.ts` with all 36 assertions kept, plus
integration-gating and Next/TanStack parity tests. `tsc` clean; full
`vite build --mode test` passes.

Follow-up (separate): server-side Sentry for the Start handler
(`server.ts` entry + `@sentry/node`-style init).

## To test

- **Locally (no DSN set)**: load the TanStack build — no Sentry network
requests, no console errors, and crucially no `ReferenceError: process
is not defined` (the define fallback). Forcing an error must not POST to
any `/envelope` endpoint.
- **On a preview/deploy (DSN set, telemetry consent accepted)**: throw a
test error (e.g. crash a route component) → a POST to
`o…ingest.sentry.io/api/…/envelope/` fires, and the event lands in
Sentry with a `codeSampleRate` tag and **no** `third_party_code` tag.
Navigation spans named after TanStack routes appear when the 2% pageload
trace samples in.
- **Next build regression check**: the Next dev/preview still reports
errors exactly as before (`instrumentation-client.ts` now builds its
options from the same shared source).



---

### Review feedback: Sentry `/envelope` never fires on TanStack (Joshen)

Root-caused: `@sentry/core`'s `Client.sendSession` silently drops the
session when the client has no `release`. The Next build gets a release
injected by `withSentryConfig` (the Vercel commit SHA); the Vite build
runs no Sentry bundler plugin, so it had no release → session envelopes
were discarded before transport → zero `/envelope` traffic
(errors/transactions are separate). Fix: inject `release:
NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA` on the TanStack build (vite.config
re-exposes `VERCEL_GIT_COMMIT_SHA` under the `NEXT_PUBLIC_` name, same
SHA the Next release resolves to). Also switched `integrations` to the
function form so defaults are preserved by contract (not just by current
SDK behavior). 45 unit tests green.

**To test (deploys only — the SHA is unset locally, so this can't be
reproduced on a local dev build):** on this PR's Vercel preview with a
DSN + telemetry consent, load any page and watch the Network tab for a
POST to `…ingest.sentry.io/…/envelope/` — a session envelope should now
fire on load, matching the Next build.


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

## Summary by CodeRabbit

* **New Features**
* Improved client-side error and performance monitoring for the Studio
app across both router setups.
* Added support for passing release/version information into monitoring
data.

* **Bug Fixes**
* Reduced noisy error reporting by better filtering common browser,
extension, cancellation, and load-related issues.
* Prevented browser bundles from referencing missing environment values
at runtime.
* Made monitoring initialization safer in server-rendered and
client-only environments.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Alaister Young <[email protected]>
alaister added a commit that referenced this pull request Jul 10, 2026
) (#47119)

**Stack 6/6 (final)** of the TanStack Start migration (#46424). The
middle slices (#47107 → #47118) have all merged, so this now sits
directly on master.

## What's in this PR

One file: `.github/workflows/studio-e2e-test.yml` — adds `framework:
[next, tanstack]` to the test/report matrices and sets
`STUDIO_FRAMEWORK` (consumed by `scripts/dispatch.js`). Until now CI
only built/tested Next. This flips on the dual-framework E2E matrix so
the TanStack build gets exercised end-to-end on every run.

## ⚠️ Depends on #47657 (merge that first)

The `tanstack` shard needs the Monaco loader fix in **#47657** to be on
master. Quick version: master's #47182 re-nested the Monaco assets under
`public/monaco-editor/vs/` and the TanStack root was still pointing at
the old flat path, so Monaco didn't mount anywhere in the TanStack build
and every editor-backed test timed out (RLS, cron SQL, realtime JSON, db
functions, GraphiQL). Kept that fix on its own branch rather than piling
it onto this one.

Merge order:
1. #47657 → master
2. re-merge master into here (I'll cascade it)
3. `tanstack` shard goes green → merge this

## ⚠️ Branch-protection note

This renames the E2E jobs (`E2E tests` → `E2E tests (next|tanstack,
shard)`), so master's current required status checks (`E2E tests (1, 2)`
/ `(2, 2)`) stop being reported. The required-check list in branch
protection needs updating to the new names when this merges.

## Verification

Config-only, no app code. The real validation is this matrix running
both shards green once #47657 lands — the `next` shards already pass
here; the `tanstack` shards pass once the Monaco fix is on master.

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

* **New Features**
* Integration overview markdown can now be loaded more reliably from a
synchronized on-disk registry (raw markdown support).

* **Bug Fixes**
* Navigation, redirects, and prefetch now preserve query strings and
hash fragments more consistently using Next-like semantics (including
repeated keys, empty clearing, and lossless encoding like newlines).
* Improved internal-link/router compatibility for Next-style `?`/`#`
targets and base-path handling.
* Edge Functions diff tab matching works correctly in the browser
without Node-specific path utilities.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Alaister Young <[email protected]>
Co-authored-by: Ivan Vasilov <[email protected]>
alaister added a commit that referenced this pull request Jul 10, 2026
… @sentry/nextjs compat alias

The stub's only real-world importer was @sentry/nextjs's isBuild.js, which
the @sentry/nextjs -> compat/sentry-nextjs.ts alias (already on master via
#47657) removes from the browser graph entirely. Dropping it brings this
branch to a zero diff against master.
@alaister alaister mentioned this pull request Jul 10, 2026
6 tasks
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