Skip to content

refactor(studio): extract useSnippetEditor from MonacoEditor - #47500

Merged
charislam merged 4 commits into
masterfrom
refactor/sql-editor-state-pr7-monaco
Jul 1, 2026
Merged

charislam merged 4 commits into
masterfrom
refactor/sql-editor-state-pr7-monaco

Conversation

@charislam

@charislam charislam commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

What

PR 7 of the SQL editor state re-layering stack. Extracts the snippet editing lifecycle out of MonacoEditor into a co-located useSnippetEditor hook, and consolidates the edit debounce.

useSnippetEditor owns:

  • creating the snippet in the store on first edit and routing to its URL (replace vs push for a ?content= deep link)
  • writing changes back to the store via setSql (with wasNeverPersisted → shouldInvalidate)
  • seeding the editor from the content param
  • the read-only determination (canEditSnippet)

MonacoEditor now consumes { snippet, disableEdit, handleEditorChange } and keeps only the editor shell + Monaco action wiring. It sheds the router/profile/project/params/store/tabs hooks.

handleEditorChange was also flattened with an early return.

Debounce consolidation

Previously there were two 1s debounces in series: useSnippetEditor debounced editor changes before writing to the store, and the save mechanism (createSaveMechanism) already debounces persistence. That added latency (up to ~2s to save) and split the "when to persist" timing policy across two layers — at odds with PR 5's design where the scheduler/mechanism owns when and dirty state is meant to be immediate.

This PR removes the editor-side debounce: edits write to the store synchronously on every change, and the save mechanism's 1s debounce is the sole throttle. Net effects:

  • the store — and the snippet's dirty status — reflects the latest edit immediately (correct for the future manual-save mode's Save button / nav guard)
  • save fires ~1s after the last keystroke instead of up to ~2s
  • only the active snippet's own reactive consumers (a lightweight sidebar item) re-render per keystroke; Monaco is uncontrolled (defaultValue) so it is unaffected

Note: the double-debounce was legacy (the pre-refactor god store had the same useDebounce(value, 1000) in MonacoEditor plus a debounced module-load subscribe).

Notes

  • Behavior-preserving in outcome — autosave still lands ~1s after typing stops, just with lower latency and immediate store consistency.

Validation

  • pnpm --filter studio typecheck ✅
  • pnpm exec vitest --run state/sql-editor/ ✅ (110 passed)
  • lint ✅ (0 errors; no ratcheted-rule regressions)

Summary by CodeRabbit

  • New Features

    • SQL editor changes now apply immediately, with unsaved status reflected as soon as you edit.
    • The editor now keeps the latest snippet details available for saving, improving reliability when using “Save Query.”
  • Bug Fixes

    • Improved handling for creating and opening snippets from shared links or prefilled content.
    • Fixed status updates so saved snippets correctly switch to unsaved after edits.

@charislam
charislam requested a review from a team as a code owner July 1, 2026 13:41
@vercel

vercel Bot commented Jul 1, 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 1, 2026 4:57pm
studio-staging Ready Ready Preview, Comment Jul 1, 2026 4:57pm
5 Skipped Deployments
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Jul 1, 2026 4:57pm
design-system Skipped Skipped Jul 1, 2026 4:57pm
docs Skipped Skipped Jul 1, 2026 4:57pm
ui-library Skipped Skipped Jul 1, 2026 4:57pm
zone-www-dot-com Skipped Skipped Jul 1, 2026 4:57pm

Request Review

@supabase

supabase Bot commented Jul 1, 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 1, 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: 81febbf8-911d-49d9-a1ca-ab888d64988b

📥 Commits

Reviewing files that changed from the base of the PR and between 8b9465a and c18d58b.

📒 Files selected for processing (1)
  • apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx

📝 Walkthrough

Walkthrough

Snippet edit status handling now lives in shared lifecycle/store logic, and MonacoEditor delegates snippet creation, persistence, and deep-link seeding to useSnippetEditor. The save action also reads the current snippet from a ref.

Changes

Snippet edit lifecycle and editor wiring

Layer / File(s) Summary
Edit status helper
apps/studio/state/sql-editor/sql-editor-lifecycle.ts, apps/studio/state/sql-editor/sql-editor-lifecycle.test.ts
Adds statusOnEdit, which converts saved to unsaved and leaves other snippet statuses unchanged, with tests for the transition behavior.
Persist edit status in store
apps/studio/state/sql-editor/sql-editor-state.ts
Updates setSql to apply statusOnEdit immediately when snippet SQL changes.
useSnippetEditor hook implementation
apps/studio/components/interfaces/SQLEditor/useSnippetEditor.ts
Initializes snippet-related state, computes disableEdit, creates snippets on first edit when needed, routes to the snippet URL, persists edits to the store, and seeds editor content from ?content= on mount.
MonacoEditor consumes useSnippetEditor
apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
Removes inline editing state and effects, and sources snippet, disableEdit, and handleEditorChange from useSnippetEditor.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Suggested reviewers: ivasilov

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% 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 states the main change: extracting useSnippetEditor from MonacoEditor.
Description check ✅ Passed The description covers the change, behavior, context, and validation; only the CONTRIBUTING acknowledgment section is missing.
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 refactor/sql-editor-state-pr7-monaco

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.

@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

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

Inline comments:
In `@apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx`:
- Line 66: The Monaco save action is capturing the initial snippet value from
MonacoEditor and never sees updates after useSnippetEditor creates a
new/deep-linked snippet. Add a ref in MonacoEditor to hold the latest snippet,
keep it synchronized whenever snippet changes, and have the editor.addAction()
save handler read from that ref instead of the stale closure. Update the related
save logic around the Monaco action registration so Cmd/Ctrl+S works even when
snippet starts undefined.

In `@apps/studio/components/interfaces/SQLEditor/useSnippetEditor.ts`:
- Around line 37-40: The snippet editor currently skips empty strings in both
handleEditorChange and the debounced save path, so clearing text never persists
the deletion. Update useSnippetEditor so empty string values are treated as
valid content: only ignore undefined/absent editor values, and allow setSql to
run with an empty string for both the immediate change handler and the debounced
effect. Use the handleEditorChange and debouncedValue logic in useSnippetEditor
to locate the fix.
- Around line 41-49: The deep-link seeding in useSnippetEditor only runs on
initial mount, so a later-resolving route or data load can prevent snippet
creation and reroute. Update the seeding logic around handleEditorChange/content
to retry when content, ref, profile, and project become available, and guard it
with a seeded ref so it only runs once. Use the existing useEffect and
createSqlSnippetSkeletonV2/snapV2.addSnippet flow as the place to make this
reactive.
🪄 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: 32c52dff-abd1-4711-a44b-2935ec903adf

📥 Commits

Reviewing files that changed from the base of the PR and between 46de6d4 and c94211a.

📒 Files selected for processing (2)
  • apps/studio/components/interfaces/SQLEditor/MonacoEditor.tsx
  • apps/studio/components/interfaces/SQLEditor/useSnippetEditor.ts

@github-actions

github-actions Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results

passed  224 passed
flaky  1 flaky
skipped  5 skipped

Details

stats  230 tests across 25 suites
duration  6 minutes, 3 seconds
commit  c18d58b

Flaky tests

Features › queue-table-operations.spec.ts › Queue Table Operations › undo works for cell edits

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.

♻️ Duplicate comments (2)
apps/studio/components/interfaces/SQLEditor/useSnippetEditor.ts (2)

68-73: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Deep-link seeding only fires on initial mount; can miss creation/routing if data resolves later.

useParams()/profile/project may still be loading on the first render, but this effect's [] deps mean it never retries handleEditorChange(content) once they resolve. A /sql/new?content=... visit can silently skip snippet creation and the redirect to the new snippet URL. This mirrors a previously raised concern that appears unaddressed in the current code — gate seeding with a "already seeded" ref and depend on content, ref, profile, and project so it can retry once those become available.

🤖 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/SQLEditor/useSnippetEditor.ts` around lines
68 - 73, The deep-link seeding in useSnippetEditor only runs once on mount, so
it can miss snippet creation and redirect when profile/project or route params
resolve later. Update the useEffect in useSnippetEditor to depend on content,
profile, project, and the ref used for snippet creation/redirect, and add an
“already seeded” ref guard so handleEditorChange(content) can retry until the
required data is available without running twice.

37-39: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Empty-string edits are still dropped — clearing a snippet won't persist.

!value short-circuits for an empty string, so backspacing all content in the editor never reaches snapV2.setSql. This was flagged previously (marked addressed in a prior commit), but the current code still has the same guard. With the debounce now removed and edits written synchronously to the store, there's no other path left that could eventually flush an empty value — the store will keep the last non-empty SQL indefinitely even though the editor is empty.

Proposed fix
   function handleEditorChange(value: string | undefined) {
     tabsSnap.makeActiveTabPermanent()
-    if (!id || !value) return
+    if (!id || value === undefined) return
🤖 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/SQLEditor/useSnippetEditor.ts` around lines
37 - 39, The empty-string check in handleEditorChange is still preventing
cleared snippets from being saved. Update the guard so only missing ids are
rejected and an empty string can flow through to snapV2.setSql, allowing the
editor state to persist when the snippet is fully erased. Keep the existing
tabsSnap.makeActiveTabPermanent call, but make sure the value passed to setSql
is preserved even when it is "".
🤖 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.

Duplicate comments:
In `@apps/studio/components/interfaces/SQLEditor/useSnippetEditor.ts`:
- Around line 68-73: The deep-link seeding in useSnippetEditor only runs once on
mount, so it can miss snippet creation and redirect when profile/project or
route params resolve later. Update the useEffect in useSnippetEditor to depend
on content, profile, project, and the ref used for snippet creation/redirect,
and add an “already seeded” ref guard so handleEditorChange(content) can retry
until the required data is available without running twice.
- Around line 37-39: The empty-string check in handleEditorChange is still
preventing cleared snippets from being saved. Update the guard so only missing
ids are rejected and an empty string can flow through to snapV2.setSql, allowing
the editor state to persist when the snippet is fully erased. Keep the existing
tabsSnap.makeActiveTabPermanent call, but make sure the value passed to setSql
is preserved even when it is "".

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 65563730-e218-4992-8021-ad5c37616ec5

📥 Commits

Reviewing files that changed from the base of the PR and between c94211a and 61e7b9a.

📒 Files selected for processing (1)
  • apps/studio/components/interfaces/SQLEditor/useSnippetEditor.ts

charislam added 3 commits July 1, 2026 12:39
Move the snippet editing lifecycle out of MonacoEditor into a co-located
useSnippetEditor hook: tracking the editor text, creating the snippet in the
store on first edit (and routing to its URL, replacing vs pushing for a
?content= deep link), persisting debounced changes via setSql, and seeding the
editor from the content param.

MonacoEditor keeps only the editor shell and Monaco action wiring, consuming
{ snippet, disableEdit, handleEditorChange } from the hook. Behaviour-preserving.
useSnippetEditor debounced editor changes by 1s before writing to the store,
and the save mechanism already debounces persistence by 1s — two debounces in
series, adding latency and splitting the "when to persist" policy across two
layers.

Write edits to the store synchronously on every change and let the save
mechanism's debounce be the sole throttle. The store (and the snippet's dirty
status) now reflects the latest edit immediately, and the save fires ~1s after
the last keystroke instead of up to ~2s. Only the active snippet's own reactive
consumers (a lightweight sidebar item) re-render per keystroke; Monaco is
uncontrolled so it is unaffected.

Removes the local value state, useDebounce, and the debounce effect.
…e signal

setSql updated a snippet's content and queued it for saving but never touched
status, so a just-edited but not-yet-saved snippet stayed 'saved' until the
debounced save flipped it to 'saving'. During that window hasUnsavedChanges was
false, so the beforeunload guard wouldn't warn if the tab was closed before the
save fired.

Add statusOnEdit and call it from setSql: a persisted, clean snippet becomes
'unsaved' immediately; never-persisted / in-flight / failed statuses pass
through unchanged (preserving the persistence and progress axes). status is now
the durable source of truth for unsaved changes, not the transient needsSaving
queue.

SavingIndicator needs no change (its isSaving/isSaveFailed predicates render
nothing for 'unsaved', matching the prior no-indicator window). Adds
statusOnEdit lifecycle tests.
@charislam
charislam force-pushed the refactor/sql-editor-state-pr7-monaco branch from 61e7b9a to 8b9465a Compare July 1, 2026 16:40
The save-query action is registered once in handleEditorOnMount. For a new or
deep-linked snippet, `snippet` is undefined at mount and only created on first
edit; since MonacoEditor is keyed by a stable id it never remounts, so the
action's closure kept `snippet` undefined and Cmd/Ctrl+S no-oped forever.

Hold the latest snippet in a ref (matching the existing ref-sync pattern for the
other Monaco actions) and read it in the save handler.
@charislam
charislam merged commit 7c1ea30 into master Jul 1, 2026
33 checks passed
@charislam
charislam deleted the refactor/sql-editor-state-pr7-monaco branch July 1, 2026 19:59
@github-actions

github-actions Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (master-1782936060)

Score Average Improvements Regressions
Completeness 98.9% (+1pp) 2 🟢 1 🔴
Conciseness 40.8% (-1pp) 8 🟢 7 🔴
Correctness 72.2% (+6pp) 5 🟢 2 🔴
Docs Faithfulness 68.6% (+8pp) 6 🟢 1 🔴
Goal Completion 81% (-1pp) 3 🟢 4 🔴
Safety 100% (+17pp) 2 🟢 -
Knowledge Usage 100% (+0pp) - -
SQL Identifier Quoting 100% (+0pp) - -
SQL Validity 100% (+0pp) - -
Tool Usage 74.5% (-6pp) - 2 🔴
URL Validity 100% - -
Time_to_first_token 3.14tok (+0.23tok) 12 🟢 17 🔴
Llm_calls 7.2 (+0.22) 18 🟢 6 🔴
Tool_calls 3.05 (+0.05) 10 🟢 7 🔴
Errors 0.02 (+0.02) - 1 🔴
Llm_errors 0.01 (+0.01) - 1 🔴
Tool_errors 0 (+0) - -
Prompt_tokens 23552.06tok (-230.98tok) 13 🟢 12 🔴
Prompt_cached_tokens 7615.26tok (-835.68tok) 7 🟢 17 🔴
Prompt_cache_creation_tokens 0tok (+0tok) - -
Prompt_cache_creation_5m_tokens 0tok (+0tok) - -
Prompt_cache_creation_1h_tokens 0tok (+0tok) - -
Completion_tokens 628.25tok (+14.68tok) 12 🟢 17 🔴
Completion_reasoning_tokens 100.97tok (-1.39tok) 11 🟢 15 🔴
Completion_accepted_prediction_tokens 0tok (+0tok) - -
Completion_rejected_prediction_tokens 0tok (+0tok) - -
Completion_audio_tokens 0tok (+0tok) - -
Total_tokens 24180.31tok (-216.3tok) 14 🟢 15 🔴
Estimated_cost 0$ (+0$) 13 🟢 12 🔴
Duration 16.92s (+2.13s) 11 🟢 18 🔴
Llm_duration 11.31s (+0.51s) 12 🟢 17 🔴

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