Repository navigation
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
6 Skipped Deployments
|
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
WalkthroughReplaces EdgeFunctionFile with FileData across utils, UI, and data layers; adds per-file state ('new' | 'modified' | 'unchanged'); introduces formatFunctionBodyToFiles() to normalize remote function bodies; adds unsaved-change detection and selection by selectedFileId; adds right-aligned actions to TreeView items. Changes
Sequence DiagramsequenceDiagram
participant User
participant Explorer as FileExplorerAndEditor
participant Page
participant Browser
User->>Explorer: Edit/create files
Explorer->>Explorer: Update FileData (state: new/modified/unchanged)
Explorer->>Page: onFilesChange(files)
Page->>Page: Compare files vs initialFiles (isEqual)
Page->>Page: Set hasUnsavedChanges
User->>Browser: Attempt navigation
Browser->>Page: beforeunload event
alt hasUnsavedChanges == true
Page->>Browser: Trigger unsaved changes warning
Browser->>User: Show confirm/cancel dialog
else
Browser->>User: Allow navigation
end
User->>Explorer: View tree
Explorer->>User: Render state badges and right-aligned actions
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Fix all issues with AI agents
In `@apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.ts`:
- Around line 76-95: The mapping over functionBody.files mutates the original
objects by assigning to file.name, which can corrupt the API response; instead
create and return a new object for each entry (e.g., inside the filesWithRelPath
map) copying existing properties and setting the adjusted name via relative('/'
+ base_path, '/' + file.name) when appropriate; ensure you never assign to
file.name directly and handle the same try/catch around the creation to return
the original file object untouched on error.
- Around line 116-141: The checkUnimportedFiles function incorrectly only strips
".ts" (file.name.replace('.ts','')) and uses naive
indexFile.content.includes(...) which causes missed matches for .js/.tsx/.jsx
and false positives via substring matches; update checkUnimportedFiles to
normalize filenames by removing any of the known extensions (e.g., .ts, .tsx,
.js, .jsx) using the file.name base (e.g., path.basename without extension or a
small helper that strips a list of extensions) and replace the includes check
with a safer import-aware match (e.g., test for import/require/export patterns
or at minimum use word-boundary/regex matching like \b<basename>\b or look for
'./<basename>' and '/<basename>' variants) when checking indexFile.content and
level1Files.content so only proper imports are considered.
In `@apps/studio/pages/project/`[ref]/functions/[functionSlug]/code.tsx:
- Around line 69-79: The memoized initialFiles currently passes a stale/unused
files array into formatFunctionBodyToFiles and silences exhaustive-deps; either
remove the files parameter entirely (recommended if you always want fresh
API-derived files) or include files in the dependency array and refactor to
avoid loops. To fix by removing: update formatFunctionBodyToFiles signature to
drop the files/prevState lookup, remove any files.find() logic inside it, call
formatFunctionBodyToFiles({ functionBody, entrypointPath:
selectedFunction?.entrypoint_path }) from the useMemo, remove the eslint-disable
comment and keep [isSuccessLoadingFiles] as the single dep; ensure
hasUnsavedChanges logic still compares the resulting initialFiles to the
editable files state. If you instead want to preserve user state, add files to
the useMemo deps and change the logic to use files only when it differs from the
API-derived content to prevent infinite recomputation.
In `@apps/studio/pages/project/`[ref]/functions/new.tsx:
- Around line 435-449: The AlertDialogAction currently has no onClick, so the
"Deploy function" button does nothing; wire it to call handleDeploy and close
the dialog: add an onClick handler to AlertDialogAction that calls
handleDeploy() and then setShowWarning(false) (or otherwise close the dialog) to
proceed with deployment; ensure you import/use the existing handleDeploy
function referenced in this component and preserve any async/await or error
handling already present in handleDeploy.
🧹 Nitpick comments (1)
apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx (1)
145-148: Effect dependency may cause issues.The effect runs when
initialFileschanges, butinitialFilesis a new array reference each timeisSuccessLoadingFilestransitions to true. If this effect triggers andsetFiles(initialFiles)causes a re-render, the memo would need to be stable to avoid loops.Currently this works because
isSuccessLoadingFilesonly transitions once, but the pattern is fragile. Consider adding an explicit guard or using a ref to track initialization.Alternative approach using a ref
+ const hasInitialized = useRef(false) + useEffect(() => { - if (initialFiles.length === 0) return - setFiles(initialFiles) - }, [initialFiles]) + if (hasInitialized.current || initialFiles.length === 0) return + hasInitialized.current = true + setFiles(initialFiles) + }, [initialFiles])
📜 Review details
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
apps/studio/components/interfaces/EdgeFunctions/DeployEdgeFunctionWarningModal.tsxapps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.tsapps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsxapps/studio/pages/project/[ref]/functions/new.tsx
🧰 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:isprefix for state/identity,hasprefix for possession,canprefix for capability/permission,shouldprefix 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/EdgeFunctions/DeployEdgeFunctionWarningModal.tsxapps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.tsapps/studio/pages/project/[ref]/functions/new.tsxapps/studio/pages/project/[ref]/functions/[functionSlug]/code.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: useonprefix for prop callbacks andhandleprefix 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/EdgeFunctions/DeployEdgeFunctionWarningModal.tsxapps/studio/pages/project/[ref]/functions/new.tsxapps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx
🧠 Learnings (15)
📚 Learning: 2025-12-11T16:46:18.701Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.701Z
Learning: Applies to apps/studio/**/*.tsx : Define prop interfaces explicitly for React components with proper typing of props and callback handlers
Applied to files:
apps/studio/components/interfaces/EdgeFunctions/DeployEdgeFunctionWarningModal.tsx
📚 Learning: 2025-12-12T05:20:17.409Z
Learnt from: joshenlim
Repo: supabase/supabase PR: 41258
File: apps/studio/pages/project/[ref]/storage/vectors/buckets/[bucketId].tsx:9-9
Timestamp: 2025-12-12T05:20:17.409Z
Learning: 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/EdgeFunctions/DeployEdgeFunctionWarningModal.tsxapps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.tsapps/studio/pages/project/[ref]/functions/new.tsxapps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx
📚 Learning: 2026-01-02T05:58:55.226Z
Learnt from: meGauravJain
Repo: supabase/supabase PR: 41658
File: apps/studio/components/interfaces/Connect/content/prisma/content.tsx:70-85
Timestamp: 2026-01-02T05:58:55.226Z
Learning: In Prisma configuration or related connection setup code, prefer the environment variable name DIRECT_URL for direct/non-pooled database connections instead of DATABASE_URL_UNPOOLED, per Prisma documentation. Update code that reads database connection strings to use DIRECT_URL where applicable, and document why this is preferred (explicit, documented behavior). Ensure your environment provides DIRECT_URL when using direct connections and fallback handling if needed.
Applied to files:
apps/studio/components/interfaces/EdgeFunctions/DeployEdgeFunctionWarningModal.tsxapps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.tsapps/studio/pages/project/[ref]/functions/new.tsxapps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx
📚 Learning: 2026-01-06T18:30:35.031Z
Learnt from: laktek
Repo: supabase/supabase PR: 41745
File: apps/studio/components/layouts/EdgeFunctionsLayout/EdgeFunctionDetailsLayout.tsx:171-190
Timestamp: 2026-01-06T18:30:35.031Z
Learning: In the Supabase edge functions system, paths with embedded "../" segments are denormalized on the backend, so frontend ZIP generation in EdgeFunctionDetailsLayout.tsx doesn't need additional path normalization beyond stripping leading "../" segments.
Applied to files:
apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.tsapps/studio/pages/project/[ref]/functions/new.tsxapps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx
📚 Learning: 2025-12-11T16:46:03.692Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/e2e-testing.mdc:0-0
Timestamp: 2025-12-11T16:46:03.692Z
Learning: Applies to e2e/studio/**/*.{ts,spec.ts} : Always import from the custom test utility at '../utils/test.js' for consistent fixtures in E2E tests
Applied to files:
apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.ts
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/interfaces/**/*.{ts,tsx} : Create a new component in apps/studio/components/interfaces for the contents of each new page
Applied to files:
apps/studio/pages/project/[ref]/functions/new.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Do not introduce new UI components unless asked to; check packages/ui/index.tsx for available components before composing interfaces
Applied to files:
apps/studio/pages/project/[ref]/functions/new.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Build forms with react-hook-form and zod for validation
Applied to files:
apps/studio/pages/project/[ref]/functions/new.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/**/*.{ts,tsx} : Use Admonition component to alert users of important actions or restrictions
Applied to files:
apps/studio/pages/project/[ref]/functions/new.tsx
📚 Learning: 2026-01-05T23:42:59.440Z
Learnt from: kallebysantos
Repo: supabase/supabase PR: 41727
File: apps/docs/content/guides/functions/auth.mdx:93-93
Timestamp: 2026-01-05T23:42:59.440Z
Learning: In Supabase Edge Functions documentation, the `meta="name=..."` attribute in CodeSample components may intentionally use generic example names (like "hello/index.ts") rather than matching the actual file path being referenced, to help users understand how to adapt templates to their own use cases.
Applied to files:
apps/studio/pages/project/[ref]/functions/new.tsxapps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx
📚 Learning: 2025-12-11T16:46:18.701Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.701Z
Learning: Applies to apps/studio/**/*.tsx : Avoid inline arrow functions for expensive operations; use useCallback to maintain stable function references
Applied to files:
apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx
📚 Learning: 2025-12-11T17:04:40.037Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Import primitive UI components from packages/ui package for use across apps, not from individual component files
Applied to files:
apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx
📚 Learning: 2025-12-11T16:46:18.701Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.701Z
Learning: Applies to apps/studio/**/*.tsx : Extract repeated JSX patterns into reusable components instead of copying similar JSX blocks
Applied to files:
apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx
📚 Learning: 2025-12-11T16:46:18.701Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.701Z
Learning: Applies to 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
Applied to files:
apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx
📚 Learning: 2025-12-11T16:46:18.701Z
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.701Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Extract complex logic into custom hooks when logic becomes reusable or complex
Applied to files:
apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx
⏰ 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). (3)
- GitHub Check: test
- GitHub Check: typecheck
- GitHub Check: test (1)
🔇 Additional comments (6)
apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.ts (1)
40-57: LGTM!The
getBasePathhelper correctly handles the edge cases: missing entrypoint returns/, file name suffix matching derives the directory, and URL parsing serves as a fallback with appropriate error handling.apps/studio/components/interfaces/EdgeFunctions/DeployEdgeFunctionWarningModal.tsx (1)
1-49: LGTM!The component is well-structured with explicit prop typing, and the conditional alert rendering follows best practices. The warning message clearly communicates the issue to users.
apps/studio/pages/project/[ref]/functions/new.tsx (2)
284-293: LGTM on beforeunload handling.The effect correctly adds and removes the event listener, and properly uses
e.preventDefault()along with the legacyreturnValuefor cross-browser compatibility.
112-119: FixhasUnsavedChangescomparison to account for template URL parameter initialization.
hasUnsavedChangescompares against a fixedINITIAL_FILESconstant (which always has 'hello-world' template content), but the actual initial state can differ when atemplateURL parameter is provided. When users load the page with?template=stripe-webhook(or another template), thetemplateeffect (lines 266-282) correctly updatesfileswith that template's content. However,hasUnsavedChangeswill incorrectly reporttrueeven if the user makes no edits, because it compares the template-loaded content against the hardcoded hello-worldINITIAL_FILES.Store the actual initial file state after template initialization completes, or compare
filesagainst the current template's content instead of a fixed constant.Note:
EDGE_FUNCTION_TEMPLATES[0]is safe at module load (it's a static export), but consider whetherINITIAL_FILESshould be derived from the first template rather than hardcoded.apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx (2)
150-159: LGTM on beforeunload handling.The implementation correctly prevents accidental navigation when there are unsaved changes, matching the pattern used in
new.tsx.
224-230: LGTM!The
DeployEdgeFunctionWarningModalis correctly wired with theunimportedFilesprop to display the appropriate warning.
✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.
🎭 Playwright Test ResultsDetails
Flaky testsFeatures › sql-editor.spec.ts › SQL Editor › should check if SQL editor is working as expected Skipped testsFeatures › sql-editor.spec.ts › SQL Editor › snippet favourite works as expected |
b727e89 to
08b81e3
Compare
…ppears-after-deploy-in-dashboard
…modified and unsaved files
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx (1)
54-58: DuplicaterefetchOnMountoption.
refetchOnMount: falseappears twice in the query options (lines 54 and 57). Remove the duplicate.🔧 Proposed fix
// [Alaister]: These parameters prevent the function files // from being refetched when the user is editing the code retry: false, retryOnMount: false, refetchOnWindowFocus: false, staleTime: Infinity, - refetchOnMount: false, refetchOnReconnect: false, refetchInterval: false, refetchIntervalInBackground: false,apps/studio/components/ui/FileExplorerAndEditor/index.tsx (1)
218-232: Bug:handleStartRenameincorrectly setsstate: 'new'for all files.When a user starts renaming a file, this function hardcodes
state: 'new'for every file in the tree (line 228). This will incorrectly change the visual state indicator for files that were'unchanged'or'modified'.🐛 Proposed fix: preserve the file's actual state
const handleStartRename = (id: number) => { // Force re-render of the TreeView with the updated metadata setTreeData({ name: '', children: files.map((file) => ({ id: file.id.toString(), name: file.name, metadata: { isEditing: file.id === id, originalId: file.id, - state: 'new', + state: file.state, }, })), }) }
🤖 Fix all issues with AI agents
In
`@apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.types.ts`:
- Line 6: The FileData type declares a required state ('new' | 'modified' |
'unchanged') but the API response doesn't include it; either make state optional
on FileData (change state to state?: 'new' | 'modified' | 'unchanged') or update
the response cast that currently uses Omit<FileData, 'id' | 'selected'>[] to
also omit state (e.g., Omit<FileData, 'id' | 'selected' | 'state'>[]); locate
the FileData declaration and the cast using Omit<FileData, 'id' | 'selected'>[]
and apply one of these fixes so types align with the API response.
In `@apps/studio/data/edge-functions/edge-function-body-query.ts`:
- Around line 56-59: The files array is being cast to Omit<FileData, 'id' |
'selected'> but FileData now requires a state field; update the cast to exclude
state as well (e.g., cast files to Omit<FileData, 'id' | 'selected' | 'state'>
or use a narrower type like Pick<FileData,'name'|'content'>) where the variable
files is returned so the compiler no longer masks the missing state field;
adjust the return object in edge-function-body-query.ts accordingly.
♻️ Duplicate comments (1)
apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx (1)
65-75: Thefilesparameter informatFunctionBodyToFilesappears unused based on the memoization.The
eslint-disablesuppresses the exhaustive-deps warning, but whenisSuccessLoadingFilesfirst becomestrue,filesis still[](initial state). This means thefiles.find()lookup insideformatFunctionBodyToFileswill never find matches on initial load.If the intent is to always derive
initialFilesfresh from the API response (which the query config withstaleTime: Infinitysuggests), consider removing thefilesparameter fromformatFunctionBodyToFiles. If preserving user edits across reloads is intended, the dependency array needs restructuring.
🧹 Nitpick comments (2)
apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx (1)
182-193: Consider extracting theonFilesChangehandler.Per coding guidelines, inline arrow functions passed to props should be avoided when they perform non-trivial logic. This handler compares against
initialFileson every file change.♻️ Suggested refactor using useCallback
+ const handleFilesChange = useCallback( + (files: FileData[]) => { + const formattedFiles: FileData[] = files.map((f) => { + const originalFile = initialFiles.find((x) => x.id === f.id) + if (!originalFile) { + return f + } else if (originalFile.content !== f.content) { + return { ...f, state: 'modified' } + } + return { ...f, state: 'unchanged' } + }) + setFiles(formattedFiles) + }, + [initialFiles] + ) <FileExplorerAndEditor files={files} - onFilesChange={(files) => { - const formattedFiles: FileData[] = files.map((f) => { - const originalFile = initialFiles.find((x) => x.id === f.id) - if (!originalFile) { - return f - } else if (originalFile.content !== f.content) { - return { ...f, state: 'modified' } - } - return { ...f, state: 'unchanged' } - }) - setFiles(formattedFiles) - }} + onFilesChange={handleFilesChange} aiEndpoint={`${BASE_PATH}/api/ai/code/complete`}apps/studio/components/ui/FileExplorerAndEditor/index.tsx (1)
409-417: Consider simplifying the nested ternary.The className has nested ternaries which can be hard to read. Per coding guidelines, avoid nested ternaries in JSX.
♻️ Suggested refactor using cn() with conditional object
- className={cn( - isEditing - ? '' - : state === 'new' - ? 'text-brand-600' - : state === 'modified' - ? 'text-code_block-2' - : '' - )} + className={cn({ + 'text-brand-600': !isEditing && state === 'new', + 'text-code_block-2': !isEditing && state === 'modified', + })}
| name: string | ||
| content: string | ||
| selected?: boolean | ||
| state: 'new' | 'modified' | 'unchanged' |
There was a problem hiding this comment.
Type mismatch: state is required but API response doesn't include it.
The state field is required on FileData, but in edge-function-body-query.ts (line 58), the API response is cast to Omit<FileData, 'id' | 'selected'>[]—which still expects state to be present. However, the API doesn't return a state field.
Consider either:
- Making
stateoptional:state?: 'new' | 'modified' | 'unchanged' - Updating the cast to also omit
state:Omit<FileData, 'id' | 'selected' | 'state'>[]
🔧 Option 2: Update the cast in edge-function-body-query.ts
return {
metadata,
- files: files as Omit<FileData, 'id' | 'selected'>[],
+ files: files as Omit<FileData, 'id' | 'selected' | 'state'>[],
}🤖 Prompt for AI Agents
In
`@apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.types.ts`
at line 6, The FileData type declares a required state ('new' | 'modified' |
'unchanged') but the API response doesn't include it; either make state optional
on FileData (change state to state?: 'new' | 'modified' | 'unchanged') or update
the response cast that currently uses Omit<FileData, 'id' | 'selected'>[] to
also omit state (e.g., Omit<FileData, 'id' | 'selected' | 'state'>[]); locate
the FileData declaration and the cast using Omit<FileData, 'id' | 'selected'>[]
and apply one of these fixes so types align with the API response.
There was a problem hiding this comment.
@alaister Yes, option 2 is correct! 👍
The API doesn't return the state field, so the cast should omit it. Looking at the code flow, formatFunctionBodyToFiles in EdgeFunctions.utils.ts adds the state field (defaulting to 'unchanged') when transforming the API response into FileData[]. This keeps the types aligned at each step:
- API response →
Omit<FileData, 'id' | 'selected' | 'state'>[](no state yet) formatFunctionBodyToFiles→FileData[](state added)- Component usage →
FileData[](with state)
🧠 Learnings used
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.701Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Derive boolean state from existing state instead of storing it separately
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-best-practices.mdc:0-0
Timestamp: 2025-12-11T16:46:18.701Z
Learning: Applies to apps/studio/**/*.{ts,tsx} : Use discriminated unions for complex state management instead of multiple independent state fields
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@apps/studio/pages/project/`[ref]/functions/new.tsx:
- Line 136: The showWarning state is never set true because no detection of
unimported files is performed; update handleDeploy to first run a detection
routine (e.g., a function detectUnimportedFiles or inline logic) that scans the
project's files against index.ts imports and returns the list of unimported
files, and if any are found call setShowWarning(true) to display the dialog
instead of immediately invoking form.handleSubmit(onSubmit)(); wire the dialog
confirmation to continue the deploy by invoking form.handleSubmit(onSubmit)()
when the user confirms; reference and modify handleDeploy, setShowWarning,
showWarning, and onSubmit to implement this flow.
♻️ Duplicate comments (2)
apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx (1)
66-75: Thefilesparameter issue persists — still passed toformatFunctionBodyToFilesbut excluded from dependencies.This was flagged in a previous review and marked as addressed, but the same pattern remains:
filesis captured in the closure (line 71) yet excluded from the dependency array with aneslint-disablecomment.When
isSuccessLoadingFilesbecomestrueand this memo runs,filesis always[](the initial state from line 64). Thefiles.find()call insideformatFunctionBodyToFiles(per the utility atEdgeFunctions.utils.ts:100) will never find a match, making thefilesparameter ineffective for preserving selection state.If the intent is to preserve selection state from a prior render, the dependency array needs restructuring. If the intent is always fresh data from API, remove the
filesparameter from the call and updateformatFunctionBodyToFilesaccordingly.apps/studio/pages/project/[ref]/functions/new.tsx (1)
433-447: Critical:AlertDialogActionis still missing itsonClickhandler.This issue was previously flagged and marked as addressed, but the "Deploy function" button still has no
onClickhandler. Clicking it will only close the dialog without actually deploying the function.Proposed fix
<AlertDialogFooter> <AlertDialogCancel>Cancel</AlertDialogCancel> - <AlertDialogAction>Deploy function</AlertDialogAction> + <AlertDialogAction onClick={handleDeploy}>Deploy function</AlertDialogAction> </AlertDialogFooter>
🧹 Nitpick comments (1)
apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx (1)
187-198: Consider extractingonFilesChangehandler withuseCallback.This inline arrow function performs non-trivial work (mapping, finding original files, computing state). Per coding guidelines, extracting it with
useCallbackwould provide a stable reference ifFileExplorerAndEditoris memoized.Suggested refactor
+ const handleFilesChange = useCallback( + (updatedFiles: FileData[]) => { + const formattedFiles: FileData[] = updatedFiles.map((f) => { + const originalFile = initialFiles.find((x) => x.id === f.id) + if (!originalFile) { + return f + } else if (originalFile.content !== f.content) { + return { ...f, state: 'modified' } + } + return { ...f, state: 'unchanged' } + }) + setFiles(formattedFiles) + }, + [initialFiles] + ) <FileExplorerAndEditor files={files} - onFilesChange={(files) => { - const formattedFiles: FileData[] = files.map((f) => { - const originalFile = initialFiles.find((x) => x.id === f.id) - if (!originalFile) { - return f - } else if (originalFile.content !== f.content) { - return { ...f, state: 'modified' } - } - return { ...f, state: 'unchanged' } - }) - setFiles(formattedFiles) - }} + onFilesChange={handleFilesChange} aiEndpoint={`${BASE_PATH}/api/ai/code/complete`}
| const [open, setOpen] = useState(false) | ||
| const [isPreviewingTemplate, setIsPreviewingTemplate] = useState(false) | ||
| const [savedCode, setSavedCode] = useState<string>('') | ||
| const [showWarning, setShowWarning] = useState(false) |
There was a problem hiding this comment.
Critical: showWarning is never set to true — the unimported files warning will never display.
The PR objective states this dialog should "warn about unimported files that would be omitted from the deployed bundle," but there is no code that sets showWarning(true). The detection logic for unimported files is missing.
Expected flow based on PR objectives:
- Before deploy, detect files not imported through
index.ts - If unimported files exist, call
setShowWarning(true)to show the warning - User confirms, then deploy proceeds
Currently, handleDeploy calls form.handleSubmit(onSubmit)() directly without any detection check.
Suggested approach
+ const hasUnimportedFiles = useMemo(() => {
+ // Detection logic: check if any files beyond index.ts are not imported
+ // This is a simplified check - adjust based on actual detection requirements
+ return files.length > 1 && files.some((f) => f.name !== 'index.ts' && /* not imported check */)
+ }, [files])
const handleDeploy = () => {
const currentName = form.getValues('functionName')
const isValid = FUNCTION_NAME_REGEX.test(currentName)
if (!isValid && currentName) {
const sanitizedName = sanitizeFunctionName(currentName)
form.setValue('functionName', sanitizedName, { shouldValidate: true })
}
+ if (hasUnimportedFiles) {
+ setShowWarning(true)
+ return
+ }
+
form.handleSubmit(onSubmit)()
}🤖 Prompt for AI Agents
In `@apps/studio/pages/project/`[ref]/functions/new.tsx at line 136, The
showWarning state is never set true because no detection of unimported files is
performed; update handleDeploy to first run a detection routine (e.g., a
function detectUnimportedFiles or inline logic) that scans the project's files
against index.ts imports and returns the list of unimported files, and if any
are found call setShowWarning(true) to display the dialog instead of immediately
invoking form.handleSubmit(onSubmit)(); wire the dialog confirmation to continue
the deploy by invoking form.handleSubmit(onSubmit)() when the user confirms;
reference and modify handleDeploy, setShowWarning, showWarning, and onSubmit to
implement this flow.
charislam
left a comment
There was a problem hiding this comment.
There's some odd behavior when renaming: here I have two files that are untouched, but when I try to rename each one, the other file gets the modified state while I'm renaming
CleanShot.2026-01-20.at.10.08.27.mp4
| }) | ||
| : [] | ||
| // eslint-disable-next-line react-hooks/exhaustive-deps | ||
| }, [isSuccessLoadingFiles]) |
There was a problem hiding this comment.
Let's use a ref like const initializedRef = useRef(false) here so we don't have to disable the lint. IMO it's better to be explicit, avoids footguns later.
| state !== 'unchanged' && ( | ||
| <div className="flex items-center justify-center w-3"> | ||
| <Tooltip> | ||
| <TooltipTrigger className="text-xs">{state === 'new' ? 'U' : 'M'}</TooltipTrigger> |
There was a problem hiding this comment.
Just pushed up this className="text-xs" so it isn’t so large. Matches VSCode.
dnywh
left a comment
There was a problem hiding this comment.
Tested on staging and locally. Made one minor text size change on the M and U. Looks good!
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
apps/studio/pages/project/[ref]/functions/new.tsx (1)
104-129: Unsaved-change baseline should update when a template is preselected.
hasUnsavedChangescompares against the staticINITIAL_FILES, so a template passed via the URL (or future baseline changes) can flag the page as dirty even when a reload would restore the same template. Also, comparingselected/statecan introduce false positives. Consider tracking aninitialFilesstate that you reset on template changes and compare only stable fields (id/name/content).🔧 Suggested adjustment
-const INITIAL_FILES: FileData[] = [ - { - id: 1, - name: 'index.ts', - selected: true, - content: EDGE_FUNCTION_TEMPLATES[0].content, - state: 'new', - }, -] +const buildInitialFiles = (content: string): FileData[] => [ + { + id: 1, + name: 'index.ts', + selected: true, + content, + state: 'new', + }, +] -const [files, setFiles] = useState<FileData[]>(INITIAL_FILES) +const [initialFiles, setInitialFiles] = useState<FileData[]>(() => + buildInitialFiles(EDGE_FUNCTION_TEMPLATES[0].content) +) +const [files, setFiles] = useState<FileData[]>(initialFiles) -const hasUnsavedChanges = !isEqual(INITIAL_FILES, files) +const normalizeFiles = (list: FileData[]) => + list.map(({ id, name, content }) => ({ id, name, content })) +const hasUnsavedChanges = !isEqual(normalizeFiles(initialFiles), normalizeFiles(files)) ... - setFiles([ - { - id: 1, - name: 'index.ts', - selected: true, - content: templateMeta.content, - state: 'new', - }, - ]) + const nextFiles = buildInitialFiles(templateMeta.content) + setInitialFiles(nextFiles) + setFiles(nextFiles)Also applies to: 257-270
apps/studio/components/ui/FileExplorerAndEditor/index.tsx (1)
218-231: Rename mode shouldn’t mark every file asnew.
handleStartRenamesetsstate: 'new'for all nodes, which will paint the entire tree as unsaved while renaming a single file. Preserve each file’s existing state instead.🐛 Suggested fix
- state: 'new', + state: file.state,
🤖 Fix all issues with AI agents
In `@apps/studio/pages/project/`[ref]/functions/[functionSlug]/code.tsx:
- Around line 187-196: The current onFilesChange handler only marks files as
'modified' when content changes, so renames aren't detected; update the
comparison in the formattedFiles mapping (inside onFilesChange) to consider both
originalFile.content and originalFile.name (or id-name pair) when deciding state
on FileData: if either content or name differs from initialFiles (the
originalFile found by id), set state to 'modified', otherwise 'unchanged'
(preserve returning f when originalFile is missing).
- Around line 64-77: The unsaved-change check is comparing full FileData objects
(including UI-only fields) so selection/state flips mark the doc dirty;
normalize both sides to only the editable fields (e.g., id, name, content)
before comparing. Update the logic around initialFiles/hasUnsavedChanges
(references: initialFiles, files, hasUnsavedChanges, formatFunctionBodyToFiles,
FileData) to map initialFiles and files to arrays of objects containing only
id/name/content (or whichever canonical editable props) and then use isEqual on
those normalized arrays to determine dirty state.
♻️ Duplicate comments (2)
apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.ts (1)
76-90: Avoid mutating API file objects when rewriting paths.
Assigning tofile.namemutates the original API response, which can leak into caches or other consumers. Return a new object instead.🐛 Suggested fix
- file.name = relative('/' + base_path, '/' + file.name) - return file + return { + ...file, + name: relative('/' + base_path, '/' + file.name), + }apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx (1)
66-75:initialFilesmemo uses stale dependencies.
functionBody,selectedFunction?.entrypoint_path, andfilesare referenced but onlyisSuccessLoadingFilesis in the dependency list (with lint suppressed), sofilesis effectively stale. If selection preservation isn’t needed, consider removing thefilesparameter from the helper; otherwise include dependencies and guard against loops.🔧 One possible cleanup (drops `files` param)
- const initialFiles = useMemo(() => { - return !!functionBody - ? formatFunctionBodyToFiles({ - functionBody, - entrypointPath: selectedFunction?.entrypoint_path, - files, - }) - : [] - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [isSuccessLoadingFiles]) + const initialFiles = useMemo(() => { + return functionBody + ? formatFunctionBodyToFiles({ + functionBody, + entrypointPath: selectedFunction?.entrypoint_path, + }) + : [] + }, [functionBody, selectedFunction?.entrypoint_path])
🧹 Nitpick comments (2)
apps/studio/components/ui/FileExplorerAndEditor/index.tsx (1)
394-417: Avoid castingmetadata.stateand nested ternaries in JSX.
Consider guardingmetadata.stateat runtime and computing astateClassvariable to remove the nested ternary. This reduces unsafe casts and keeps JSX simpler. As per coding guidelines, prefer runtime checks over casts and avoid nested ternaries in JSX.♻️ Example refactor
- const state = element.metadata?.state as FileData['state'] + const rawState = element.metadata?.state + const state: FileData['state'] = + rawState === 'new' || rawState === 'modified' ? rawState : 'unchanged' const isEditing = Boolean(element.metadata?.isEditing) + const stateClass = + !isEditing && state === 'new' + ? 'text-brand-600' + : !isEditing && state === 'modified' + ? 'text-code_block-2' + : '' ... - className={cn( - isEditing - ? '' - : state === 'new' - ? 'text-brand-600' - : state === 'modified' - ? 'text-code_block-2' - : '' - )} + className={cn(stateClass)}apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.ts (1)
97-105: Drop theas FileDatacast by typing the mapper return.
You can make the mapper returnFileDataexplicitly and remove the cast. As per coding guidelines, avoid type casting in favor of explicit typing or runtime checks.♻️ Example adjustment
- return filesWithRelPath.map((file: { name: string; content: string }, index: number) => { + return filesWithRelPath.map( + (file: { name: string; content: string }, index: number): FileData => { const prevState = files.find((x) => x.name === file.name) return { id: index + 1, name: file.name, content: file.content, selected: prevState?.selected ?? index === 0, state: 'unchanged', - } as FileData - }) + } + )
|
Looks like my earlier fixes to |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@apps/studio/pages/project/`[ref]/functions/[functionSlug]/code.tsx:
- Around line 83-87: The current call setFiles(files.map(...)) captures the
render-time files array and can drop concurrent edits; change it to a functional
updater so the latest state is used: replace the direct use of files in setFiles
with a functional form that maps over the previous state (referencing setFiles
and files) and sets each file's state to 'unchanged' to avoid stale-closure bugs
during in-flight deploys.
♻️ Duplicate comments (1)
apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx (1)
192-205: Rename should bemodified, notnew.A rename is still the same file (same id), so marking it as
newwill show the wrong indicator.🔧 Suggested tweak
- } else if (originalFile.name !== f.name) { - return { ...f, state: 'new' } - } else if (originalFile.content !== f.content) { + } else if ( + originalFile.name !== f.name || + originalFile.content !== f.content + ) { return { ...f, state: 'modified' } }
alaister
left a comment
There was a problem hiding this comment.
LGTM!
- Tested on preview + locally
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Fix all issues with AI agents
In `@apps/studio/pages/project/`[ref]/functions/[functionSlug]/code.tsx:
- Around line 75-83: The deploy onSuccess currently sets file states to
'unchanged' but doesn't update the unsaved-change baseline (initialFiles), so
the unload warning still triggers; in the useEdgeFunctionDeployMutation
onSuccess handler update the baseline to the deployed content by either calling
the same setter that holds initialFiles (e.g., setInitialFiles(updatedFiles)
where updatedFiles is the files array you just set to 'unchanged') or trigger a
refetch/invalidate of the edge-function query via your query client so
initialFiles is refreshed; apply the same change to the other deploy/commit
success handlers referenced around the other locations (lines ~144-147 and
~149-159) so the baseline is consistently updated after deploys.
In `@apps/studio/pages/project/`[ref]/functions/new.tsx:
- Around line 228-235: In handleTemplateMouseEnter the code assumes a
selectedFile exists and calls selectedFile.content which throws when files is
empty; add a null guard: resolve selectedFile via files.find(...) ?? files[0]
may still be undefined, so check if selectedFile is truthy before calling
setSavedCode(selectedFile.content) (or pass a safe default like an empty
string), and ensure setFiles mapping also handles when selectedFileId is
undefined (only update files when selectedFileId matches an existing file). This
prevents runtime errors when all files have been deleted.
- Around line 278-292: The beforeunload guard currently compares the live files
array to INITIAL_FILES and includes UI-only fields, causing false positives (see
handleBeforeUnload, filesRef, INITIAL_FILES, isEqual, FileData). Change it to
compare filesRef.current to a true initial snapshot captured once at mount
(store in a ref, e.g., initialSnapshotRef) and perform equality on normalized
file objects that omit UI-only fields like FileData.state (map/strip those keys
before comparing). Update the handleBeforeUnload logic to compute
hasUnsavedChanges using the normalized current files vs the normalized
initialSnapshotRef so template preloads and UI-only state do not trigger the
warning.
🧹 Nitpick comments (1)
apps/studio/data/edge-functions/edge-function-body-query.ts (1)
4-59: Prefer typed + validated multipart payloads instead ofascasting.Line 58 uses a cast that can mask malformed multipart data. Consider validating the payload (zod) and typing the array directly so the return type is inferred without
as.♻️ Suggested refactor
+import { z } from 'zod' import { FileData } from '@/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.types' @@ - const files = [] + const FilePayloadSchema = z.object({ + name: z.string(), + content: z.string(), + }) + type FilePayload = Pick<FileData, 'name' | 'content'> + const files: FilePayload[] = [] @@ - files.push({ - name: part.filename, - content: part.text, - }) + files.push( + FilePayloadSchema.parse({ + name: part.filename, + content: part.text, + }) + ) @@ - files: files as Omit<FileData, 'id' | 'selected' | 'state'>[], + files,As per coding guidelines, avoid type casting in apps/studio and prefer runtime validation.
| const { mutate: deployFunction, isPending: isDeploying } = useEdgeFunctionDeployMutation({ | ||
| onSuccess: () => { | ||
| toast.success('Successfully updated edge function') | ||
| setShowDeployWarning(false) | ||
| setFiles((files) => | ||
| files.map((f) => { | ||
| return { ...f, state: 'unchanged' } | ||
| }) | ||
| ) |
There was a problem hiding this comment.
Reset the unsaved-change baseline after a successful deploy.
After a deploy, you set state: 'unchanged', but the unsaved-change check still compares against the original initialFiles (from the first fetch). Since the query never refetches, users will continue to see the unload warning even after deploying. Update the baseline to the deployed content (or refetch).
🛠️ Suggested fix
-import { useEffect, useMemo, useState } from 'react'
+import { useEffect, useMemo, useRef, useState } from 'react'
@@
- const filesRef = useLatest(files)
- const initialFilesRef = useLatest(initialFiles)
+ const filesRef = useLatest(files)
+ const baselineFilesRef = useRef<FileData[]>([])
@@
- setFiles((files) =>
- files.map((f) => {
- return { ...f, state: 'unchanged' }
- })
- )
+ setFiles((files) => {
+ const next = files.map((f) => ({ ...f, state: 'unchanged' }))
+ baselineFilesRef.current = next
+ return next
+ })
@@
- setFiles(initialFiles)
+ setFiles(initialFiles)
+ baselineFilesRef.current = initialFiles
@@
- const hasUnsavedChanges = !isEqual(
- normalizeFiles(initialFilesRef.current),
- normalizeFiles(filesRef.current)
- )
+ const hasUnsavedChanges = !isEqual(
+ normalizeFiles(baselineFilesRef.current),
+ normalizeFiles(filesRef.current)
+ )Also applies to: 144-147, 149-159
🤖 Prompt for AI Agents
In `@apps/studio/pages/project/`[ref]/functions/[functionSlug]/code.tsx around
lines 75 - 83, The deploy onSuccess currently sets file states to 'unchanged'
but doesn't update the unsaved-change baseline (initialFiles), so the unload
warning still triggers; in the useEdgeFunctionDeployMutation onSuccess handler
update the baseline to the deployed content by either calling the same setter
that holds initialFiles (e.g., setInitialFiles(updatedFiles) where updatedFiles
is the files array you just set to 'unchanged') or trigger a refetch/invalidate
of the edge-function query via your query client so initialFiles is refreshed;
apply the same change to the other deploy/commit success handlers referenced
around the other locations (lines ~144-147 and ~149-159) so the baseline is
consistently updated after deploys.
There was a problem hiding this comment.
unsaved check no longer considers state as it's being normalized (as per your previous GH commit here)
state is a UI paramater and does not come from the API response so this is alright
There was a problem hiding this comment.
@joshenlim, thanks for the clarification! You're absolutely right that state is normalized out of the comparison—I can see the normalizeFiles function extracts only { id, name, content }.
My concern wasn't about the state field being included in the comparison, but rather about the content baseline after a deploy. Here's the scenario I'm flagging:
- User loads the page →
initialFilesis set from the API response - User edits a file →
filescontent changes - User deploys → the edited content is deployed, and
stateis reset to'unchanged' - User tries to refresh → the beforeunload handler compares:
normalizeFiles(initialFiles)← still has the original API contentnormalizeFiles(files)← now has the deployed (edited) content- These are not equal, so the warning still fires
Since the query never refetches (staleTime: Infinity, etc.), initialFiles remains stale after the deploy. If the intent is to keep warning users even after a successful deploy (until they refresh), that's totally fine! Just wanted to confirm that's the expected behavior. 🐰
🧠 Learnings used
Learnt from: joshenlim
Repo: supabase/supabase PR: 41258
File: apps/studio/pages/project/[ref]/storage/vectors/buckets/[bucketId].tsx:9-9
Timestamp: 2025-12-12T05:20:21.681Z
Learning: In apps/studio/**/*.{ts,tsx}, use named import for DefaultLayout: `import { DefaultLayout } from 'components/layouts/DefaultLayout'` instead of default import. This is the new practice being adopted across the studio app.
| const handleTemplateMouseEnter = (content: string) => { | ||
| if (!isPreviewingTemplate) { | ||
| const selectedFile = files.find((f) => f.selected) ?? files[0] | ||
| const selectedFile = files.find((f) => f.id === selectedFileId) ?? files[0] | ||
| setSavedCode(selectedFile.content) | ||
| } | ||
| setIsPreviewingTemplate(true) | ||
| setFiles((prev) => prev.map((file) => (file.selected ? { ...file, content } : file))) | ||
| setFiles((prev) => prev.map((f) => (f.id === selectedFileId ? { ...f, content } : f))) | ||
| } |
There was a problem hiding this comment.
Guard template preview when no files exist.
If the user deletes all files, selectedFile can be undefined, and Line 231 will throw. Add a null guard before accessing .content.
🐛 Suggested fix
- const selectedFile = files.find((f) => f.id === selectedFileId) ?? files[0]
- setSavedCode(selectedFile.content)
+ const selectedFile = files.find((f) => f.id === selectedFileId) ?? files[0]
+ if (!selectedFile) return
+ setSavedCode(selectedFile.content)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const handleTemplateMouseEnter = (content: string) => { | |
| if (!isPreviewingTemplate) { | |
| const selectedFile = files.find((f) => f.selected) ?? files[0] | |
| const selectedFile = files.find((f) => f.id === selectedFileId) ?? files[0] | |
| setSavedCode(selectedFile.content) | |
| } | |
| setIsPreviewingTemplate(true) | |
| setFiles((prev) => prev.map((file) => (file.selected ? { ...file, content } : file))) | |
| setFiles((prev) => prev.map((f) => (f.id === selectedFileId ? { ...f, content } : f))) | |
| } | |
| const handleTemplateMouseEnter = (content: string) => { | |
| if (!isPreviewingTemplate) { | |
| const selectedFile = files.find((f) => f.id === selectedFileId) ?? files[0] | |
| if (!selectedFile) return | |
| setSavedCode(selectedFile.content) | |
| } | |
| setIsPreviewingTemplate(true) | |
| setFiles((prev) => prev.map((f) => (f.id === selectedFileId ? { ...f, content } : f))) | |
| } |
🤖 Prompt for AI Agents
In `@apps/studio/pages/project/`[ref]/functions/new.tsx around lines 228 - 235, In
handleTemplateMouseEnter the code assumes a selectedFile exists and calls
selectedFile.content which throws when files is empty; add a null guard: resolve
selectedFile via files.find(...) ?? files[0] may still be undefined, so check if
selectedFile is truthy before calling setSavedCode(selectedFile.content) (or
pass a safe default like an empty string), and ensure setFiles mapping also
handles when selectedFileId is undefined (only update files when selectedFileId
matches an existing file). This prevents runtime errors when all files have been
deleted.
There was a problem hiding this comment.
that's alright - we don't support deleting the only file left in the UI
There was a problem hiding this comment.
@joshenlim, got it! Thanks for clarifying—I wasn't aware of that UI constraint. The code is safe as-is. 👍
/>\_/\
( •.• )
/>📝 Noted!
✏️ Learnings added
Learnt from: joshenlim
Repo: supabase/supabase PR: 41921
File: apps/studio/pages/project/[ref]/functions/new.tsx:228-235
Timestamp: 2026-01-21T12:38:55.311Z
Learning: In `apps/studio/pages/project/[ref]/functions/new.tsx` and the FileExplorerAndEditor component, the UI prevents deletion of the last remaining file, so handlers like `handleTemplateMouseEnter` do not need guards against empty file arrays.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
🧠 Learnings used
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/studio-ui.mdc:0-0
Timestamp: 2025-12-11T17:04:40.037Z
Learning: Applies to apps/studio/components/interfaces/**/*.{ts,tsx} : Create a new component in apps/studio/components/interfaces for the contents of each new page
Learnt from: CR
Repo: supabase/supabase PR: 0
File: .cursor/rules/e2e-testing.mdc:0-0
Timestamp: 2025-12-11T16:46:03.692Z
Learning: Applies to e2e/studio/**/*.{ts,spec.ts} : Check if test data exists before attempting to delete it to handle existing state gracefully
Learnt from: joshenlim
Repo: supabase/supabase PR: 41258
File: apps/studio/pages/project/[ref]/storage/vectors/buckets/[bucketId].tsx:9-9
Timestamp: 2025-12-12T05:20:21.681Z
Learning: In apps/studio/**/*.{ts,tsx}, use named import for DefaultLayout: `import { DefaultLayout } from 'components/layouts/DefaultLayout'` instead of default import. This is the new practice being adopted across the studio app.
| // [Joshen] Probably a candidate for useStaticEffectEvent | ||
| const filesRef = useLatest(files) | ||
| useEffect(() => { | ||
| const handleBeforeUnload = (e: BeforeUnloadEvent) => { | ||
| const hasUnsavedChanges = !isEqual(INITIAL_FILES, filesRef.current) | ||
|
|
||
| if (hasUnsavedChanges) { | ||
| e.preventDefault() | ||
| e.returnValue = '' // deprecated, but older browsers still require this | ||
| } | ||
| } | ||
| window.addEventListener('beforeunload', handleBeforeUnload) | ||
| return () => window.removeEventListener('beforeunload', handleBeforeUnload) | ||
| // eslint-disable-next-line react-hooks/exhaustive-deps | ||
| }, []) |
There was a problem hiding this comment.
Unsaved-change guard should compare against the real initial snapshot and ignore UI-only fields.
Line 282 compares to INITIAL_FILES, which can be wrong when a template query param preloads different content. It also compares full FileData objects, so UI-only state changes can trigger a warning.
🛠️ Suggested fix
-import { useEffect, useMemo, useState } from 'react'
+import { useEffect, useMemo, useRef, useState } from 'react'
@@
+ const initialFilesRef = useRef(INITIAL_FILES)
@@
- setFiles([
+ const nextFiles = [
{
id: 1,
name: 'index.ts',
content: templateMeta.content,
state: 'new',
},
- ])
+ ]
+ setFiles(nextFiles)
+ initialFilesRef.current = nextFiles
@@
- const hasUnsavedChanges = !isEqual(INITIAL_FILES, filesRef.current)
+ const normalizeFiles = (list: FileData[]) =>
+ list.map(({ id, name, content }) => ({ id, name, content }))
+ const hasUnsavedChanges = !isEqual(
+ normalizeFiles(initialFilesRef.current),
+ normalizeFiles(filesRef.current)
+ )🤖 Prompt for AI Agents
In `@apps/studio/pages/project/`[ref]/functions/new.tsx around lines 278 - 292,
The beforeunload guard currently compares the live files array to INITIAL_FILES
and includes UI-only fields, causing false positives (see handleBeforeUnload,
filesRef, INITIAL_FILES, isEqual, FileData). Change it to compare
filesRef.current to a true initial snapshot captured once at mount (store in a
ref, e.g., initialSnapshotRef) and perform equality on normalized file objects
that omit UI-only fields like FileData.state (map/strip those keys before
comparing). Update the handleBeforeUnload logic to compute hasUnsavedChanges
using the normalized current files vs the normalized initialSnapshotRef so
template preloads and UI-only state do not trigger the warning.
Braintrust eval report
|
Context
There's 2 UX footguns in the dashboard for Edge Functions at the moment
index.ts) will be omitted from the bundle and hence not persistedChanges in this PR aims to address just the latter issue (The unimported files we'll investigate in the future again, as I can't really figure out a fool proof way to check for unimported files and float a warning)
Changes involved
Summary by CodeRabbit
New Features
Improvements
✏️ Tip: You can customize this high-level summary in your review settings.