Skip to content

Add UX guardrails for edge functions RE unsaved and unimported files - #41921

Merged
joshenlim merged 15 commits into
masterfrom
joshen/fe-2358-new-edge-function-file-disappears-after-deploy-in-dashboard
Jan 22, 2026
Merged

joshenlim merged 15 commits into
masterfrom
joshen/fe-2358-new-edge-function-file-disappears-after-deploy-in-dashboard

Conversation

@joshenlim

@joshenlim joshenlim commented Jan 15, 2026 •

Copy link
Copy Markdown
Member

Context

There's 2 UX footguns in the dashboard for Edge Functions at the moment

  • Unimported files (through index.ts) will be omitted from the bundle and hence not persisted
    • It's a Deno behaviour and not really known amongst our users
  • Unsaved changes will be lost if you refresh the page

Changes 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

  • Show native browser "Reload site" warning when attempting to refresh the page when there's unsaved changes (Similar to Auth templates)
    image
  • Add VScode like indicators for new + modified files
    • image
    • image

Summary by CodeRabbit

  • New Features

    • Per-file state tracking (new / modified / unchanged) with visual indicators and tooltips
    • Optional right-side actions on tree items
    • External-controlled file selection for editor/file list
  • Improvements

    • Unsaved-changes warning on navigation and deploy; deploy resets per-file state
    • Better initialization and preservation of file selection and file states when loading remote functions or applying templates
    • Endpoint input is read-only (copyable) with layout tweaks

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

@joshenlim
joshenlim requested a review from a team as a code owner January 15, 2026 09:14
@vercel

vercel Bot commented Jan 15, 2026 •

Copy link
Copy Markdown

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

Project Deployment Review Updated (UTC)
studio-self-hosted Ready Ready Preview, Comment Jan 21, 2026 8:28am
studio-staging Ready Ready Preview, Comment Jan 21, 2026 8:28am
6 Skipped Deployments
Project Deployment Review Updated (UTC)
cms Ignored Ignored Jan 21, 2026 8:28am
studio Ignored Ignored Jan 21, 2026 8:28am
design-system Skipped Skipped Jan 21, 2026 8:28am
docs Skipped Skipped Jan 21, 2026 8:28am
ui-library Skipped Skipped Jan 21, 2026 8:28am
zone-www-dot-com Skipped Skipped Jan 21, 2026 8:28am

Request Review

@supabase

supabase Bot commented Jan 15, 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 Jan 15, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

Replaces 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

Cohort / File(s) Summary
Type System Migration
apps/studio/components/interfaces/EdgeFunctions/EdgeFunction.types.ts, apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.types.ts
Removed EdgeFunctionFile; extended FileData with `state: 'new'
Utilities & Normalization
apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.ts
Switched utils to FileData; added getBasePath() and exported formatFunctionBodyToFiles() to convert EdgeFunctionBodyData into normalized FileData[] with relative names and states; updated path imports.
Pages: Code & New Function
apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx, apps/studio/pages/project/[ref]/functions/new.tsx
Files state changed to FileData[]; initialize via formatFunctionBodyToFiles()/INITIAL_FILES; detect unsaved changes using isEqual; add beforeunload guard via useLatest; controlled selection via selectedFileId; DefaultLayout import adjusted.
File Explorer & Editor
apps/studio/components/ui/FileExplorerAndEditor/index.tsx
Threaded state into tree nodes (TreeChildData), preserve state across edits/drops/renames/zip extraction; selection controlled via optional selectedFileId/setSelectedFileId; UI shows per-item state indicators and modified styling.
Data Layer
apps/studio/data/edge-functions/edge-function-body-query.ts
Return typing updated to use FileData for returned files; EdgeFunctionBodyData files now reflect FileData shape.
TreeView Action Support
packages/ui/src/components/TreeView/TreeView.tsx
Added optional actions?: ReactNode prop to TreeViewItem; adjusted item layout to render right-aligned actions while preserving edit behavior.
Minor UI Adjustments
apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
Small import and layout/input tweaks (readOnly endpoint input, Input import path, AlertError now named import).

Sequence Diagram

sequenceDiagram
    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
Loading

Suggested reviewers

  • dnywh
  • awaseem
  • SaxonF
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main changes: adding UX safeguards (unsaved change warnings and file state indicators) for edge functions, which matches the PR's primary objectives.
Description check ✅ Passed The description follows the template with all major sections completed: context provided, current behavior explained, new behavior with visual examples shown, and additional context included.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

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 and usage tips.

@coveralls

coveralls commented Jan 15, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 66.113%. remained the same
when pulling f5653d3 on joshen/fe-2358-new-edge-function-file-disappears-after-deploy-in-dashboard
into 1db3da7 on master.

@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: 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 initialFiles changes, but initialFiles is a new array reference each time isSuccessLoadingFiles transitions to true. If this effect triggers and setFiles(initialFiles) causes a re-render, the memo would need to be stable to avoid loops.

Currently this works because isSuccessLoadingFiles only 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

📥 Commits

Reviewing files that changed from the base of the PR and between 167ad55 and 0ff8201.

📒 Files selected for processing (4)
  • apps/studio/components/interfaces/EdgeFunctions/DeployEdgeFunctionWarningModal.tsx
  • apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.ts
  • apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx
  • apps/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: 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/EdgeFunctions/DeployEdgeFunctionWarningModal.tsx
  • apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.ts
  • apps/studio/pages/project/[ref]/functions/new.tsx
  • apps/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: use on prefix for prop callbacks and handle 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/EdgeFunctions/DeployEdgeFunctionWarningModal.tsx
  • apps/studio/pages/project/[ref]/functions/new.tsx
  • apps/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.tsx
  • apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.ts
  • apps/studio/pages/project/[ref]/functions/new.tsx
  • apps/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.tsx
  • apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.ts
  • apps/studio/pages/project/[ref]/functions/new.tsx
  • apps/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.ts
  • apps/studio/pages/project/[ref]/functions/new.tsx
  • apps/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.tsx
  • 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 : 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 getBasePath helper 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 legacy returnValue for cross-browser compatibility.


112-119: Fix hasUnsavedChanges comparison to account for template URL parameter initialization.

hasUnsavedChanges compares against a fixed INITIAL_FILES constant (which always has 'hello-world' template content), but the actual initial state can differ when a template URL parameter is provided. When users load the page with ?template=stripe-webhook (or another template), the template effect (lines 266-282) correctly updates files with that template's content. However, hasUnsavedChanges will incorrectly report true even if the user makes no edits, because it compares the template-loaded content against the hardcoded hello-world INITIAL_FILES.

Store the actual initial file state after template initialization completes, or compare files against 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 whether INITIAL_FILES should 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 DeployEdgeFunctionWarningModal is correctly wired with the unimportedFiles prop to display the appropriate warning.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

@github-actions

github-actions Bot commented Jan 15, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results

passed  69 passed
flaky  1 flaky
skipped  4 skipped

Details

stats  74 tests across 12 suites
duration  9 minutes, 16 seconds
commit  f5653d3

Flaky tests

Features › sql-editor.spec.ts › SQL Editor › should check if SQL editor is working 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

@joshenlim
joshenlim requested review from a team as code owners January 20, 2026 12:55
@github-actions github-actions Bot added the documentation Improvements or additions to documentation label Jan 20, 2026
@joshenlim
joshenlim force-pushed the joshen/fe-2358-new-edge-function-file-disappears-after-deploy-in-dashboard branch from b727e89 to 08b81e3 Compare January 20, 2026 13:01

@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: 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: Duplicate refetchOnMount option.

refetchOnMount: false appears 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: handleStartRename incorrectly sets state: '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: The files parameter in formatFunctionBodyToFiles appears unused based on the memoization.

The eslint-disable suppresses the exhaustive-deps warning, but when isSuccessLoadingFiles first becomes true, files is still [] (initial state). This means the files.find() lookup inside formatFunctionBodyToFiles will never find matches on initial load.

If the intent is to always derive initialFiles fresh from the API response (which the query config with staleTime: Infinity suggests), consider removing the files parameter from formatFunctionBodyToFiles. 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 the onFilesChange handler.

Per coding guidelines, inline arrow functions passed to props should be avoided when they perform non-trivial logic. This handler compares against initialFiles on 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'

@coderabbitai coderabbitai Bot Jan 20, 2026 •

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.

⚠️ Potential issue | 🟡 Minor

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:

  1. Making state optional: state?: 'new' | 'modified' | 'unchanged'
  2. 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think option 2 here right?

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.

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

  1. API response → Omit<FileData, 'id' | 'selected' | 'state'>[] (no state yet)
  2. formatFunctionBodyToFiles → FileData[] (state added)
  3. 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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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: The files parameter issue persists — still passed to formatFunctionBodyToFiles but excluded from dependencies.

This was flagged in a previous review and marked as addressed, but the same pattern remains: files is captured in the closure (line 71) yet excluded from the dependency array with an eslint-disable comment.

When isSuccessLoadingFiles becomes true and this memo runs, files is always [] (the initial state from line 64). The files.find() call inside formatFunctionBodyToFiles (per the utility at EdgeFunctions.utils.ts:100) will never find a match, making the files parameter 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 files parameter from the call and update formatFunctionBodyToFiles accordingly.

apps/studio/pages/project/[ref]/functions/new.tsx (1)

433-447: Critical: AlertDialogAction is still missing its onClick handler.

This issue was previously flagged and marked as addressed, but the "Deploy function" button still has no onClick handler. 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 extracting onFilesChange handler with useCallback.

This inline arrow function performs non-trivial work (mapping, finding original files, computing state). Per coding guidelines, extracting it with useCallback would provide a stable reference if FileExplorerAndEditor is 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)

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.

⚠️ Potential issue | 🔴 Critical

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:

  1. Before deploy, detect files not imported through index.ts
  2. If unimported files exist, call setShowWarning(true) to show the warning
  3. 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 charislam 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.

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

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.

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>

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.

Just pushed up this className="text-xs" so it isn’t so large. Matches VSCode.

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

Tested on staging and locally. Made one minor text size change on the M and U. Looks good!

@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: 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.
hasUnsavedChanges compares against the static INITIAL_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, comparing selected/state can introduce false positives. Consider tracking an initialFiles state 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 as new.
handleStartRename sets state: '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 to file.name mutates 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: initialFiles memo uses stale dependencies.
functionBody, selectedFunction?.entrypoint_path, and files are referenced but only isSuccessLoadingFiles is in the dependency list (with lint suppressed), so files is effectively stale. If selection preservation isn’t needed, consider removing the files parameter 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 casting metadata.state and nested ternaries in JSX.
Consider guarding metadata.state at runtime and computing a stateClass variable 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 the as FileData cast by typing the mapper return.
You can make the mapper return FileData explicitly 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
-    })
+      }
+    )

@dnywh

dnywh commented Jan 21, 2026

Copy link
Copy Markdown
Contributor

Looks like my earlier fixes to EdgeFunctionDetails have clashed with this work. Sorry. See conflicts.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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 be modified, not new.

A rename is still the same file (same id), so marking it as new will 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 alaister left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM!

  • Tested on preview + locally

@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

🤖 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 of as casting.

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.

Comment on lines 75 to +83
const { mutate: deployFunction, isPending: isDeploying } = useEdgeFunctionDeployMutation({
onSuccess: () => {
toast.success('Successfully updated edge function')
setShowDeployWarning(false)
setFiles((files) =>
files.map((f) => {
return { ...f, state: 'unchanged' }
})
)

@coderabbitai coderabbitai Bot Jan 21, 2026 •

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.

⚠️ Potential issue | 🟠 Major

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

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.

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

  1. User loads the page → initialFiles is set from the API response
  2. User edits a file → files content changes
  3. User deploys → the edited content is deployed, and state is reset to 'unchanged'
  4. User tries to refresh → the beforeunload handler compares:
    • normalizeFiles(initialFiles) ← still has the original API content
    • normalizeFiles(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.

Comment on lines 228 to 235
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)))
}

@coderabbitai coderabbitai Bot Jan 21, 2026 •

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.

⚠️ Potential issue | 🟡 Minor

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.

Suggested change
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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

that's alright - we don't support deleting the only file left in the UI

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.

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

Comment on lines +278 to +292
// [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
}, [])

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.

⚠️ Potential issue | 🟡 Minor

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.

@joshenlim
joshenlim merged commit f293036 into master Jan 22, 2026
17 checks passed
@joshenlim
joshenlim deleted the joshen/fe-2358-new-edge-function-file-disappears-after-deploy-in-dashboard branch January 22, 2026 05:31
@github-actions

github-actions Bot commented Jan 22, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (master-1769060007)

Score Average Improvements Regressions
Completeness 100% (+0pp) - -
Conciseness 0% (+0pp) - -
Docs Faithfulness 40% (-22pp) - 1 🔴
Goal Completion 87.5% (+0pp) - -
Tool Usage 75% (+0pp) - -
Correctness 100% (+0pp) - -
SQL Validity 100% (+0pp) - -
Time_to_first_token 0.24tok (+0.07tok) 1 🟢 7 🔴
Llm_calls 8.25 (+0.13) 1 🟢 1 🔴
Tool_calls 2.88 (+0) 1 🟢 1 🔴
Errors 0 (+0) - -
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 85350.5tok (-15891.25tok) 5 🟢 2 🔴
Prompt_cached_tokens 46976tok (+5568tok) 2 🟢 3 🔴
Prompt_cache_creation_tokens 0tok (+0tok) - -
Completion_tokens 5551tok (+629.5tok) 2 🟢 6 🔴
Completion_reasoning_tokens 4144tok (+896tok) 2 🟢 6 🔴
Completion_accepted_prediction_tokens 0tok (+0tok) - -
Completion_rejected_prediction_tokens 0tok (+0tok) - -
Completion_audio_tokens 0tok (+0tok) - -
Total_tokens 90901.5tok (-15261.75tok) 4 🟢 4 🔴
Estimated_cost 0.02$ (0$) 4 🟢 4 🔴
Duration 47.07s (+11.86s) 1 🟢 7 🔴
Llm_duration 93.23s (+23.61s) 1 🟢 7 🔴

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

Labels

documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants