Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feature: add explain with AI in query performance#41415

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
awaseem wants to merge6 commits intomaster
base:master
Choose a base branch
Loading
fromaliwaseem/fe-2282-query-performance-explained-in-ai

Conversation

@awaseem
Copy link
Contributor

@awaseemawaseem commentedDec 16, 2025
edited by coderabbitaibot
Loading

I have read theCONTRIBUTING.md file.

YES

What kind of change does this PR introduce?

Simple button to add context of query performance into the AI chat

Summary by CodeRabbit

  • New Features

    • Introduced AI-powered query explanation feature with a new button in query performance details
    • Launches AI assistant with full query context including execution metrics, timing data, and optimization information
    • Query detail panel automatically closes after requesting AI explanation
  • Chores

    • Added telemetry event tracking for AI explanation feature usage

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel
Copy link

vercelbot commentedDec 16, 2025
edited
Loading

The latest updates on your projects. Learn more aboutVercel for GitHub.

ProjectDeploymentReviewUpdated (UTC)
studio-self-hostedReadyReadyPreview,CommentDec 17, 2025 3:42pm
studio-stagingReadyReadyPreview,CommentDec 17, 2025 3:42pm
6 Skipped Deployments
ProjectDeploymentReviewUpdated (UTC)
studioIgnoredIgnoredDec 17, 2025 3:42pm
cmsSkippedSkippedDec 17, 2025 3:42pm
design-systemSkippedSkippedDec 17, 2025 3:42pm
docsSkippedSkippedDec 17, 2025 3:42pm
ui-librarySkippedSkippedDec 17, 2025 3:42pm
zone-www-dot-comSkippedSkippedDec 17, 2025 3:42pm

@coderabbitai
Copy link
Contributor

coderabbitaibot commentedDec 16, 2025
edited
Loading

Walkthrough

This change integrates AI-assisted query explanation into the QueryPerformance interface. Users can now click an "Explain with AI" button in the query detail panel, which constructs a comprehensive prompt from performance metrics, opens the AI assistant, and logs telemetry data.

Changes

Cohort / File(s)Summary
AI-assisted explanation feature
apps/studio/components/interfaces/QueryPerformance/QueryDetail.tsx,apps/studio/components/interfaces/QueryPerformance/QueryPerformance.ai.ts
Added handleExplainQuery handler and "Explain with AI" button with animation icon to QueryDetail. New QueryPerformance.ai module exports buildQueryExplanationPrompt function that constructs detailed AI prompts from query performance metadata, including metrics, index advisor recommendations, and cost analysis.
Component integration
apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx
Wired onClose callback to QueryDetail component to clear selection when detail view closes.
Telemetry tracking
packages/common/telemetry-constants.ts
Added QueryPerformanceAIExplanationClickedEvent interface to telemetry event union for tracking AI explanation interactions.

Sequence Diagram

sequenceDiagram    participant User    participant QueryDetail    participant AI as AI Module    participant Sidebar as AI Assistant Sidebar    participant Telemetry        User->>QueryDetail: Click "Explain with AI" button    activate QueryDetail    QueryDetail->>AI: buildQueryExplanationPrompt(selectedRow)    activate AI    AI->>AI: Extract metrics & metadata    AI->>AI: Append index advisor & cost data    AI->>AI: Construct detailed prompt    AI-->>QueryDetail: Return { query, prompt }    deactivate AI        QueryDetail->>Sidebar: Open AI Assistant    activate Sidebar    QueryDetail->>Sidebar: Start chat with SQL snippet    Sidebar-->>QueryDetail: Chat initialized    deactivate Sidebar        QueryDetail->>Telemetry: Send query_performance_ai_explanation_clicked    activate Telemetry    Telemetry-->>QueryDetail: Event logged    deactivate Telemetry        QueryDetail->>QueryDetail: Invoke onClose callback    QueryDetail-->>User: Close detail panel    deactivate QueryDetail
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • QueryDetail.tsx: Integration of multiple new hooks and state management; verify handleExplainQuery logic correctly wires AI flow and telemetry context.
  • QueryPerformance.ai.ts: Review prompt construction logic to ensure all metrics are correctly extracted and formatted; validate handling of optional index advisor and cost data.
  • Prop threading: Verify onClose callback is correctly passed through component hierarchy (QueryPerformanceGrid → QueryDetail) and properly invoked.

Possibly related PRs

Suggested reviewers

  • kemaldotearth

Poem

🐰 A query explained, with AI so keen,
Performance secrets now clearly seen!
From metrics bold to suggestions bright,
We hop through prompts with pure delight.
Click explain, watch the sidebar ignite! ✨

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check nameStatusExplanationResolution
Description check⚠️ WarningThe description is largely incomplete. While it confirms CONTRIBUTING.md was read and briefly describes the feature, it lacks detailed sections on current behavior, new behavior, and additional context as specified in the template.Expand the description to include: what is the current behavior and any linked issues; detailed explanation of new behavior with screenshots if applicable; and any additional context needed for reviewers.
Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.You can run@coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check nameStatusExplanation
Title check✅ PassedThe title 'feature: add explain with AI in query performance' directly describes the main change: adding an AI-powered explain feature to the query performance interface.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branchaliwaseem/fe-2282-query-performance-explained-in-ai

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

@supabase
Copy link

This pull request has been ignored for the connected projectxguihxuzqibwxjnimxev because there are no changes detected insupabase directory. You can change this behaviour inProject Integrations Settings ↗︎.


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

interfaceQueryDetailProps{
reportType:QUERY_PERFORMANCE_REPORT_TYPES
selectedRow:any
selectedRow:QueryPerformanceRow
Copy link
ContributorAuthor

Choose a reason for hiding this comment

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

Hatred for any continues and RAGES

@github-actions
Copy link
Contributor

github-actionsbot commentedDec 16, 2025
edited
Loading

🎭 Playwright Test Results

passed  66 passed
flaky  1 flaky
skipped  4 skipped

Details

stats  71 tests across 12 suites
duration  8 minutes, 54 seconds
commit  511fe9c

Flaky tests

Features › database.spec.ts › Database › Triggers › CRUD operations works as expected

Skipped tests

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

Copy link
Member

@jordienrjordienr left a comment

Choose a reason for hiding this comment

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

only 1 nitpick non blocker

@awaseemawaseem marked this pull request as ready for reviewDecember 17, 2025 15:42
@awaseemawaseem requested review froma team ascode ownersDecember 17, 2025 15:42
Copy link
Contributor

@coderabbitaicoderabbitaibot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
apps/studio/components/interfaces/QueryPerformance/QueryPerformance.ai.ts (1)

11-20:Consider adding time units for clarity in the AI prompt.

The metadata values lack units for time fields (e.g.,total_time,mean_time). While the AI may infer these, explicitly including "ms" would make the prompt more precise.

 const metadata = [-  `Total Time: ${selectedRow.total_time.toLocaleString()}`,+  `Total Time: ${selectedRow.total_time.toLocaleString()}ms`,   `Calls: ${selectedRow.calls.toLocaleString()}`,-  `Mean Time: ${selectedRow.mean_time.toLocaleString()}`,-  `Max Time: ${selectedRow.max_time.toLocaleString()}`,-  `Min Time: ${selectedRow.min_time.toLocaleString()}`,+  `Mean Time: ${selectedRow.mean_time.toLocaleString()}ms`,+  `Max Time: ${selectedRow.max_time.toLocaleString()}ms`,+  `Min Time: ${selectedRow.min_time.toLocaleString()}ms`,   `Rows Read: ${selectedRow.rows_read.toLocaleString()}`,   `Cache Hit Rate: ${selectedRow.cache_hit_rate.toLocaleString()}%`,   `Role: ${selectedRow.rolname}`, ].join('\n')
apps/studio/components/interfaces/QueryPerformance/QueryDetail.tsx (1)

44-44:UnusedreportType prop.

ThereportType prop is declared in the interface and destructured but not used anywhere in the component. Consider removing it if not needed, or add a comment if reserved for future use.

-export const QueryDetail = ({ selectedRow, onClickViewSuggestion, onClose }: QueryDetailProps) => {+export const QueryDetail = ({+  selectedRow,+  onClickViewSuggestion,+  onClose,+}: Omit<QueryDetailProps, 'reportType'>) => {

Or update the interface to removereportType if it's no longer needed.

📜 Review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between97fa071 and511fe9c.

📒 Files selected for processing (4)
  • apps/studio/components/interfaces/QueryPerformance/QueryDetail.tsx (3 hunks)
  • apps/studio/components/interfaces/QueryPerformance/QueryPerformance.ai.ts (1 hunks)
  • apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx (1 hunks)
  • packages/common/telemetry-constants.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
apps/studio/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/studio-best-practices.mdc)

apps/studio/**/*.{ts,tsx}: Assign complex conditions to descriptive variables instead of using multiple conditions in a single expression
Use consistent naming conventions for boolean variables:is prefix for state/identity,has prefix for possession,can prefix for capability/permission,should prefix for conditional behavior
Derive boolean state from existing state instead of storing it separately
Use early returns for guard clauses instead of deeply nested conditionals
Extract complex logic into custom hooks when logic becomes reusable or complex
Return objects from custom hooks instead of arrays for better extensibility and clearer API
Use discriminated unions for complex state management instead of multiple independent state fields
Avoid type casting (e.g.,as any,as Type); instead validate values at runtime using zod schemas

Files:

  • apps/studio/components/interfaces/QueryPerformance/QueryPerformance.ai.ts
  • apps/studio/components/interfaces/QueryPerformance/QueryDetail.tsx
  • apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx
apps/studio/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/studio-best-practices.mdc)

apps/studio/**/*.tsx: Components should ideally be under 200-300 lines; break down large components with multiple distinct UI sections, complex conditional rendering, or multiple unrelated useState hooks
Extract repeated JSX patterns into reusable components instead of copying similar JSX blocks
Use consistent loading/error/success pattern: handle loading state first with early returns, then error state, then empty state, then render success state
Keep state as local as possible and only lift up when needed
Group related state using objects or reducers instead of multiple useState calls, preferring react-hook-form for form state management
Name event handlers consistently: useon prefix for prop callbacks andhandle prefix for internal handlers
Avoid inline arrow functions for expensive operations; use useCallback to maintain stable function references
Use appropriate conditional rendering patterns: && for simple show/hide, ternary for binary choice, early returns or extracted components for multiple conditions
Avoid nested ternaries in JSX; use separate conditions or early returns instead
Use useMemo for expensive computations when the computation is genuinely expensive and the value is passed to memoized children
Define prop interfaces explicitly for React components with proper typing of props and callback handlers

Files:

  • apps/studio/components/interfaces/QueryPerformance/QueryDetail.tsx
  • apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx
🧠 Learnings (1)
📚 Learning: 2025-12-12T05:20:17.409Z
Learnt from: joshenlimRepo: supabase/supabase PR: 41258File: apps/studio/pages/project/[ref]/storage/vectors/buckets/[bucketId].tsx:9-9Timestamp: 2025-12-12T05:20:17.409ZLearning: In apps/studio/**/*.{ts,tsx}, use named imports for DefaultLayout: import { DefaultLayout } from 'components/layouts/DefaultLayout' instead of default import. This is the new practice being adopted across the studio app.

Applied to files:

  • apps/studio/components/interfaces/QueryPerformance/QueryPerformance.ai.ts
  • apps/studio/components/interfaces/QueryPerformance/QueryDetail.tsx
  • apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx
🧬 Code graph analysis (1)
apps/studio/components/interfaces/QueryPerformance/QueryPerformance.ai.ts (1)
apps/studio/components/interfaces/QueryPerformance/QueryPerformance.types.ts (1)
  • QueryPerformanceRow (3-18)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: test
🔇 Additional comments (5)
packages/common/telemetry-constants.ts (1)

2552-2562:LGTM!

The new telemetry event interface follows the established patterns in the file with proper JSDoc documentation and consistent typing.

apps/studio/components/interfaces/QueryPerformance/QueryPerformanceGrid.tsx (1)

617-617:LGTM!

TheonClose callback correctly mirrors the Sheet'sonOpenChange behavior, allowing the QueryDetail component to programmatically close the panel when opening the AI assistant.

apps/studio/components/interfaces/QueryPerformance/QueryPerformance.ai.ts (1)

31-48:LGTM!

The prompt structure is well-designed with clear sections for performance metrics, optional index advisor context, and focused instructions for concise, actionable responses.

apps/studio/components/interfaces/QueryPerformance/QueryDetail.tsx (2)

65-91:LGTM!

ThehandleExplainQuery function correctly:

  • Guards against missing query data
  • Builds the AI prompt using the extracted helper
  • Opens the AI assistant sidebar and initiates a chat with context
  • Sends the telemetry event with proper project/org grouping
  • Closes the detail panel to reveal the AI assistant

The telemetry event addresses the feedback from the previous review.


96-106:LGTM!

The UI integration follows consistent patterns with proper button styling and icon usage. The header layout with flex and justify-between is clean.

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment

Reviewers

@coderabbitaicoderabbitai[bot]coderabbitai[bot] left review comments

@jordienrjordienrjordienr approved these changes

At least 1 approving review is required to merge this pull request.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

2 participants

@awaseem@jordienr

[8]ページ先頭

©2009-2025 Movatter.jp