Skip to content

feat(studio): logs snippets in SQL editor nav, search, and tabs - #48457

Merged
charislam merged 2 commits into
masterfrom
charislam/nav-logs-section-search-tabs
Aug 4, 2026
Merged

charislam merged 2 commits into
masterfrom
charislam/nav-logs-section-search-tabs

Conversation

@charislam

@charislam charislam commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

What

PR 7 of the SQL-editor query-source (Database vs Logs) stack. Surfaces log_sql snippets as a distinct query source across the SQL editor sidebar. Stacked on charislam/toolbar-ui-creation-flow (PR 6 — toolbar UI + creation flow); review/merge that first.

Nothing is user-visible until the flags roll out — every entry point requires both sqlEditorLogsSource and otelLegacyLogs.

Changes

  • Nav — a flag-gated Logs section (LogsSnippetsSection) backed by its own single-type log_sql query. The active snippet is injected only into the section it belongs to, via a shared withActiveSnippet(snippets, active, belongsPredicate) helper (also DRYs the private/favorites/shared injections).
  • Search (SearchList) — a Logs result group with a shared, extracted SqlSnippetTree; the "N results found" count now sums database + logs, with loading/empty states covering both queries.
  • Tabs — an immutable sqlSource field on tab/recent-item metadata (set at tab creation, lazily backfilled once the snippet loads via useEffectEvent), and a distinct ScrollText icon via a shared LogsSnippetIcon. Tab cleanup treats log_sql tabs as live and only prunes them when logs data is authoritative (canPruneLogsTabs), so a disabled/erroring logs query never wrongly deletes logs tabs or blocks database-tab cleanup.
  • Data layer — useSqlSnippetsQuery gains an optional type param so logs reuse the same SnippetWithContent shape as the other sections (no casts).

Tests

  • state/tabs.test.ts — sqlSource backfill + creation-time carry-through.
  • components/layouts/Tabs/Tabs.utils.test.tsx — cleanup prunes stale database/logs snippets, keeps live ones, and preserves logs tabs when logs data isn't authoritative.

Verification

  • pnpm --filter studio typecheck ✓
  • pnpm --filter studio run lint:ratchet ✓
  • pnpm test:studio (affected suites) ✓

Summary by CodeRabbit

  • New Features
    • Added a collapsible Logs section to the SQL editor sidebar for browsing, sorting, selecting, renaming, and deleting log queries.
    • Expanded SQL search with separate, paginated results for database and log queries.
    • Added dedicated log-query icons across navigation, tabs, previews, and recent items.
  • Bug Fixes
    • Improved tab and recent-item cleanup while preserving active log queries and accurate source metadata.
  • Tests
    • Added coverage for log tab cleanup and SQL source metadata synchronization.

@charislam
charislam requested a review from a team as a code owner July 29, 2026 19:57
@vercel

vercel Bot commented Jul 29, 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 Aug 4, 2026 12:44pm
docs Ready Ready Preview, v0 Aug 4, 2026 12:44pm
studio-self-hosted Ready Ready Preview Aug 4, 2026 12:44pm
studio-staging Ready Ready Preview Aug 4, 2026 12:44pm
ui-library Ready Ready Preview Aug 4, 2026 12:44pm
zone-www-dot-com Ready Ready Preview, v0 Aug 4, 2026 12:44pm
1 Skipped Deployment
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Aug 4, 2026 12:44pm

Request Review

@supabase

supabase Bot commented Jul 29, 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 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds log_sql snippet querying, a feature-gated Logs sidebar and search group, reusable snippet-tree rendering, source-aware icons and tab metadata, and conditional cleanup for logs tabs and recent items.

Changes

SQL logs navigation

Layer / File(s) Summary
Logs query and sidebar integration
apps/studio/data/content/*, apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/*
Adds typed log_sql queries, a collapsible Logs section, feature gating, pagination, active-snippet handling, and cleanup coordination.
Search and reusable snippet trees
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx, SqlSnippetTree.tsx
Separates database and logs search results and renders both with reusable SQL snippet trees.
Logs identity and tab metadata
apps/studio/components/ui/EntityTypeIcon.tsx, apps/studio/components/layouts/Tabs/*, apps/studio/state/tabs.*, apps/studio/pages/project/[ref]/sql/[id].tsx
Adds logs-specific icons and stores or backfills SQL snippet source metadata on tabs and recent items.
Conditional logs tab cleanup
apps/studio/components/layouts/Tabs/Tabs.utils.ts, apps/studio/components/layouts/Tabs/Tabs.utils.test.tsx
Recognizes log_sql snippets and conditionally preserves or prunes logs tabs and recent items, with tests.

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

Possibly related PRs

Suggested labels: frontend

Suggested reviewers: awaseem

Sequence Diagram(s)

sequenceDiagram
  participant SQLPage
  participant TabsState
  participant SQLEditorNav
  participant LogsSnippetsSection
  participant ContentAPI
  SQLPage->>TabsState: create or backfill sqlSource
  SQLEditorNav->>LogsSnippetsSection: render gated Logs section
  LogsSnippetsSection->>ContentAPI: fetch log_sql snippets
  ContentAPI-->>LogsSnippetsSection: return paginated snippets
  LogsSnippetsSection-->>SQLEditorNav: report loaded snippets
  SQLEditorNav->>TabsState: cleanup stale tabs with logs pruning guard
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding logs snippets to the SQL editor navigation, search, and tabs.
Description check ✅ Passed The description provides detailed behavior changes, implementation context, tests, verification results, and rollout requirements.
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 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch charislam/nav-logs-section-search-tabs

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.

@charislam

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@github-actions

github-actions Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results (next)

passed  240 passed
flaky  3 flaky
skipped  5 skipped

Details

stats  248 tests across 29 suites
duration  7 minutes, 29 seconds
commit  facb525

Flaky tests

Features › realtime-inspector.spec.ts › Realtime Inspector › Basic Inspector UI › can join and leave a channel
Features › realtime-inspector.spec.ts › Realtime Inspector › Basic Inspector UI › start/stop listening button works
Features › realtime-inspector.spec.ts › Realtime Inspector › Broadcast Messages › broadcast messages appear in the UI when listening

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.

Actionable comments posted: 3

🧹 Nitpick comments (2)
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx (1)

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

Flatten the nested count-state ternary.

Render the loading and loaded count states with mutually exclusive && guards.

As per coding guidelines, “never nest ternaries” and “render fetch states with top-level early returns or a flat chain of mutually exclusive && guards.”

Proposed change
-        {isLoadingCounts ? (
+        {isLoadingCounts && (
           <div className="px-4 py-1 pb-2.5">
             <Loader2 className="animate-spin" size={14} />
           </div>
-        ) : hasCounts ? (
+        )}
+        {!isLoadingCounts && hasCounts && (
           <p className="px-4 pb-2 text-sm text-foreground-lighter">
             {totalNumber} result{totalNumber === 1 ? '' : 's'} found
           </p>
-        ) : null}
+        )}
🤖 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/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx`
around lines 110 - 118, Update the count-state rendering in SearchList to remove
the nested ternary. Use mutually exclusive && guards so the loading indicator
renders when isLoadingCounts is true, and the result count renders only when
loading is false and hasCounts is true; preserve the existing content and
styling.

Source: Coding guidelines

apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SqlSnippetTree.tsx (1)

60-65: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Type the tree metadata instead of casting it.

The new shared component relies on as Snippet and additional string casts. Make TreeViewItemProps/the tree component preserve Snippet metadata so invalid nodes fail at compile time.

As per coding guidelines, “Avoid TypeScript as casts.”

Also applies to: 74-94

🤖 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/layouts/SQLEditorLayout/SQLEditorNavV2/SqlSnippetTree.tsx`
around lines 60 - 65, Update the tree component and its TreeViewItemProps typing
so metadata is parameterized as Snippet throughout, including the nodeRenderer
callback, instead of using `as Snippet` or string casts. Ensure the shared tree
preserves this metadata type and rejects incompatible nodes at compile time
while keeping the existing snippet navigation behavior unchanged.

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.

Inline comments:
In
`@apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx`:
- Around line 60-105: Prevent stale placeholder results from being rendered as
current search results in the SearchList query flow. Track isPlaceholderData
from both useSqlSnippetsQuery calls and both useContentCountQuery calls, then
treat those values as loading and exclude their data from displayed trees,
counts, and totals until the active search queries resolve; alternatively remove
keepPreviousData for these searches while preserving the existing enabled
behavior.

In
`@apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx`:
- Around line 75-83: Update the auto-expansion effect in SQLEditorNav to check
getSnippetSource(snippet) before the visibility-based branching, and set the
logs section visibility to true for an active log_sql snippet. Preserve the
existing visibility behavior for all other snippet sources.
- Around line 485-492: The logs-tab cleanup in SQLEditorNav must wait until the
logs infinite query has fetched every page before allowing pruning. Update the
condition or canPruneLogsTabs value around logsSnippetsInView and its
hasNextPage/loading state so sqlEditorTabsCleanup receives canPruneLogsTabs only
when no pages remain unfetched; preserve cleanup for non-logs tabs and the
existing failure handling.

---

Nitpick comments:
In
`@apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx`:
- Around line 110-118: Update the count-state rendering in SearchList to remove
the nested ternary. Use mutually exclusive && guards so the loading indicator
renders when isLoadingCounts is true, and the result count renders only when
loading is false and hasCounts is true; preserve the existing content and
styling.

In
`@apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SqlSnippetTree.tsx`:
- Around line 60-65: Update the tree component and its TreeViewItemProps typing
so metadata is parameterized as Snippet throughout, including the nodeRenderer
callback, instead of using `as Snippet` or string casts. Ensure the shared tree
preserves this metadata type and rejects incompatible nodes at compile time
while keeping the existing snippet navigation behavior unchanged.
🪄 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 Plus

Run ID: 1790d9e4-8645-43dc-b91f-1b2923eddaed

📥 Commits

Reviewing files that changed from the base of the PR and between b0d51ac and 3ae7d7a.

📒 Files selected for processing (18)
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/LogsSnippetsSection.tsx
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.constants.ts
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.utils.ts
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SqlSnippetTree.tsx
  • apps/studio/components/layouts/Tabs/RecentItems.tsx
  • apps/studio/components/layouts/Tabs/SortableTab.tsx
  • apps/studio/components/layouts/Tabs/TabPreview.tsx
  • apps/studio/components/layouts/Tabs/Tabs.utils.test.tsx
  • apps/studio/components/layouts/Tabs/Tabs.utils.ts
  • apps/studio/components/ui/EntityTypeIcon.tsx
  • apps/studio/data/content/keys.ts
  • apps/studio/data/content/sql-snippets-query.ts
  • apps/studio/pages/project/[ref]/sql/[id].tsx
  • apps/studio/state/tabs.test.ts
  • apps/studio/state/tabs.tsx

Base automatically changed from charislam/toolbar-ui-creation-flow to master July 30, 2026 12:38
@charislam
charislam force-pushed the charislam/nav-logs-section-search-tabs branch from 3ae7d7a to bb92c9b Compare July 30, 2026 18:08

@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: 3

Caution

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

⚠️ Outside diff range comments (1)
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx (1)

430-445: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Active logs snippet never opens the Logs section.

This effect only checks snippet.visibility ('project'/'user') to auto-open Shared/Private. A log_sql active snippet has visibility: 'user', so it will flip private: true instead of logs: true, leaving the Logs section collapsed even though the snippet is force-injected into it via activeSnippet. Check getSnippetSource(snippet) === 'logs' first.

This was flagged in a prior review on this same effect and doesn't appear to have been addressed yet.

🐛 Proposed fix
   useEffect(() => {
     if (snippet !== undefined && isSuccess) {
-      if (snippet.visibility === 'project') {
+      if (getSnippetSource(snippet) === 'logs') {
+        setSectionVisibility({ ...sectionVisibility, logs: true })
+      } else if (snippet.visibility === 'project') {
         setSectionVisibility({ ...sectionVisibility, shared: true })
       } else if (snippet.visibility === 'user') {
         setSectionVisibility({ ...sectionVisibility, private: true })
       }
🤖 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/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx`
around lines 430 - 445, Update the visibility handling in the useEffect around
getSnippetSource so snippets whose source is 'logs' set the logs section open
before checking snippet.visibility. Keep the existing shared/private behavior
for non-logs snippets, while preserving the folder expansion logic.
♻️ Duplicate comments (1)
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx (1)

60-96: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Stale search results/counts can render without a loading indicator.

None of the four queries here (sql results, sql count, log_sql count, log_sql results) destructure isPlaceholderData, even though all use placeholderData: keepPreviousData. isPending/isSearchLoading/isLoadingCounts stay false once any previous-search data exists, so when search changes, the UI keeps showing the previous search's results and "N results found" count as if they were current, then swaps abruptly once the new data resolves.

This reproduces a past review finding on this file that was marked addressed on an earlier commit — it looks like the addressed fix didn't carry over through the refactor that split this into separate sql/log_sql queries.

🤖 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/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx`
around lines 60 - 96, Update all four queries in the SearchList query block to
destructure isPlaceholderData and incorporate it into the loading-state
calculations. Ensure stale placeholder results and counts are treated as loading
after search changes, including the combined isSearchLoading, isLoadingCounts,
and log-section loading paths, so previous-search data is not presented as
current.
🧹 Nitpick comments (1)
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx (1)

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

Logs feature-flag gating duplicated across two files. The identical sqlEditorLogsSource && otelLegacyLogs combination is computed independently in both files; extracting a shared hook keeps them from drifting if the gating logic changes.

  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx#L78-L84: replace with a shared useCanShowLogsSection() hook (e.g. placed alongside SQLEditorNav.utils.ts).
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx#L54-L56: consume the same shared hook instead of re-deriving the flags.
🤖 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/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx`
around lines 78 - 84, Extract the duplicated logs feature-flag gating into a
shared useCanShowLogsSection hook. In
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx
lines 78-84, replace the local flag combination with the hook; in
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx
lines 54-56, consume the same hook instead of re-deriving sqlEditorLogsSource
and otelLegacyLogs.
🤖 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/layouts/SQLEditorLayout/SQLEditorNavV2/LogsSnippetsSection.tsx`:
- Around line 88-91: Prevent log-tab pruning until every logs page has been
fetched: update LogsSnippetsSection.tsx lines 88-91 to include hasNextPage or an
equivalent fully-loaded flag in the onSnippetsLoaded payload, then update
SQLEditorNav.tsx lines 485-501 to set canPruneLogsTabs only when the query is
successful and hasNextPage is false.

In
`@apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx`:
- Around line 110-118: Replace the nested ternary in the fetch-state rendering
around isLoadingCounts and hasCounts with mutually exclusive flat conditional
rendering: show the loader when isLoadingCounts is true, show the result count
only when loading is false and hasCounts is true, and render nothing otherwise.
Preserve the existing Loader2 and totalNumber display behavior.

In `@apps/studio/components/layouts/Tabs/Tabs.utils.test.tsx`:
- Around line 60-72: Extend the test case around cleanup({ snippets: [],
canPruneLogsTabs: false }) to assert recent-item behavior as well as open tabs:
verify the logs entry sql-logs remains in recent items and the stale database
entry sql-db-stale is removed. Use the store’s existing recent-items state or
accessor created by addTab, without changing the cleanup setup.

---

Outside diff comments:
In
`@apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx`:
- Around line 430-445: Update the visibility handling in the useEffect around
getSnippetSource so snippets whose source is 'logs' set the logs section open
before checking snippet.visibility. Keep the existing shared/private behavior
for non-logs snippets, while preserving the folder expansion logic.

---

Duplicate comments:
In
`@apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx`:
- Around line 60-96: Update all four queries in the SearchList query block to
destructure isPlaceholderData and incorporate it into the loading-state
calculations. Ensure stale placeholder results and counts are treated as loading
after search changes, including the combined isSearchLoading, isLoadingCounts,
and log-section loading paths, so previous-search data is not presented as
current.

---

Nitpick comments:
In
`@apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx`:
- Around line 78-84: Extract the duplicated logs feature-flag gating into a
shared useCanShowLogsSection hook. In
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx
lines 78-84, replace the local flag combination with the hook; in
apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx
lines 54-56, consume the same hook instead of re-deriving sqlEditorLogsSource
and otelLegacyLogs.
🪄 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 Plus

Run ID: bf9558ee-b797-4282-8eab-5e337676cc9a

📥 Commits

Reviewing files that changed from the base of the PR and between 3ae7d7a and bb92c9b.

📒 Files selected for processing (16)
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/LogsSnippetsSection.tsx
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.constants.ts
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.utils.ts
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SqlSnippetTree.tsx
  • apps/studio/components/layouts/Tabs/RecentItems.tsx
  • apps/studio/components/layouts/Tabs/SortableTab.tsx
  • apps/studio/components/layouts/Tabs/TabPreview.tsx
  • apps/studio/components/layouts/Tabs/Tabs.utils.test.tsx
  • apps/studio/components/layouts/Tabs/Tabs.utils.ts
  • apps/studio/components/ui/EntityTypeIcon.tsx
  • apps/studio/data/content/keys.ts
  • apps/studio/data/content/sql-snippets-query.ts
  • apps/studio/pages/project/[ref]/sql/[id].tsx
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/studio/components/layouts/Tabs/TabPreview.tsx
  • apps/studio/components/layouts/Tabs/SortableTab.tsx
  • apps/studio/data/content/keys.ts

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

Preview test — ✅ all pass

This PR didn't have an explicit "To test" section, so I inferred the checklist from the summary + diff (dual-flag-gated logs snippets support in the SQL editor nav, search, and tabs) and ran through it on the studio-staging preview, toggling sqlEditorLogsSource + otelLegacyLogs via the dev-toolbar flag-override cookie (both flags are off by default, so none of this is visible without it).

# Test Result
1 Baseline, flags off — no Logs section in nav ✅ nav shows only Private/Shared/Favorites/Reference
2 Flags on — Logs section appears ✅ collapsible "Logs" section shows up, empty state: "No logs queries" / "Create a logs query from the toolbar to explore your project's logs with SQL."
3 Create a logs snippet (/sql/new?skip=true&source=logs, type to materialize) ✅ saves as log_sql on first keystroke (URL flips from /sql/new to /sql/<uuid>) — see note on a console warning here
4 Nav reflects the new snippet ✅ section label bumps to "Logs (1)", snippet renders with the ScrollText icon, distinct from the normal SQL icon
5 Search — logs-only match ✅ "1 result found", flat list, no group heading (correct — only one group matched)
6 Search — mixed DB + Logs match ✅ "2 results found", "Database" and "Logs" headings both appear with the right snippet under each
7 Tabs — logs tab icon ✅ active logs tab shows the ScrollText icon
8 Tabs — DB tab regression ✅ normal DB tab keeps its usual SQL icon, no bleed-over
9 Tab persistence across reload ✅ both tabs survive a full reload, nothing pruned
10 Flags off again — regression ✅ Logs section disappears, toolbar reverts to the old source toggle, search drops the logs snippet, previously-open tabs stay open
11 Console errors throughout ✅ no JS errors across the whole run

Notes:

  • Worth a look: right when the logs snippet is first materialized (step 3), the console logs a "Tabs is changing from controlled to uncontrolled" warning immediately followed by the reverse "...uncontrolled to controlled", from the tabs component, during the new → real-snippet-id transition. Nothing visibly broke, but it smells like the Tabs value passes through undefined momentarily and might be worth a quick look.
  • Created one throwaway log_sql snippet and one throwaway DB snippet to get real search-grouping coverage (steps 5/6); both deleted afterward via the nav's delete action. No pre-existing projects, orgs, or snippets touched.
  • Didn't touch the actual logs SQL execution path (running a query against ClickHouse) — that's PR #48452/#48414 territory, out of scope here.
  • No screenshots — everything was verifiable via DOM/class checks with nothing visually broken.

@joshenlim

joshenlim commented Jul 31, 2026 •

Copy link
Copy Markdown
Member

UI issues found

Caught some stuff that weren't covered by the automated review

  • Minor UI nit found in the search results - shouldn't say "Private" here -> should say "Logs" (Or maybe just remove the description since the icon communicates that its a logs snippet)
    image
  • If the "Private" section is collapsed, opening a log snippet in the Logs section opens the "Private" section
    • There's a lot of other actions that seem to do this too e.g renaming the logs snippet
    • CodeRabbit caught this here
  • (Not sure if within scope) Favouriting a logs snippet doesn't show up within the "Favourites" section
    image
  • This CodeRabbit comment seems worth checking too - seems valid

@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/layouts/SQLEditorLayout/SQLEditorNavV2/LogsSnippetsSection.tsx`:
- Around line 33-42: Update the useSqlSnippetsQuery result handling in
LogsSnippetsSection to destructure isPlaceholderData and prevent placeholder
results from being reported as complete. Require !isPlaceholderData when
calculating isComplete, and apply the same guard to isSettled so the parent only
treats current-query data as settled.
🪄 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 Plus

Run ID: 97000b5e-c84a-4cd6-8759-45f4cb84ce73

📥 Commits

Reviewing files that changed from the base of the PR and between bb92c9b and 91fd667.

📒 Files selected for processing (5)
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/LogsSnippetsSection.tsx
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SqlSnippetTree.tsx
  • apps/studio/components/layouts/Tabs/Tabs.utils.test.tsx
🚧 Files skipped from review as they are similar to previous changes (4)
  • apps/studio/components/layouts/Tabs/Tabs.utils.test.tsx
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SqlSnippetTree.tsx
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx
  • apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx

Comment on lines +33 to +42
onSnippetsLoaded: (info: {
snippets: Snippet[]
/**
* Whether `snippets` is the complete set of logs snippets. Only true once every
* page has been fetched — cleanup prunes tabs whose snippet is absent from the
* list, and a snippet on an unfetched page would otherwise look deleted.
*/
isComplete: boolean
isSettled: boolean
}) => void

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

rg -n -C 8 \
  'useSqlSnippetsQuery|placeholderData|keepPreviousData|isPlaceholderData|canPruneLogsTabs' \
  apps/studio/data/content/sql-snippets-query.ts \
  apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/LogsSnippetsSection.tsx \
  apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx

Repository: supabase/supabase

Length of output: 24328


Do not report placeholder data as a complete logs set.

useSqlSnippetsQuery uses placeholderData: keepPreviousData. After a query-key change, the previous pages can remain visible while isSuccess is already true, and !hasNextPage can report isComplete: true before the current query finishes. The parent cleanup can compare tabs against that stale snapshot and prune a valid logs tab. Destructure isPlaceholderData and require a non-placeholder result before reporting isComplete; apply the same guard to isSettled if the parent treats it as current-query completion status.

🤖 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/layouts/SQLEditorLayout/SQLEditorNavV2/LogsSnippetsSection.tsx`
around lines 33 - 42, Update the useSqlSnippetsQuery result handling in
LogsSnippetsSection to destructure isPlaceholderData and prevent placeholder
results from being reported as complete. Require !isPlaceholderData when
calculating isComplete, and apply the same guard to isSettled so the parent only
treats current-query data as settled.

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

Changes LGTM! Verified on preview

Surface log_sql snippets as a distinct query source across the SQL editor
sidebar, following the toolbar/creation flow work:

- Nav: a flag-gated "Logs" section (LogsSnippetsSection) backed by its own
  log_sql query; the active snippet is injected only into the section it
  belongs to via a shared withActiveSnippet helper.
- Search: a "Logs" result group and correct combined result counts, with the
  tree rendering extracted into a reusable SqlSnippetTree.
- Tabs: an immutable sqlSource tab metadata field (backfilled once the snippet
  loads) and a distinct ScrollText icon via a shared LogsSnippetIcon; tab
  cleanup treats log_sql tabs as live and only prunes them when logs data is
  authoritative.
- Parameterize useSqlSnippetsQuery with a content type so logs reuse the same
  SnippetWithContent shape (no casts).

Both sqlEditorLogsSource and otelLegacyLogs flags gate the entry points.
- Open the Logs section, not Private, when the active snippet is a logs
  snippet. The auto-expansion effect branched on visibility first, so opening
  or renaming a log_sql snippet expanded a section it isn't in.
- Only prune logs tabs once every logs page has been fetched. useInfiniteQuery
  flips isSuccess after the first page, so a tab whose snippet lived on an
  unfetched page could be pruned as stale; the bubbled-up flag is now
  isComplete (isSuccess && !hasNextPage).
- Label logs search results "Logs" instead of "Private" — the visibility axis
  doesn't distinguish them from the database results beside them.
- Flatten the search result-count nested ternary into mutually exclusive
  guards, and assert recent-item preservation in the canPruneLogsTabs test.
@charislam
charislam force-pushed the charislam/nav-logs-section-search-tabs branch from 91fd667 to facb525 Compare August 4, 2026 12:36
@charislam
charislam merged commit b3c5c9f into master Aug 4, 2026
38 checks passed
@charislam
charislam deleted the charislam/nav-logs-section-search-tabs branch August 4, 2026 13:02
charislam added a commit that referenced this pull request Aug 4, 2026
…ckHouse (#48501)

## I have read the
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
file.

YES

## What kind of change does this PR introduce?

Feature, plus a refactor of the shared logs-rewrite flow.

PR 8 of the SQL editor query-source series. Stacked on #48457 — review
that one first, and merge this after it.

## What is the current behavior?

A `log_sql` snippet runs against the ClickHouse-backed analytics
endpoint, but the SQL editor's AI still writes Postgres: inline edits
get Postgres system prompts, and the result is run through
`sql-formatter`, which mangles ClickHouse backticks and `log_attributes`
map lookups.

Legacy Logs Explorer saved queries open in the editor as `log_sql`
snippets. Those are BigQuery dialect and error against the ClickHouse
endpoint the editor runs them on, with no in-editor way out — only the
Logs Explorer offered a rewrite.

The completion route was also asymmetric. It assembled a
schema/code/instruction message for Postgres but forwarded `prompt`
verbatim for ClickHouse, so a client wanting ClickHouse had to
hand-build the equivalent string.

## What is the new behavior?

**Inline AI speaks ClickHouse for logs snippets.** `sqlSourceToDialect`
maps a snippet's source to `postgres`/`clickhouse` and
`buildCompletionRequestBody` threads it through. For ClickHouse,
`useSqlEditorAi` strips code fences from the response and skips
`formatSql`. Execution and dialect both follow the snippet type, so a
snippet's valid dialect never flips.

**Rewrite to ClickHouse in the editor.** A banner offers the rewrite for
a logs snippet whose text trips `looksLikeLegacyLogsQuery`, and proposes
the result through the editor's existing AI diff view rather than
replacing the snippet, so it's accepted or discarded like any other AI
edit. Gated on `otelLegacyLogs`: on a non-migrated org the BigQuery text
is still correct, so rewriting it would break a working query.

The offer is a state machine (`offered` / `rewriting` / `failed` /
`noRewriteNeeded` / `dismissed`) with a declarative table of valid
transitions, so the states are mutually exclusive by construction and
dismissal is terminal. A failure keeps its message and offers a retry; a
response identical to the input is reported rather than opening an empty
diff.

**One place assembles completion prompts.** The route now uses a single
template for both dialects, branching only the schema section and — for
`intent: 'rewrite'` — the instruction. `lib/ai/clickhouse-logs.ts` is
the single home for ClickHouse-logs prompt content, replacing two
independently maintained descriptions of the same table. Clients carry
no prompt text.

**The rewrite flow is shared with the Logs Explorer.** Both surfaces
previously hand-rolled the same sequence and had drifted: only one
detected a no-op rewrite, they sourced `log_attributes` keys
differently, and the Explorer formatted errors with an `as Error` cast.
Both now use `useLegacyLogsRewrite` and the same state-driven banner, so
the Explorer picks up no-op detection and typed error extraction.

**Attribute keys are fetched on submit, not while typing.** The detected
source would otherwise feed a reactive query key, making every edit that
changed it cost another network call. `useLogsAttributeKeys` is
imperative and goes through `queryClient.fetchQuery`, so a source
already cached — including by the Explorer header and query panel, which
subscribe reactively — is reused. This also closes a gap where inline
edits never received keys at all, unlike full rewrites.

`getErrorMessage` gains an optional typed fallback and no longer
stringifies a bare object into `'[object Object]'`; every existing
caller already hand-rolled a fallback, except `QueueSettings`, which
interpolated the raw result and now passes one.

Nothing here is user-visible until the `sqlEditorLogsSource` flag is
enabled.

Tests: dialect selection and request-body shape, the ClickHouse prompt
content (including that the schema section does not restate the dialect
rules), the reducer's valid and invalid transitions,
`shouldOfferLegacyLogsRewrite`, on-submit key discovery with cache
reuse, and `getErrorMessage`.

## Additional context

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

## Summary by CodeRabbit

* **New Features**
* Added an Assistant banner to help rewrite legacy BigQuery-style logs
queries into ClickHouse SQL.
* SQL assistance now adapts to the selected query type, including
relevant log attribute context.
* Rewrite suggestions can be reviewed as editor diffs before being
applied.

* **Bug Fixes**
* Improved rewrite failure handling, retry options, dismissal behavior,
and “no rewrite needed” messaging.
* Error notifications now provide a clearer fallback message when
details are unavailable.

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

2 participants